OSDN Git Service

* gcc.dg/dfp/operandor-conf.c: Call init, fix typo.
[pf3gnuchains/gcc-fork.git] / libgfortran / io / unix.c
1 /* Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007
2    Free Software Foundation, Inc.
3    Contributed by Andy Vaught
4
5 This file is part of the GNU Fortran 95 runtime library (libgfortran).
6
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.
11
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.)
20
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.
25
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.  */
30
31 /* Unix stream I/O module */
32
33 #include "config.h"
34 #include <stdlib.h>
35 #include <limits.h>
36
37 #include <unistd.h>
38 #include <stdio.h>
39 #include <stdarg.h>
40 #include <sys/stat.h>
41 #include <fcntl.h>
42 #include <assert.h>
43
44 #include <string.h>
45 #include <errno.h>
46
47 #include "libgfortran.h"
48 #include "io.h"
49
50 #ifndef SSIZE_MAX
51 #define SSIZE_MAX SHRT_MAX
52 #endif
53
54 #ifndef PATH_MAX
55 #define PATH_MAX 1024
56 #endif
57
58 #ifndef PROT_READ
59 #define PROT_READ 1
60 #endif
61
62 #ifndef PROT_WRITE
63 #define PROT_WRITE 2
64 #endif
65
66 /* These flags aren't defined on all targets (mingw32), so provide them
67    here.  */
68 #ifndef S_IRGRP
69 #define S_IRGRP 0
70 #endif
71
72 #ifndef S_IWGRP
73 #define S_IWGRP 0
74 #endif
75
76 #ifndef S_IROTH
77 #define S_IROTH 0
78 #endif
79
80 #ifndef S_IWOTH
81 #define S_IWOTH 0
82 #endif
83
84
85 /* Unix stream I/O module */
86
87 #define BUFFER_SIZE 8192
88
89 typedef struct
90 {
91   stream st;
92
93   int fd;
94   gfc_offset buffer_offset;     /* File offset of the start of the buffer */
95   gfc_offset physical_offset;   /* Current physical file offset */
96   gfc_offset logical_offset;    /* Current logical file offset */
97   gfc_offset dirty_offset;      /* Start of modified bytes in buffer */
98   gfc_offset file_length;       /* Length of the file, -1 if not seekable. */
99
100   char *buffer;
101   int len;                      /* Physical length of the current buffer */
102   int active;                   /* Length of valid bytes in the buffer */
103
104   int prot;
105   int ndirty;                   /* Dirty bytes starting at dirty_offset */
106
107   int special_file;             /* =1 if the fd refers to a special file */
108
109   unsigned unbuffered:1;
110
111   char small_buffer[BUFFER_SIZE];
112
113 }
114 unix_stream;
115
116 extern stream *init_error_stream (unix_stream *);
117 internal_proto(init_error_stream);
118
119
120 /* This implementation of stream I/O is based on the paper:
121  *
122  *  "Exploiting the advantages of mapped files for stream I/O",
123  *  O. Krieger, M. Stumm and R. Umrau, "Proceedings of the 1992 Winter
124  *  USENIX conference", p. 27-42.
125  *
126  * It differs in a number of ways from the version described in the
127  * paper.  First of all, threads are not an issue during I/O and we
128  * also don't have to worry about having multiple regions, since
129  * fortran's I/O model only allows you to be one place at a time.
130  *
131  * On the other hand, we have to be able to writing at the end of a
132  * stream, read from the start of a stream or read and write blocks of
133  * bytes from an arbitrary position.  After opening a file, a pointer
134  * to a stream structure is returned, which is used to handle file
135  * accesses until the file is closed.
136  *
137  * salloc_at_r(stream, len, where)-- Given a stream pointer, return a
138  * pointer to a block of memory that mirror the file at position
139  * 'where' that is 'len' bytes long.  The len integer is updated to
140  * reflect how many bytes were actually read.  The only reason for a
141  * short read is end of file.  The file pointer is updated.  The
142  * pointer is valid until the next call to salloc_*.
143  *
144  * salloc_at_w(stream, len, where)-- Given the stream pointer, returns
145  * a pointer to a block of memory that is updated to reflect the state
146  * of the file.  The length of the buffer is always equal to that
147  * requested.  The buffer must be completely set by the caller.  When
148  * data has been written, the sfree() function must be called to
149  * indicate that the caller is done writing data to the buffer.  This
150  * may or may not cause a physical write.
151  *
152  * Short forms of these are salloc_r() and salloc_w() which drop the
153  * 'where' parameter and use the current file pointer. */
154
155
156 /*move_pos_offset()--  Move the record pointer right or left
157  *relative to current position */
158
159 int
160 move_pos_offset (stream* st, int pos_off)
161 {
162   unix_stream * str = (unix_stream*)st;
163   if (pos_off < 0)
164     {
165       str->logical_offset += pos_off;
166
167       if (str->dirty_offset + str->ndirty > str->logical_offset)
168         {
169           if (str->ndirty + pos_off > 0)
170             str->ndirty += pos_off;
171           else
172             {
173               str->dirty_offset +=  pos_off + pos_off;
174               str->ndirty = 0;
175             }
176         }
177
178     return pos_off;
179   }
180   return 0;
181 }
182
183
184 /* fix_fd()-- Given a file descriptor, make sure it is not one of the
185  * standard descriptors, returning a non-standard descriptor.  If the
186  * user specifies that system errors should go to standard output,
187  * then closes standard output, we don't want the system errors to a
188  * file that has been given file descriptor 1 or 0.  We want to send
189  * the error to the invalid descriptor. */
190
191 static int
192 fix_fd (int fd)
193 {
194   int input, output, error;
195
196   input = output = error = 0;
197
198   /* Unix allocates the lowest descriptors first, so a loop is not
199      required, but this order is. */
200
201   if (fd == STDIN_FILENO)
202     {
203       fd = dup (fd);
204       input = 1;
205     }
206   if (fd == STDOUT_FILENO)
207     {
208       fd = dup (fd);
209       output = 1;
210     }
211   if (fd == STDERR_FILENO)
212     {
213       fd = dup (fd);
214       error = 1;
215     }
216
217   if (input)
218     close (STDIN_FILENO);
219   if (output)
220     close (STDOUT_FILENO);
221   if (error)
222     close (STDERR_FILENO);
223
224   return fd;
225 }
226
227 int
228 is_preconnected (stream * s)
229 {
230   int fd;
231
232   fd = ((unix_stream *) s)->fd;
233   if (fd == STDIN_FILENO || fd == STDOUT_FILENO || fd == STDERR_FILENO)
234     return 1;
235   else
236     return 0;
237 }
238
239 /* If the stream corresponds to a preconnected unit, we flush the
240    corresponding C stream.  This is bugware for mixed C-Fortran codes
241    where the C code doesn't flush I/O before returning.  */
242 void
243 flush_if_preconnected (stream * s)
244 {
245   int fd;
246
247   fd = ((unix_stream *) s)->fd;
248   if (fd == STDIN_FILENO)
249     fflush (stdin);
250   else if (fd == STDOUT_FILENO)
251     fflush (stdout);
252   else if (fd == STDERR_FILENO)
253     fflush (stderr);
254 }
255
256
257 /* Reset a stream after reading/writing. Assumes that the buffers have
258    been flushed.  */
259
260 inline static void
261 reset_stream (unix_stream * s, size_t bytes_rw)
262 {
263   s->physical_offset += bytes_rw;
264   s->logical_offset = s->physical_offset;
265   if (s->file_length != -1 && s->physical_offset > s->file_length)
266     s->file_length = s->physical_offset;
267 }
268
269
270 /* Read bytes into a buffer, allowing for short reads.  If the nbytes
271  * argument is less on return than on entry, it is because we've hit
272  * the end of file. */
273
274 static int
275 do_read (unix_stream * s, void * buf, size_t * nbytes)
276 {
277   ssize_t trans;
278   size_t bytes_left;
279   char *buf_st;
280   int status;
281
282   status = 0;
283   bytes_left = *nbytes;
284   buf_st = (char *) buf;
285
286   /* We must read in a loop since some systems don't restart system
287      calls in case of a signal.  */
288   while (bytes_left > 0)
289     {
290       /* Requests between SSIZE_MAX and SIZE_MAX are undefined by SUSv3,
291          so we must read in chunks smaller than SSIZE_MAX.  */
292       trans = (bytes_left < SSIZE_MAX) ? bytes_left : SSIZE_MAX;
293       trans = read (s->fd, buf_st, trans);
294       if (trans < 0)
295         {
296           if (errno == EINTR)
297             continue;
298           else
299             {
300               status = errno;
301               break;
302             }
303         }
304       else if (trans == 0) /* We hit EOF.  */
305         break;
306       buf_st += trans;
307       bytes_left -= trans;
308     }
309
310   *nbytes -= bytes_left;
311   return status;
312 }
313
314
315 /* Write a buffer to a stream, allowing for short writes.  */
316
317 static int
318 do_write (unix_stream * s, const void * buf, size_t * nbytes)
319 {
320   ssize_t trans;
321   size_t bytes_left;
322   char *buf_st;
323   int status;
324
325   status = 0;
326   bytes_left = *nbytes;
327   buf_st = (char *) buf;
328
329   /* We must write in a loop since some systems don't restart system
330      calls in case of a signal.  */
331   while (bytes_left > 0)
332     {
333       /* Requests between SSIZE_MAX and SIZE_MAX are undefined by SUSv3,
334          so we must write in chunks smaller than SSIZE_MAX.  */
335       trans = (bytes_left < SSIZE_MAX) ? bytes_left : SSIZE_MAX;
336       trans = write (s->fd, buf_st, trans);
337       if (trans < 0)
338         {
339           if (errno == EINTR)
340             continue;
341           else
342             {
343               status = errno;
344               break;
345             }
346         }
347       buf_st += trans;
348       bytes_left -= trans;
349     }
350
351   *nbytes -= bytes_left;
352   return status;
353 }
354
355
356 /* get_oserror()-- Get the most recent operating system error.  For
357  * unix, this is errno. */
358
359 const char *
360 get_oserror (void)
361 {
362   return strerror (errno);
363 }
364
365
366 /*********************************************************************
367     File descriptor stream functions
368 *********************************************************************/
369
370
371 /* fd_flush()-- Write bytes that need to be written */
372
373 static try
374 fd_flush (unix_stream * s)
375 {
376   size_t writelen;
377
378   if (s->ndirty == 0)
379     return SUCCESS;
380   
381   if (s->file_length != -1 && s->physical_offset != s->dirty_offset &&
382       lseek (s->fd, s->dirty_offset, SEEK_SET) < 0)
383     return FAILURE;
384
385   writelen = s->ndirty;
386   if (do_write (s, s->buffer + (s->dirty_offset - s->buffer_offset),
387                 &writelen) != 0)
388     return FAILURE;
389
390   s->physical_offset = s->dirty_offset + writelen;
391
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; 
395
396   s->ndirty -= writelen;
397   if (s->ndirty != 0)
398     return FAILURE;
399
400   return SUCCESS;
401 }
402
403
404 /* fd_alloc()-- Arrange a buffer such that the salloc() request can be
405  * satisfied.  This subroutine gets the buffer ready for whatever is
406  * to come next. */
407
408 static void
409 fd_alloc (unix_stream * s, gfc_offset where,
410           int *len __attribute__ ((unused)))
411 {
412   char *new_buffer;
413   int n, read_len;
414
415   if (*len <= BUFFER_SIZE)
416     {
417       new_buffer = s->small_buffer;
418       read_len = BUFFER_SIZE;
419     }
420   else
421     {
422       new_buffer = get_mem (*len);
423       read_len = *len;
424     }
425
426   /* Salvage bytes currently within the buffer.  This is important for
427    * devices that cannot seek. */
428
429   if (s->buffer != NULL && s->buffer_offset <= where &&
430       where <= s->buffer_offset + s->active)
431     {
432
433       n = s->active - (where - s->buffer_offset);
434       memmove (new_buffer, s->buffer + (where - s->buffer_offset), n);
435
436       s->active = n;
437     }
438   else
439     {                           /* new buffer starts off empty */
440       s->active = 0;
441     }
442
443   s->buffer_offset = where;
444
445   /* free the old buffer if necessary */
446
447   if (s->buffer != NULL && s->buffer != s->small_buffer)
448     free_mem (s->buffer);
449
450   s->buffer = new_buffer;
451   s->len = read_len;
452 }
453
454
455 /* fd_alloc_r_at()-- Allocate a stream buffer for reading.  Either
456  * we've already buffered the data or we need to load it.  Returns
457  * NULL on I/O error. */
458
459 static char *
460 fd_alloc_r_at (unix_stream * s, int *len, gfc_offset where)
461 {
462   gfc_offset m;
463
464   if (where == -1)
465     where = s->logical_offset;
466
467   if (s->buffer != NULL && s->buffer_offset <= where &&
468       where + *len <= s->buffer_offset + s->active)
469     {
470
471       /* Return a position within the current buffer */
472
473       s->logical_offset = where + *len;
474       return s->buffer + where - s->buffer_offset;
475     }
476
477   fd_alloc (s, where, len);
478
479   m = where + s->active;
480
481   if (s->physical_offset != m && lseek (s->fd, m, SEEK_SET) < 0)
482     return NULL;
483
484   /* do_read() hangs on read from terminals for *BSD-systems.  Only
485      use read() in that case.  */
486
487   if (s->special_file)
488     {
489       ssize_t n;
490
491       n = read (s->fd, s->buffer + s->active, s->len - s->active);
492       if (n < 0)
493         return NULL;
494
495       s->physical_offset = where + n;
496       s->active += n;
497     }
498   else
499     {
500       size_t n;
501
502       n = s->len - s->active;
503       if (do_read (s, s->buffer + s->active, &n) != 0)
504         return NULL;
505
506       s->physical_offset = where + n;
507       s->active += n;
508     }
509
510   if (s->active < *len)
511     *len = s->active;           /* Bytes actually available */
512
513   s->logical_offset = where + *len;
514
515   return s->buffer;
516 }
517
518
519 /* fd_alloc_w_at()-- Allocate a stream buffer for writing.  Either
520  * we've already buffered the data or we need to load it. */
521
522 static char *
523 fd_alloc_w_at (unix_stream * s, int *len, gfc_offset where)
524 {
525   gfc_offset n;
526
527   if (where == -1)
528     where = s->logical_offset;
529
530   if (s->buffer == NULL || s->buffer_offset > where ||
531       where + *len > s->buffer_offset + s->len)
532     {
533
534       if (fd_flush (s) == FAILURE)
535         return NULL;
536       fd_alloc (s, where, len);
537     }
538
539   /* Return a position within the current buffer */
540   if (s->ndirty == 0 
541       || where > s->dirty_offset + s->ndirty    
542       || s->dirty_offset > where + *len)
543     {  /* Discontiguous blocks, start with a clean buffer.  */  
544         /* Flush the buffer.  */  
545        if (s->ndirty != 0)    
546          fd_flush (s);  
547        s->dirty_offset = where;  
548        s->ndirty = *len;
549     }
550   else
551     {  
552       gfc_offset start;  /* Merge with the existing data.  */  
553       if (where < s->dirty_offset)    
554         start = where;  
555       else    
556         start = s->dirty_offset;  
557       if (where + *len > s->dirty_offset + s->ndirty)    
558         s->ndirty = where + *len - start;  
559       else    
560         s->ndirty = s->dirty_offset + s->ndirty - start;  
561         s->dirty_offset = start;
562     }
563
564   s->logical_offset = where + *len;
565
566   /* Don't increment file_length if the file is non-seekable.  */
567
568   if (s->file_length != -1 && s->logical_offset > s->file_length)
569      s->file_length = s->logical_offset;
570
571   n = s->logical_offset - s->buffer_offset;
572   if (n > s->active)
573     s->active = n;
574
575   return s->buffer + where - s->buffer_offset;
576 }
577
578
579 static try
580 fd_sfree (unix_stream * s)
581 {
582   if (s->ndirty != 0 &&
583       (s->buffer != s->small_buffer || options.all_unbuffered ||
584        s->unbuffered))
585     return fd_flush (s);
586
587   return SUCCESS;
588 }
589
590
591 static try
592 fd_seek (unix_stream * s, gfc_offset offset)
593 {
594
595   if (s->file_length == -1)
596     return SUCCESS;
597
598   if (s->physical_offset == offset) /* Are we lucky and avoid syscall?  */
599     {
600       s->logical_offset = offset;
601       return SUCCESS;
602     }
603
604   s->physical_offset = s->logical_offset = offset;
605   s->active = 0;
606
607   return (lseek (s->fd, offset, SEEK_SET) < 0) ? FAILURE : SUCCESS;
608 }
609
610
611 /* truncate_file()-- Given a unit, truncate the file at the current
612  * position.  Sets the physical location to the new end of the file.
613  * Returns nonzero on error. */
614
615 static try
616 fd_truncate (unix_stream * s)
617 {
618   /* Non-seekable files, like terminals and fifo's fail the lseek so just
619      return success, there is nothing to truncate.  If its not a pipe there
620      is a real problem.  */
621   if (lseek (s->fd, s->logical_offset, SEEK_SET) == -1)
622     {
623       if (errno == ESPIPE)
624         return SUCCESS;
625       else
626         return FAILURE;
627     }
628
629   /* Using ftruncate on a seekable special file (like /dev/null)
630      is undefined, so we treat it as if the ftruncate succeeded.  */
631 #ifdef HAVE_FTRUNCATE
632   if (s->special_file || ftruncate (s->fd, s->logical_offset))
633 #else
634 #ifdef HAVE_CHSIZE
635   if (s->special_file || chsize (s->fd, s->logical_offset))
636 #endif
637 #endif
638     {
639       s->physical_offset = s->file_length = 0;
640       return SUCCESS;
641     }
642
643   s->physical_offset = s->file_length = s->logical_offset;
644   s->active = 0;
645   return SUCCESS;
646 }
647
648
649 /* Similar to memset(), but operating on a stream instead of a string.
650    Takes care of not using too much memory.  */
651
652 static try
653 fd_sset (unix_stream * s, int c, size_t n)
654 {
655   size_t bytes_left;
656   int trans;
657   void *p;
658
659   bytes_left = n;
660
661   while (bytes_left > 0)
662     {
663       /* memset() in chunks of BUFFER_SIZE.  */
664       trans = (bytes_left < BUFFER_SIZE) ? bytes_left : BUFFER_SIZE;
665
666       p = fd_alloc_w_at (s, &trans, -1);
667       if (p)
668           memset (p, c, trans);
669       else
670         return FAILURE;
671
672       bytes_left -= trans;
673     }
674
675   return SUCCESS;
676 }
677
678
679 /* Stream read function. Avoids using a buffer for big reads. The
680    interface is like POSIX read(), but the nbytes argument is a
681    pointer; on return it contains the number of bytes written. The
682    function return value is the status indicator (0 for success).  */
683
684 static int
685 fd_read (unix_stream * s, void * buf, size_t * nbytes)
686 {
687   void *p;
688   int tmp, status;
689
690   if (*nbytes < BUFFER_SIZE && !s->unbuffered)
691     {
692       tmp = *nbytes;
693       p = fd_alloc_r_at (s, &tmp, -1);
694       if (p)
695         {
696           *nbytes = tmp;
697           memcpy (buf, p, *nbytes);
698           return 0;
699         }
700       else
701         {
702           *nbytes = 0;
703           return errno;
704         }
705     }
706
707   /* If the request is bigger than BUFFER_SIZE we flush the buffers
708      and read directly.  */
709   if (fd_flush (s) == FAILURE)
710     {
711       *nbytes = 0;
712       return errno;
713     }
714
715   if (is_seekable ((stream *) s) && fd_seek (s, s->logical_offset) == FAILURE)
716     {
717       *nbytes = 0;
718       return errno;
719     }
720
721   status = do_read (s, buf, nbytes);
722   reset_stream (s, *nbytes);
723   return status;
724 }
725
726
727 /* Stream write function. Avoids using a buffer for big writes. The
728    interface is like POSIX write(), but the nbytes argument is a
729    pointer; on return it contains the number of bytes written. The
730    function return value is the status indicator (0 for success).  */
731
732 static int
733 fd_write (unix_stream * s, const void * buf, size_t * nbytes)
734 {
735   void *p;
736   int tmp, status;
737
738   if (*nbytes < BUFFER_SIZE && !s->unbuffered)
739     {
740       tmp = *nbytes;
741       p = fd_alloc_w_at (s, &tmp, -1);
742       if (p)
743         {
744           *nbytes = tmp;
745           memcpy (p, buf, *nbytes);
746           return 0;
747         }
748       else
749         {
750           *nbytes = 0;
751           return errno;
752         }
753     }
754
755   /* If the request is bigger than BUFFER_SIZE we flush the buffers
756      and write directly.  */
757   if (fd_flush (s) == FAILURE)
758     {
759       *nbytes = 0;
760       return errno;
761     }
762
763   if (is_seekable ((stream *) s) && fd_seek (s, s->logical_offset) == FAILURE)
764     {
765       *nbytes = 0;
766       return errno;
767     }
768
769   status =  do_write (s, buf, nbytes);
770   reset_stream (s, *nbytes);
771   return status;
772 }
773
774
775 static try
776 fd_close (unix_stream * s)
777 {
778   if (fd_flush (s) == FAILURE)
779     return FAILURE;
780
781   if (s->buffer != NULL && s->buffer != s->small_buffer)
782     free_mem (s->buffer);
783
784   if (s->fd != STDOUT_FILENO && s->fd != STDERR_FILENO)
785     {
786       if (close (s->fd) < 0)
787         return FAILURE;
788     }
789
790   free_mem (s);
791
792   return SUCCESS;
793 }
794
795
796 static void
797 fd_open (unix_stream * s)
798 {
799   if (isatty (s->fd))
800     s->unbuffered = 1;
801
802   s->st.alloc_r_at = (void *) fd_alloc_r_at;
803   s->st.alloc_w_at = (void *) fd_alloc_w_at;
804   s->st.sfree = (void *) fd_sfree;
805   s->st.close = (void *) fd_close;
806   s->st.seek = (void *) fd_seek;
807   s->st.truncate = (void *) fd_truncate;
808   s->st.read = (void *) fd_read;
809   s->st.write = (void *) fd_write;
810   s->st.set = (void *) fd_sset;
811
812   s->buffer = NULL;
813 }
814
815
816
817
818 /*********************************************************************
819   memory stream functions - These are used for internal files
820
821   The idea here is that a single stream structure is created and all
822   requests must be satisfied from it.  The location and size of the
823   buffer is the character variable supplied to the READ or WRITE
824   statement.
825
826 *********************************************************************/
827
828
829 static char *
830 mem_alloc_r_at (unix_stream * s, int *len, gfc_offset where)
831 {
832   gfc_offset n;
833
834   if (where == -1)
835     where = s->logical_offset;
836
837   if (where < s->buffer_offset || where > s->buffer_offset + s->active)
838     return NULL;
839
840   s->logical_offset = where + *len;
841
842   n = s->buffer_offset + s->active - where;
843   if (*len > n)
844     *len = n;
845
846   return s->buffer + (where - s->buffer_offset);
847 }
848
849
850 static char *
851 mem_alloc_w_at (unix_stream * s, int *len, gfc_offset where)
852 {
853   gfc_offset m;
854
855   assert (*len >= 0);  /* Negative values not allowed. */
856   
857   if (where == -1)
858     where = s->logical_offset;
859
860   m = where + *len;
861
862   if (where < s->buffer_offset)
863     return NULL;
864
865   if (m > s->file_length)
866     return NULL;
867
868   s->logical_offset = m;
869
870   return s->buffer + (where - s->buffer_offset);
871 }
872
873
874 /* Stream read function for internal units. This is not actually used
875    at the moment, as all internal IO is formatted and the formatted IO
876    routines use mem_alloc_r_at.  */
877
878 static int
879 mem_read (unix_stream * s, void * buf, size_t * nbytes)
880 {
881   void *p;
882   int tmp;
883
884   tmp = *nbytes;
885   p = mem_alloc_r_at (s, &tmp, -1);
886   if (p)
887     {
888       *nbytes = tmp;
889       memcpy (buf, p, *nbytes);
890       return 0;
891     }
892   else
893     {
894       *nbytes = 0;
895       return errno;
896     }
897 }
898
899
900 /* Stream write function for internal units. This is not actually used
901    at the moment, as all internal IO is formatted and the formatted IO
902    routines use mem_alloc_w_at.  */
903
904 static int
905 mem_write (unix_stream * s, const void * buf, size_t * nbytes)
906 {
907   void *p;
908   int tmp;
909
910   errno = 0;
911
912   tmp = *nbytes;
913   p = mem_alloc_w_at (s, &tmp, -1);
914   if (p)
915     {
916       *nbytes = tmp;
917       memcpy (p, buf, *nbytes);
918       return 0;
919     }
920   else
921     {
922       *nbytes = 0;
923       return errno;
924     }
925 }
926
927
928 static int
929 mem_seek (unix_stream * s, gfc_offset offset)
930 {
931   if (offset > s->file_length)
932     {
933       errno = ESPIPE;
934       return FAILURE;
935     }
936
937   s->logical_offset = offset;
938   return SUCCESS;
939 }
940
941
942 static try
943 mem_set (unix_stream * s, int c, size_t n)
944 {
945   void *p;
946   int len;
947
948   len = n;
949   
950   p = mem_alloc_w_at (s, &len, -1);
951   if (p)
952     {
953       memset (p, c, len);
954       return SUCCESS;
955     }
956   else
957     return FAILURE;
958 }
959
960
961 static int
962 mem_truncate (unix_stream * s __attribute__ ((unused)))
963 {
964   return SUCCESS;
965 }
966
967
968 static try
969 mem_close (unix_stream * s)
970 {
971   if (s != NULL)
972     free_mem (s);
973
974   return SUCCESS;
975 }
976
977
978 static try
979 mem_sfree (unix_stream * s __attribute__ ((unused)))
980 {
981   return SUCCESS;
982 }
983
984
985
986 /*********************************************************************
987   Public functions -- A reimplementation of this module needs to
988   define functional equivalents of the following.
989 *********************************************************************/
990
991 /* empty_internal_buffer()-- Zero the buffer of Internal file */
992
993 void
994 empty_internal_buffer(stream *strm)
995 {
996   unix_stream * s = (unix_stream *) strm;
997   memset(s->buffer, ' ', s->file_length);
998 }
999
1000 /* open_internal()-- Returns a stream structure from an internal file */
1001
1002 stream *
1003 open_internal (char *base, int length)
1004 {
1005   unix_stream *s;
1006
1007   s = get_mem (sizeof (unix_stream));
1008   memset (s, '\0', sizeof (unix_stream));
1009
1010   s->buffer = base;
1011   s->buffer_offset = 0;
1012
1013   s->logical_offset = 0;
1014   s->active = s->file_length = length;
1015
1016   s->st.alloc_r_at = (void *) mem_alloc_r_at;
1017   s->st.alloc_w_at = (void *) mem_alloc_w_at;
1018   s->st.sfree = (void *) mem_sfree;
1019   s->st.close = (void *) mem_close;
1020   s->st.seek = (void *) mem_seek;
1021   s->st.truncate = (void *) mem_truncate;
1022   s->st.read = (void *) mem_read;
1023   s->st.write = (void *) mem_write;
1024   s->st.set = (void *) mem_set;
1025
1026   return (stream *) s;
1027 }
1028
1029
1030 /* fd_to_stream()-- Given an open file descriptor, build a stream
1031  * around it. */
1032
1033 static stream *
1034 fd_to_stream (int fd, int prot)
1035 {
1036   struct stat statbuf;
1037   unix_stream *s;
1038
1039   s = get_mem (sizeof (unix_stream));
1040   memset (s, '\0', sizeof (unix_stream));
1041
1042   s->fd = fd;
1043   s->buffer_offset = 0;
1044   s->physical_offset = 0;
1045   s->logical_offset = 0;
1046   s->prot = prot;
1047
1048   /* Get the current length of the file. */
1049
1050   fstat (fd, &statbuf);
1051
1052   if (lseek (fd, 0, SEEK_CUR) == (off_t) -1)
1053     s->file_length = -1;
1054   else
1055     s->file_length = S_ISREG (statbuf.st_mode) ? statbuf.st_size : -1;
1056
1057   s->special_file = !S_ISREG (statbuf.st_mode);
1058
1059   fd_open (s);
1060
1061   return (stream *) s;
1062 }
1063
1064
1065 /* Given the Fortran unit number, convert it to a C file descriptor.  */
1066
1067 int
1068 unit_to_fd (int unit)
1069 {
1070   gfc_unit *us;
1071   int fd;
1072
1073   us = find_unit (unit);
1074   if (us == NULL)
1075     return -1;
1076
1077   fd = ((unix_stream *) us->s)->fd;
1078   unlock_unit (us);
1079   return fd;
1080 }
1081
1082
1083 /* unpack_filename()-- Given a fortran string and a pointer to a
1084  * buffer that is PATH_MAX characters, convert the fortran string to a
1085  * C string in the buffer.  Returns nonzero if this is not possible.  */
1086
1087 int
1088 unpack_filename (char *cstring, const char *fstring, int len)
1089 {
1090   len = fstrlen (fstring, len);
1091   if (len >= PATH_MAX)
1092     return 1;
1093
1094   memmove (cstring, fstring, len);
1095   cstring[len] = '\0';
1096
1097   return 0;
1098 }
1099
1100
1101 /* tempfile()-- Generate a temporary filename for a scratch file and
1102  * open it.  mkstemp() opens the file for reading and writing, but the
1103  * library mode prevents anything that is not allowed.  The descriptor
1104  * is returned, which is -1 on error.  The template is pointed to by 
1105  * opp->file, which is copied into the unit structure
1106  * and freed later. */
1107
1108 static int
1109 tempfile (st_parameter_open *opp)
1110 {
1111   const char *tempdir;
1112   char *template;
1113   int fd;
1114
1115   tempdir = getenv ("GFORTRAN_TMPDIR");
1116   if (tempdir == NULL)
1117     tempdir = getenv ("TMP");
1118   if (tempdir == NULL)
1119     tempdir = getenv ("TEMP");
1120   if (tempdir == NULL)
1121     tempdir = DEFAULT_TEMPDIR;
1122
1123   template = get_mem (strlen (tempdir) + 20);
1124
1125   st_sprintf (template, "%s/gfortrantmpXXXXXX", tempdir);
1126
1127 #ifdef HAVE_MKSTEMP
1128
1129   fd = mkstemp (template);
1130
1131 #else /* HAVE_MKSTEMP */
1132
1133   if (mktemp (template))
1134     do
1135 #if defined(HAVE_CRLF) && defined(O_BINARY)
1136       fd = open (template, O_RDWR | O_CREAT | O_EXCL | O_BINARY,
1137                  S_IREAD | S_IWRITE);
1138 #else
1139       fd = open (template, O_RDWR | O_CREAT | O_EXCL, S_IREAD | S_IWRITE);
1140 #endif
1141     while (!(fd == -1 && errno == EEXIST) && mktemp (template));
1142   else
1143     fd = -1;
1144
1145 #endif /* HAVE_MKSTEMP */
1146
1147   if (fd < 0)
1148     free_mem (template);
1149   else
1150     {
1151       opp->file = template;
1152       opp->file_len = strlen (template);        /* Don't include trailing nul */
1153     }
1154
1155   return fd;
1156 }
1157
1158
1159 /* regular_file()-- Open a regular file.
1160  * Change flags->action if it is ACTION_UNSPECIFIED on entry,
1161  * unless an error occurs.
1162  * Returns the descriptor, which is less than zero on error. */
1163
1164 static int
1165 regular_file (st_parameter_open *opp, unit_flags *flags)
1166 {
1167   char path[PATH_MAX + 1];
1168   int mode;
1169   int rwflag;
1170   int crflag;
1171   int fd;
1172
1173   if (unpack_filename (path, opp->file, opp->file_len))
1174     {
1175       errno = ENOENT;           /* Fake an OS error */
1176       return -1;
1177     }
1178
1179   rwflag = 0;
1180
1181   switch (flags->action)
1182     {
1183     case ACTION_READ:
1184       rwflag = O_RDONLY;
1185       break;
1186
1187     case ACTION_WRITE:
1188       rwflag = O_WRONLY;
1189       break;
1190
1191     case ACTION_READWRITE:
1192     case ACTION_UNSPECIFIED:
1193       rwflag = O_RDWR;
1194       break;
1195
1196     default:
1197       internal_error (&opp->common, "regular_file(): Bad action");
1198     }
1199
1200   switch (flags->status)
1201     {
1202     case STATUS_NEW:
1203       crflag = O_CREAT | O_EXCL;
1204       break;
1205
1206     case STATUS_OLD:            /* open will fail if the file does not exist*/
1207       crflag = 0;
1208       break;
1209
1210     case STATUS_UNKNOWN:
1211     case STATUS_SCRATCH:
1212       crflag = O_CREAT;
1213       break;
1214
1215     case STATUS_REPLACE:
1216       crflag = O_CREAT | O_TRUNC;
1217       break;
1218
1219     default:
1220       internal_error (&opp->common, "regular_file(): Bad status");
1221     }
1222
1223   /* rwflag |= O_LARGEFILE; */
1224
1225 #if defined(HAVE_CRLF) && defined(O_BINARY)
1226   crflag |= O_BINARY;
1227 #endif
1228
1229   mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
1230   fd = open (path, rwflag | crflag, mode);
1231   if (flags->action != ACTION_UNSPECIFIED)
1232     return fd;
1233
1234   if (fd >= 0)
1235     {
1236       flags->action = ACTION_READWRITE;
1237       return fd;
1238     }
1239   if (errno != EACCES && errno != EROFS)
1240      return fd;
1241
1242   /* retry for read-only access */
1243   rwflag = O_RDONLY;
1244   fd = open (path, rwflag | crflag, mode);
1245   if (fd >=0)
1246     {
1247       flags->action = ACTION_READ;
1248       return fd;               /* success */
1249     }
1250   
1251   if (errno != EACCES)
1252     return fd;                 /* failure */
1253
1254   /* retry for write-only access */
1255   rwflag = O_WRONLY;
1256   fd = open (path, rwflag | crflag, mode);
1257   if (fd >=0)
1258     {
1259       flags->action = ACTION_WRITE;
1260       return fd;               /* success */
1261     }
1262   return fd;                   /* failure */
1263 }
1264
1265
1266 /* open_external()-- Open an external file, unix specific version.
1267  * Change flags->action if it is ACTION_UNSPECIFIED on entry.
1268  * Returns NULL on operating system error. */
1269
1270 stream *
1271 open_external (st_parameter_open *opp, unit_flags *flags)
1272 {
1273   int fd, prot;
1274
1275   if (flags->status == STATUS_SCRATCH)
1276     {
1277       fd = tempfile (opp);
1278       if (flags->action == ACTION_UNSPECIFIED)
1279         flags->action = ACTION_READWRITE;
1280
1281 #if HAVE_UNLINK_OPEN_FILE
1282       /* We can unlink scratch files now and it will go away when closed. */
1283       if (fd >= 0)
1284         unlink (opp->file);
1285 #endif
1286     }
1287   else
1288     {
1289       /* regular_file resets flags->action if it is ACTION_UNSPECIFIED and
1290        * if it succeeds */
1291       fd = regular_file (opp, flags);
1292     }
1293
1294   if (fd < 0)
1295     return NULL;
1296   fd = fix_fd (fd);
1297
1298   switch (flags->action)
1299     {
1300     case ACTION_READ:
1301       prot = PROT_READ;
1302       break;
1303
1304     case ACTION_WRITE:
1305       prot = PROT_WRITE;
1306       break;
1307
1308     case ACTION_READWRITE:
1309       prot = PROT_READ | PROT_WRITE;
1310       break;
1311
1312     default:
1313       internal_error (&opp->common, "open_external(): Bad action");
1314     }
1315
1316   return fd_to_stream (fd, prot);
1317 }
1318
1319
1320 /* input_stream()-- Return a stream pointer to the default input stream.
1321  * Called on initialization. */
1322
1323 stream *
1324 input_stream (void)
1325 {
1326   return fd_to_stream (STDIN_FILENO, PROT_READ);
1327 }
1328
1329
1330 /* output_stream()-- Return a stream pointer to the default output stream.
1331  * Called on initialization. */
1332
1333 stream *
1334 output_stream (void)
1335 {
1336 #if defined(HAVE_CRLF) && defined(HAVE_SETMODE)
1337   setmode (STDOUT_FILENO, O_BINARY);
1338 #endif
1339   return fd_to_stream (STDOUT_FILENO, PROT_WRITE);
1340 }
1341
1342
1343 /* error_stream()-- Return a stream pointer to the default error stream.
1344  * Called on initialization. */
1345
1346 stream *
1347 error_stream (void)
1348 {
1349 #if defined(HAVE_CRLF) && defined(HAVE_SETMODE)
1350   setmode (STDERR_FILENO, O_BINARY);
1351 #endif
1352   return fd_to_stream (STDERR_FILENO, PROT_WRITE);
1353 }
1354
1355 /* init_error_stream()-- Return a pointer to the error stream.  This
1356  * subroutine is called when the stream is needed, rather than at
1357  * initialization.  We want to work even if memory has been seriously
1358  * corrupted. */
1359
1360 stream *
1361 init_error_stream (unix_stream *error)
1362 {
1363   memset (error, '\0', sizeof (*error));
1364
1365   error->fd = options.use_stderr ? STDERR_FILENO : STDOUT_FILENO;
1366
1367   error->st.alloc_w_at = (void *) fd_alloc_w_at;
1368   error->st.sfree = (void *) fd_sfree;
1369
1370   error->unbuffered = 1;
1371   error->buffer = error->small_buffer;
1372
1373   return (stream *) error;
1374 }
1375
1376 /* st_printf()-- simple printf() function for streams that handles the
1377  * formats %d, %s and %c.  This function handles printing of error
1378  * messages that originate within the library itself, not from a user
1379  * program. */
1380
1381 int
1382 st_printf (const char *format, ...)
1383 {
1384   int count, total;
1385   va_list arg;
1386   char *p;
1387   const char *q;
1388   stream *s;
1389   char itoa_buf[GFC_ITOA_BUF_SIZE];
1390   unix_stream err_stream;
1391
1392   total = 0;
1393   s = init_error_stream (&err_stream);
1394   va_start (arg, format);
1395
1396   for (;;)
1397     {
1398       count = 0;
1399
1400       while (format[count] != '%' && format[count] != '\0')
1401         count++;
1402
1403       if (count != 0)
1404         {
1405           p = salloc_w (s, &count);
1406           memmove (p, format, count);
1407           sfree (s);
1408         }
1409
1410       total += count;
1411       format += count;
1412       if (*format++ == '\0')
1413         break;
1414
1415       switch (*format)
1416         {
1417         case 'c':
1418           count = 1;
1419
1420           p = salloc_w (s, &count);
1421           *p = (char) va_arg (arg, int);
1422
1423           sfree (s);
1424           break;
1425
1426         case 'd':
1427           q = gfc_itoa (va_arg (arg, int), itoa_buf, sizeof (itoa_buf));
1428           count = strlen (q);
1429
1430           p = salloc_w (s, &count);
1431           memmove (p, q, count);
1432           sfree (s);
1433           break;
1434
1435         case 'x':
1436           q = xtoa (va_arg (arg, unsigned), itoa_buf, sizeof (itoa_buf));
1437           count = strlen (q);
1438
1439           p = salloc_w (s, &count);
1440           memmove (p, q, count);
1441           sfree (s);
1442           break;
1443
1444         case 's':
1445           q = va_arg (arg, char *);
1446           count = strlen (q);
1447
1448           p = salloc_w (s, &count);
1449           memmove (p, q, count);
1450           sfree (s);
1451           break;
1452
1453         case '\0':
1454           return total;
1455
1456         default:
1457           count = 2;
1458           p = salloc_w (s, &count);
1459           p[0] = format[-1];
1460           p[1] = format[0];
1461           sfree (s);
1462           break;
1463         }
1464
1465       total += count;
1466       format++;
1467     }
1468
1469   va_end (arg);
1470   return total;
1471 }
1472
1473
1474 /* compare_file_filename()-- Given an open stream and a fortran string
1475  * that is a filename, figure out if the file is the same as the
1476  * filename. */
1477
1478 int
1479 compare_file_filename (gfc_unit *u, const char *name, int len)
1480 {
1481   char path[PATH_MAX + 1];
1482   struct stat st1;
1483 #ifdef HAVE_WORKING_STAT
1484   struct stat st2;
1485 #endif
1486
1487   if (unpack_filename (path, name, len))
1488     return 0;                   /* Can't be the same */
1489
1490   /* If the filename doesn't exist, then there is no match with the
1491    * existing file. */
1492
1493   if (stat (path, &st1) < 0)
1494     return 0;
1495
1496 #ifdef HAVE_WORKING_STAT
1497   fstat (((unix_stream *) (u->s))->fd, &st2);
1498   return (st1.st_dev == st2.st_dev) && (st1.st_ino == st2.st_ino);
1499 #else
1500   if (len != u->file_len)
1501     return 0;
1502   return (memcmp(path, u->file, len) == 0);
1503 #endif
1504 }
1505
1506
1507 #ifdef HAVE_WORKING_STAT
1508 # define FIND_FILE0_DECL struct stat *st
1509 # define FIND_FILE0_ARGS st
1510 #else
1511 # define FIND_FILE0_DECL const char *file, gfc_charlen_type file_len
1512 # define FIND_FILE0_ARGS file, file_len
1513 #endif
1514
1515 /* find_file0()-- Recursive work function for find_file() */
1516
1517 static gfc_unit *
1518 find_file0 (gfc_unit *u, FIND_FILE0_DECL)
1519 {
1520   gfc_unit *v;
1521
1522   if (u == NULL)
1523     return NULL;
1524
1525 #ifdef HAVE_WORKING_STAT
1526   if (u->s != NULL
1527       && fstat (((unix_stream *) u->s)->fd, &st[1]) >= 0 &&
1528       st[0].st_dev == st[1].st_dev && st[0].st_ino == st[1].st_ino)
1529     return u;
1530 #else
1531   if (compare_string (u->file_len, u->file, file_len, file) == 0)
1532     return u;
1533 #endif
1534
1535   v = find_file0 (u->left, FIND_FILE0_ARGS);
1536   if (v != NULL)
1537     return v;
1538
1539   v = find_file0 (u->right, FIND_FILE0_ARGS);
1540   if (v != NULL)
1541     return v;
1542
1543   return NULL;
1544 }
1545
1546
1547 /* find_file()-- Take the current filename and see if there is a unit
1548  * that has the file already open.  Returns a pointer to the unit if so. */
1549
1550 gfc_unit *
1551 find_file (const char *file, gfc_charlen_type file_len)
1552 {
1553   char path[PATH_MAX + 1];
1554   struct stat st[2];
1555   gfc_unit *u;
1556
1557   if (unpack_filename (path, file, file_len))
1558     return NULL;
1559
1560   if (stat (path, &st[0]) < 0)
1561     return NULL;
1562
1563   __gthread_mutex_lock (&unit_lock);
1564 retry:
1565   u = find_file0 (unit_root, FIND_FILE0_ARGS);
1566   if (u != NULL)
1567     {
1568       /* Fast path.  */
1569       if (! __gthread_mutex_trylock (&u->lock))
1570         {
1571           /* assert (u->closed == 0); */
1572           __gthread_mutex_unlock (&unit_lock);
1573           return u;
1574         }
1575
1576       inc_waiting_locked (u);
1577     }
1578   __gthread_mutex_unlock (&unit_lock);
1579   if (u != NULL)
1580     {
1581       __gthread_mutex_lock (&u->lock);
1582       if (u->closed)
1583         {
1584           __gthread_mutex_lock (&unit_lock);
1585           __gthread_mutex_unlock (&u->lock);
1586           if (predec_waiting_locked (u) == 0)
1587             free_mem (u);
1588           goto retry;
1589         }
1590
1591       dec_waiting_unlocked (u);
1592     }
1593   return u;
1594 }
1595
1596 static gfc_unit *
1597 flush_all_units_1 (gfc_unit *u, int min_unit)
1598 {
1599   while (u != NULL)
1600     {
1601       if (u->unit_number > min_unit)
1602         {
1603           gfc_unit *r = flush_all_units_1 (u->left, min_unit);
1604           if (r != NULL)
1605             return r;
1606         }
1607       if (u->unit_number >= min_unit)
1608         {
1609           if (__gthread_mutex_trylock (&u->lock))
1610             return u;
1611           if (u->s)
1612             flush (u->s);
1613           __gthread_mutex_unlock (&u->lock);
1614         }
1615       u = u->right;
1616     }
1617   return NULL;
1618 }
1619
1620 void
1621 flush_all_units (void)
1622 {
1623   gfc_unit *u;
1624   int min_unit = 0;
1625
1626   __gthread_mutex_lock (&unit_lock);
1627   do
1628     {
1629       u = flush_all_units_1 (unit_root, min_unit);
1630       if (u != NULL)
1631         inc_waiting_locked (u);
1632       __gthread_mutex_unlock (&unit_lock);
1633       if (u == NULL)
1634         return;
1635
1636       __gthread_mutex_lock (&u->lock);
1637
1638       min_unit = u->unit_number + 1;
1639
1640       if (u->closed == 0)
1641         {
1642           flush (u->s);
1643           __gthread_mutex_lock (&unit_lock);
1644           __gthread_mutex_unlock (&u->lock);
1645           (void) predec_waiting_locked (u);
1646         }
1647       else
1648         {
1649           __gthread_mutex_lock (&unit_lock);
1650           __gthread_mutex_unlock (&u->lock);
1651           if (predec_waiting_locked (u) == 0)
1652             free_mem (u);
1653         }
1654     }
1655   while (1);
1656 }
1657
1658
1659 /* stream_at_bof()-- Returns nonzero if the stream is at the beginning
1660  * of the file. */
1661
1662 int
1663 stream_at_bof (stream * s)
1664 {
1665   unix_stream *us;
1666
1667   if (!is_seekable (s))
1668     return 0;
1669
1670   us = (unix_stream *) s;
1671
1672   return us->logical_offset == 0;
1673 }
1674
1675
1676 /* stream_at_eof()-- Returns nonzero if the stream is at the end
1677  * of the file. */
1678
1679 int
1680 stream_at_eof (stream * s)
1681 {
1682   unix_stream *us;
1683
1684   if (!is_seekable (s))
1685     return 0;
1686
1687   us = (unix_stream *) s;
1688
1689   return us->logical_offset == us->dirty_offset;
1690 }
1691
1692
1693 /* delete_file()-- Given a unit structure, delete the file associated
1694  * with the unit.  Returns nonzero if something went wrong. */
1695
1696 int
1697 delete_file (gfc_unit * u)
1698 {
1699   char path[PATH_MAX + 1];
1700
1701   if (unpack_filename (path, u->file, u->file_len))
1702     {                           /* Shouldn't be possible */
1703       errno = ENOENT;
1704       return 1;
1705     }
1706
1707   return unlink (path);
1708 }
1709
1710
1711 /* file_exists()-- Returns nonzero if the current filename exists on
1712  * the system */
1713
1714 int
1715 file_exists (const char *file, gfc_charlen_type file_len)
1716 {
1717   char path[PATH_MAX + 1];
1718   struct stat statbuf;
1719
1720   if (unpack_filename (path, file, file_len))
1721     return 0;
1722
1723   if (stat (path, &statbuf) < 0)
1724     return 0;
1725
1726   return 1;
1727 }
1728
1729
1730
1731 static const char yes[] = "YES", no[] = "NO", unknown[] = "UNKNOWN";
1732
1733 /* inquire_sequential()-- Given a fortran string, determine if the
1734  * file is suitable for sequential access.  Returns a C-style
1735  * string. */
1736
1737 const char *
1738 inquire_sequential (const char *string, int len)
1739 {
1740   char path[PATH_MAX + 1];
1741   struct stat statbuf;
1742
1743   if (string == NULL ||
1744       unpack_filename (path, string, len) || stat (path, &statbuf) < 0)
1745     return unknown;
1746
1747   if (S_ISREG (statbuf.st_mode) ||
1748       S_ISCHR (statbuf.st_mode) || S_ISFIFO (statbuf.st_mode))
1749     return yes;
1750
1751   if (S_ISDIR (statbuf.st_mode) || S_ISBLK (statbuf.st_mode))
1752     return no;
1753
1754   return unknown;
1755 }
1756
1757
1758 /* inquire_direct()-- Given a fortran string, determine if the file is
1759  * suitable for direct access.  Returns a C-style string. */
1760
1761 const char *
1762 inquire_direct (const char *string, int len)
1763 {
1764   char path[PATH_MAX + 1];
1765   struct stat statbuf;
1766
1767   if (string == NULL ||
1768       unpack_filename (path, string, len) || stat (path, &statbuf) < 0)
1769     return unknown;
1770
1771   if (S_ISREG (statbuf.st_mode) || S_ISBLK (statbuf.st_mode))
1772     return yes;
1773
1774   if (S_ISDIR (statbuf.st_mode) ||
1775       S_ISCHR (statbuf.st_mode) || S_ISFIFO (statbuf.st_mode))
1776     return no;
1777
1778   return unknown;
1779 }
1780
1781
1782 /* inquire_formatted()-- Given a fortran string, determine if the file
1783  * is suitable for formatted form.  Returns a C-style string. */
1784
1785 const char *
1786 inquire_formatted (const char *string, int len)
1787 {
1788   char path[PATH_MAX + 1];
1789   struct stat statbuf;
1790
1791   if (string == NULL ||
1792       unpack_filename (path, string, len) || stat (path, &statbuf) < 0)
1793     return unknown;
1794
1795   if (S_ISREG (statbuf.st_mode) ||
1796       S_ISBLK (statbuf.st_mode) ||
1797       S_ISCHR (statbuf.st_mode) || S_ISFIFO (statbuf.st_mode))
1798     return yes;
1799
1800   if (S_ISDIR (statbuf.st_mode))
1801     return no;
1802
1803   return unknown;
1804 }
1805
1806
1807 /* inquire_unformatted()-- Given a fortran string, determine if the file
1808  * is suitable for unformatted form.  Returns a C-style string. */
1809
1810 const char *
1811 inquire_unformatted (const char *string, int len)
1812 {
1813   return inquire_formatted (string, len);
1814 }
1815
1816
1817 /* inquire_access()-- Given a fortran string, determine if the file is
1818  * suitable for access. */
1819
1820 static const char *
1821 inquire_access (const char *string, int len, int mode)
1822 {
1823   char path[PATH_MAX + 1];
1824
1825   if (string == NULL || unpack_filename (path, string, len) ||
1826       access (path, mode) < 0)
1827     return no;
1828
1829   return yes;
1830 }
1831
1832
1833 /* inquire_read()-- Given a fortran string, determine if the file is
1834  * suitable for READ access. */
1835
1836 const char *
1837 inquire_read (const char *string, int len)
1838 {
1839   return inquire_access (string, len, R_OK);
1840 }
1841
1842
1843 /* inquire_write()-- Given a fortran string, determine if the file is
1844  * suitable for READ access. */
1845
1846 const char *
1847 inquire_write (const char *string, int len)
1848 {
1849   return inquire_access (string, len, W_OK);
1850 }
1851
1852
1853 /* inquire_readwrite()-- Given a fortran string, determine if the file is
1854  * suitable for read and write access. */
1855
1856 const char *
1857 inquire_readwrite (const char *string, int len)
1858 {
1859   return inquire_access (string, len, R_OK | W_OK);
1860 }
1861
1862
1863 /* file_length()-- Return the file length in bytes, -1 if unknown */
1864
1865 gfc_offset
1866 file_length (stream * s)
1867 {
1868   return ((unix_stream *) s)->file_length;
1869 }
1870
1871
1872 /* file_position()-- Return the current position of the file */
1873
1874 gfc_offset
1875 file_position (stream *s)
1876 {
1877   return ((unix_stream *) s)->logical_offset;
1878 }
1879
1880
1881 /* is_seekable()-- Return nonzero if the stream is seekable, zero if
1882  * it is not */
1883
1884 int
1885 is_seekable (stream *s)
1886 {
1887   /* By convention, if file_length == -1, the file is not
1888      seekable.  */
1889   return ((unix_stream *) s)->file_length!=-1;
1890 }
1891
1892
1893 /* is_special()-- Return nonzero if the stream is not a regular file.  */
1894
1895 int
1896 is_special (stream *s)
1897 {
1898   return ((unix_stream *) s)->special_file;
1899 }
1900
1901
1902 try
1903 flush (stream *s)
1904 {
1905   return fd_flush( (unix_stream *) s);
1906 }
1907
1908 int
1909 stream_isatty (stream *s)
1910 {
1911   return isatty (((unix_stream *) s)->fd);
1912 }
1913
1914 char *
1915 stream_ttyname (stream *s)
1916 {
1917 #ifdef HAVE_TTYNAME
1918   return ttyname (((unix_stream *) s)->fd);
1919 #else
1920   return NULL;
1921 #endif
1922 }
1923
1924 gfc_offset
1925 stream_offset (stream *s)
1926 {
1927   return (((unix_stream *) s)->logical_offset);
1928 }
1929
1930
1931 /* How files are stored:  This is an operating-system specific issue,
1932    and therefore belongs here.  There are three cases to consider.
1933
1934    Direct Access:
1935       Records are written as block of bytes corresponding to the record
1936       length of the file.  This goes for both formatted and unformatted
1937       records.  Positioning is done explicitly for each data transfer,
1938       so positioning is not much of an issue.
1939
1940    Sequential Formatted:
1941       Records are separated by newline characters.  The newline character
1942       is prohibited from appearing in a string.  If it does, this will be
1943       messed up on the next read.  End of file is also the end of a record.
1944
1945    Sequential Unformatted:
1946       In this case, we are merely copying bytes to and from main storage,
1947       yet we need to keep track of varying record lengths.  We adopt
1948       the solution used by f2c.  Each record contains a pair of length
1949       markers:
1950
1951         Length of record n in bytes
1952         Data of record n
1953         Length of record n in bytes
1954
1955         Length of record n+1 in bytes
1956         Data of record n+1
1957         Length of record n+1 in bytes
1958
1959      The length is stored at the end of a record to allow backspacing to the
1960      previous record.  Between data transfer statements, the file pointer
1961      is left pointing to the first length of the current record.
1962
1963      ENDFILE records are never explicitly stored.
1964
1965 */