]> git.ipfire.org Git - thirdparty/gcc.git/blame - libgfortran/io/unix.c
PR c++/86499
[thirdparty/gcc.git] / libgfortran / io / unix.c
CommitLineData
8e8f6434 1/* Copyright (C) 2002-2018 Free Software Foundation, Inc.
4ee9c684 2 Contributed by Andy Vaught
84d33b91 3 F2003 I/O support contributed by Jerry DeLisle
4ee9c684 4
5e62a3cc 5This file is part of the GNU Fortran runtime library (libgfortran).
4ee9c684 6
7Libgfortran is free software; you can redistribute it and/or modify
8it under the terms of the GNU General Public License as published by
6bc9506f 9the Free Software Foundation; either version 3, or (at your option)
4ee9c684 10any later version.
11
12Libgfortran is distributed in the hope that it will be useful,
13but WITHOUT ANY WARRANTY; without even the implied warranty of
14MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15GNU General Public License for more details.
16
6bc9506f 17Under Section 7 of GPL version 3, you are granted additional
18permissions described in the GCC Runtime Library Exception, version
193.1, as published by the Free Software Foundation.
20
21You should have received a copy of the GNU General Public License and
22a copy of the GCC Runtime Library Exception along with this program;
23see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
24<http://www.gnu.org/licenses/>. */
4ee9c684 25
26/* Unix stream I/O module */
27
41f2d5e8 28#include "io.h"
f65f6629 29#include "unix.h"
4ee9c684 30#include <limits.h>
31
ea9ae053 32#ifdef HAVE_UNISTD_H
4ee9c684 33#include <unistd.h>
ea9ae053 34#endif
35
4ee9c684 36#include <sys/stat.h>
37#include <fcntl.h>
38
4ee9c684 39#include <string.h>
40#include <errno.h>
41
c0ecd33c 42
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. */
7a4491a4 45#ifdef __MINGW32__
c0ecd33c 46
47#define WIN32_LEAN_AND_MEAN
48#include <windows.h>
49
f6854450 50#if !defined(_FILE_OFFSET_BITS) || _FILE_OFFSET_BITS != 64
51#undef lseek
4dbc0658 52#define lseek _lseeki64
f6854450 53#undef fstat
7a4491a4 54#define fstat _fstati64
f6854450 55#undef stat
7a4491a4 56#define stat _stati64
f6854450 57#endif
4dbc0658 58
7a4491a4 59#ifndef HAVE_WORKING_STAT
c0ecd33c 60static uint64_t
61id_from_handle (HANDLE hFile)
62{
63 BY_HANDLE_FILE_INFORMATION FileInformation;
64
65 if (hFile == INVALID_HANDLE_VALUE)
66 return 0;
67
68 memset (&FileInformation, 0, sizeof(FileInformation));
69 if (!GetFileInformationByHandle (hFile, &FileInformation))
70 return 0;
71
72 return ((uint64_t) FileInformation.nFileIndexLow)
73 | (((uint64_t) FileInformation.nFileIndexHigh) << 32);
74}
75
76
77static uint64_t
78id_from_path (const char *path)
79{
80 HANDLE hFile;
81 uint64_t res;
82
83 if (!path || !*path || access (path, F_OK))
84 return (uint64_t) -1;
85
86 hFile = CreateFile (path, 0, 0, NULL, OPEN_EXISTING,
87 FILE_FLAG_BACKUP_SEMANTICS | FILE_ATTRIBUTE_READONLY,
88 NULL);
89 res = id_from_handle (hFile);
90 CloseHandle (hFile);
91 return res;
92}
93
94
95static uint64_t
96id_from_fd (const int fd)
97{
98 return id_from_handle ((HANDLE) _get_osfhandle (fd));
99}
100
a8ce53cd 101#endif /* HAVE_WORKING_STAT */
ebb925e3 102
103
104/* On mingw, we don't use umask in tempfile_open(), because it
105 doesn't support the user/group/other-based permissions. */
106#undef HAVE_UMASK
107
a8ce53cd 108#endif /* __MINGW32__ */
109
110
7dfba97b 111/* These flags aren't defined on all targets (mingw32), so provide them
112 here. */
113#ifndef S_IRGRP
114#define S_IRGRP 0
115#endif
116
117#ifndef S_IWGRP
118#define S_IWGRP 0
119#endif
120
121#ifndef S_IROTH
122#define S_IROTH 0
123#endif
124
125#ifndef S_IWOTH
126#define S_IWOTH 0
127#endif
128
76c0a846 129
fb053cd1 130#ifndef HAVE_ACCESS
131
132#ifndef W_OK
133#define W_OK 2
134#endif
135
136#ifndef R_OK
137#define R_OK 4
138#endif
139
140#ifndef F_OK
141#define F_OK 0
142#endif
143
144/* Fallback implementation of access() on systems that don't have it.
145 Only modes R_OK, W_OK and F_OK are used in this file. */
146
147static int
148fallback_access (const char *path, int mode)
149{
398e846b 150 int fd;
151
152 if ((mode & R_OK) && (fd = open (path, O_RDONLY)) < 0)
fb053cd1 153 return -1;
398e846b 154 close (fd);
fb053cd1 155
398e846b 156 if ((mode & W_OK) && (fd = open (path, O_WRONLY)) < 0)
fb053cd1 157 return -1;
398e846b 158 close (fd);
fb053cd1 159
160 if (mode == F_OK)
161 {
f6854450 162 struct stat st;
fb053cd1 163 return stat (path, &st);
164 }
165
166 return 0;
167}
168
169#undef access
170#define access fallback_access
171#endif
172
173
a291e3b6 174/* Fallback directory for creating temporary files. P_tmpdir is
175 defined on many POSIX platforms. */
176#ifndef P_tmpdir
177#ifdef _P_tmpdir
178#define P_tmpdir _P_tmpdir /* MinGW */
179#else
180#define P_tmpdir "/tmp"
181#endif
182#endif
183
184
65f15010 185/* Unix and internal stream I/O module */
76c0a846 186
65f15010 187static const int BUFFER_SIZE = 8192;
76c0a846 188
3479b863 189typedef struct
190{
191 stream st;
192
193 gfc_offset buffer_offset; /* File offset of the start of the buffer */
194 gfc_offset physical_offset; /* Current physical file offset */
195 gfc_offset logical_offset; /* Current logical file offset */
cc65b133 196 gfc_offset file_length; /* Length of the file. */
3479b863 197
198 char *buffer; /* Pointer to the buffer. */
199 int fd; /* The POSIX file descriptor. */
200
201 int active; /* Length of valid bytes in the buffer */
202
203 int ndirty; /* Dirty bytes starting at buffer_offset */
204
01cd2c93 205 /* Cached stat(2) values. */
206 dev_t st_dev;
207 ino_t st_ino;
fe34985d 208
209 bool unbuffered; /* Buffer should be flushed after each I/O statement. */
3479b863 210}
211unix_stream;
212
213
4ee9c684 214/* fix_fd()-- Given a file descriptor, make sure it is not one of the
25a5ce27 215 standard descriptors, returning a non-standard descriptor. If the
216 user specifies that system errors should go to standard output,
217 then closes standard output, we don't want the system errors to a
218 file that has been given file descriptor 1 or 0. We want to send
219 the error to the invalid descriptor. */
4ee9c684 220
221static int
222fix_fd (int fd)
223{
e0582811 224#ifdef HAVE_DUP
4ee9c684 225 int input, output, error;
226
227 input = output = error = 0;
228
7145fd06 229 /* Unix allocates the lowest descriptors first, so a loop is not
230 required, but this order is. */
4ee9c684 231 if (fd == STDIN_FILENO)
232 {
233 fd = dup (fd);
234 input = 1;
235 }
236 if (fd == STDOUT_FILENO)
237 {
238 fd = dup (fd);
239 output = 1;
240 }
241 if (fd == STDERR_FILENO)
242 {
243 fd = dup (fd);
244 error = 1;
245 }
246
247 if (input)
248 close (STDIN_FILENO);
249 if (output)
250 close (STDOUT_FILENO);
251 if (error)
252 close (STDERR_FILENO);
e0582811 253#endif
4ee9c684 254
255 return fd;
256}
257
258
2488b3b6 259/* If the stream corresponds to a preconnected unit, we flush the
260 corresponding C stream. This is bugware for mixed C-Fortran codes
261 where the C code doesn't flush I/O before returning. */
262void
25a5ce27 263flush_if_preconnected (stream *s)
2488b3b6 264{
265 int fd;
266
267 fd = ((unix_stream *) s)->fd;
268 if (fd == STDIN_FILENO)
269 fflush (stdin);
270 else if (fd == STDOUT_FILENO)
271 fflush (stdout);
272 else if (fd == STDERR_FILENO)
273 fflush (stderr);
274}
275
4ee9c684 276
65f15010 277/********************************************************************
278Raw I/O functions (read, write, seek, tell, truncate, close).
279
280These functions wrap the basic POSIX I/O syscalls. Any deviation in
281semantics is a bug, except the following: write restarts in case
282of being interrupted by a signal, and as the first argument the
283functions take the unix_stream struct rather than an integer file
284descriptor. Also, for POSIX read() and write() a nbyte argument larger
285than SSIZE_MAX is undefined; here the type of nbyte is ssize_t rather
286than size_t as for POSIX read/write.
287*********************************************************************/
4ee9c684 288
b2a112ca 289static int
25a5ce27 290raw_flush (unix_stream *s __attribute__ ((unused)))
b2a112ca 291{
65f15010 292 return 0;
4ee9c684 293}
294
6d6d3070 295/* Write/read at most 2 GB - 4k chunks at a time. Linux never reads or
296 writes more than this, and there are reports that macOS fails for
297 larger than 2 GB as well. */
298#define MAX_CHUNK 2147479552
299
65f15010 300static ssize_t
25a5ce27 301raw_read (unix_stream *s, void *buf, ssize_t nbyte)
65f15010 302{
303 /* For read we can't do I/O in a loop like raw_write does, because
714f1fe2 304 that will break applications that wait for interactive I/O. We
6d6d3070 305 still can loop around EINTR, though. This however causes a
306 problem for large reads which must be chunked, see comment above.
307 So assume that if the size is larger than the chunk size, we're
308 reading from a file and not the terminal. */
309 if (nbyte <= MAX_CHUNK)
714f1fe2 310 {
6d6d3070 311 while (true)
312 {
313 ssize_t trans = read (s->fd, buf, nbyte);
314 if (trans == -1 && errno == EINTR)
315 continue;
316 return trans;
317 }
318 }
319 else
320 {
321 ssize_t bytes_left = nbyte;
322 char *buf_st = buf;
323 while (bytes_left > 0)
324 {
325 ssize_t to_read = bytes_left < MAX_CHUNK ? bytes_left: MAX_CHUNK;
326 ssize_t trans = read (s->fd, buf_st, to_read);
327 if (trans == -1)
328 {
329 if (errno == EINTR)
330 continue;
331 else
332 return trans;
333 }
334 buf_st += trans;
335 bytes_left -= trans;
336 }
337 return nbyte - bytes_left;
714f1fe2 338 }
65f15010 339}
4ee9c684 340
65f15010 341static ssize_t
25a5ce27 342raw_write (unix_stream *s, const void *buf, ssize_t nbyte)
4ee9c684 343{
65f15010 344 ssize_t trans, bytes_left;
b2a112ca 345 char *buf_st;
b2a112ca 346
65f15010 347 bytes_left = nbyte;
b2a112ca 348 buf_st = (char *) buf;
349
350 /* We must write in a loop since some systems don't restart system
6d6d3070 351 calls in case of a signal. Also some systems might fail outright
352 if we try to write more than 2 GB in a single syscall, so chunk
353 up large writes. */
b2a112ca 354 while (bytes_left > 0)
4ee9c684 355 {
6d6d3070 356 ssize_t to_write = bytes_left < MAX_CHUNK ? bytes_left: MAX_CHUNK;
357 trans = write (s->fd, buf_st, to_write);
714f1fe2 358 if (trans == -1)
b2a112ca 359 {
360 if (errno == EINTR)
361 continue;
362 else
65f15010 363 return trans;
b2a112ca 364 }
365 buf_st += trans;
366 bytes_left -= trans;
4ee9c684 367 }
368
65f15010 369 return nbyte - bytes_left;
4ee9c684 370}
4ee9c684 371
4dbc0658 372static gfc_offset
25a5ce27 373raw_seek (unix_stream *s, gfc_offset offset, int whence)
65f15010 374{
714f1fe2 375 while (true)
376 {
377 gfc_offset off = lseek (s->fd, offset, whence);
378 if (off == (gfc_offset) -1 && errno == EINTR)
379 continue;
380 return off;
381 }
65f15010 382}
4ee9c684 383
4dbc0658 384static gfc_offset
25a5ce27 385raw_tell (unix_stream *s)
65f15010 386{
714f1fe2 387 while (true)
388 {
389 gfc_offset off = lseek (s->fd, 0, SEEK_CUR);
390 if (off == (gfc_offset) -1 && errno == EINTR)
391 continue;
392 return off;
393 }
65f15010 394}
4ee9c684 395
41178014 396static gfc_offset
25a5ce27 397raw_size (unix_stream *s)
41178014 398{
399 struct stat statbuf;
714f1fe2 400 if (TEMP_FAILURE_RETRY (fstat (s->fd, &statbuf)) == -1)
401 return -1;
6dfa90cc 402 if (S_ISREG (statbuf.st_mode))
403 return statbuf.st_size;
404 else
405 return 0;
41178014 406}
407
65f15010 408static int
25a5ce27 409raw_truncate (unix_stream *s, gfc_offset length)
4ee9c684 410{
4dbc0658 411#ifdef __MINGW32__
412 HANDLE h;
413 gfc_offset cur;
414
415 if (isatty (s->fd))
416 {
417 errno = EBADF;
418 return -1;
419 }
db23ac43 420 h = (HANDLE) _get_osfhandle (s->fd);
4dbc0658 421 if (h == INVALID_HANDLE_VALUE)
422 {
423 errno = EBADF;
424 return -1;
425 }
426 cur = lseek (s->fd, 0, SEEK_CUR);
427 if (cur == -1)
428 return -1;
429 if (lseek (s->fd, length, SEEK_SET) == -1)
430 goto error;
431 if (!SetEndOfFile (h))
432 {
433 errno = EBADF;
434 goto error;
435 }
436 if (lseek (s->fd, cur, SEEK_SET) == -1)
437 return -1;
438 return 0;
439 error:
440 lseek (s->fd, cur, SEEK_SET);
441 return -1;
442#elif defined HAVE_FTRUNCATE
714f1fe2 443 if (TEMP_FAILURE_RETRY (ftruncate (s->fd, length)) == -1)
444 return -1;
445 return 0;
65f15010 446#elif defined HAVE_CHSIZE
447 return chsize (s->fd, length);
448#else
449 runtime_error ("required ftruncate or chsize support not present");
450 return -1;
451#endif
4ee9c684 452}
453
65f15010 454static int
25a5ce27 455raw_close (unix_stream *s)
65f15010 456{
457 int retval;
458
7b89cd4f 459 if (s->fd == -1)
460 retval = -1;
461 else if (s->fd != STDOUT_FILENO
8b89aa85 462 && s->fd != STDERR_FILENO
463 && s->fd != STDIN_FILENO)
714f1fe2 464 {
465 retval = close (s->fd);
466 /* close() and EINTR is special, as the file descriptor is
467 deallocated before doing anything that might cause the
468 operation to be interrupted. Thus if we get EINTR the best we
469 can do is ignore it and continue (otherwise if we try again
470 the file descriptor may have been allocated again to some
471 other file). */
472 if (retval == -1 && errno == EINTR)
473 retval = errno = 0;
474 }
8b89aa85 475 else
6ffeb312 476 retval = 0;
5e62a3cc 477 free (s);
65f15010 478 return retval;
479}
4ee9c684 480
155fbd31 481static int
25a5ce27 482raw_markeor (unix_stream *s __attribute__ ((unused)))
155fbd31 483{
484 return 0;
485}
486
292d5498 487static const struct stream_vtable raw_vtable = {
488 .read = (void *) raw_read,
489 .write = (void *) raw_write,
490 .seek = (void *) raw_seek,
491 .tell = (void *) raw_tell,
492 .size = (void *) raw_size,
493 .trunc = (void *) raw_truncate,
494 .close = (void *) raw_close,
155fbd31 495 .flush = (void *) raw_flush,
496 .markeor = (void *) raw_markeor
292d5498 497};
498
65f15010 499static int
25a5ce27 500raw_init (unix_stream *s)
65f15010 501{
292d5498 502 s->st.vptr = &raw_vtable;
4ee9c684 503
65f15010 504 s->buffer = NULL;
505 return 0;
506}
b2a112ca 507
4ee9c684 508
65f15010 509/*********************************************************************
510Buffered I/O functions. These functions have the same semantics as the
511raw I/O functions above, except that they are buffered in order to
512improve performance. The buffer must be flushed when switching from
fe34985d 513reading to writing and vice versa.
65f15010 514*********************************************************************/
515
516static int
25a5ce27 517buf_flush (unix_stream *s)
4ee9c684 518{
65f15010 519 int writelen;
520
521 /* Flushing in read mode means discarding read bytes. */
522 s->active = 0;
b2a112ca 523
4ee9c684 524 if (s->ndirty == 0)
65f15010 525 return 0;
352597f9 526
cc65b133 527 if (s->physical_offset != s->buffer_offset
714f1fe2 528 && raw_seek (s, s->buffer_offset, SEEK_SET) < 0)
65f15010 529 return -1;
4ee9c684 530
65f15010 531 writelen = raw_write (s, s->buffer, s->ndirty);
4ee9c684 532
65f15010 533 s->physical_offset = s->buffer_offset + writelen;
5a78b88f 534
cc65b133 535 if (s->physical_offset > s->file_length)
65f15010 536 s->file_length = s->physical_offset;
b2a112ca 537
538 s->ndirty -= writelen;
539 if (s->ndirty != 0)
65f15010 540 return -1;
4ee9c684 541
65f15010 542 return 0;
4ee9c684 543}
544
65f15010 545static ssize_t
25a5ce27 546buf_read (unix_stream *s, void *buf, ssize_t nbyte)
4ee9c684 547{
65f15010 548 if (s->active == 0)
549 s->buffer_offset = s->logical_offset;
5d5f00d5 550
65f15010 551 /* Is the data we want in the buffer? */
552 if (s->logical_offset + nbyte <= s->buffer_offset + s->active
553 && s->buffer_offset <= s->logical_offset)
c60f0c1e 554 {
555 /* When nbyte == 0, buf can be NULL which would lead to undefined
556 behavior if we called memcpy(). */
557 if (nbyte != 0)
558 memcpy (buf, s->buffer + (s->logical_offset - s->buffer_offset),
559 nbyte);
560 }
5d5f00d5 561 else
562 {
65f15010 563 /* First copy the active bytes if applicable, then read the rest
564 either directly or filling the buffer. */
565 char *p;
566 int nread = 0;
567 ssize_t to_read, did_read;
568 gfc_offset new_logical;
569
570 p = (char *) buf;
571 if (s->logical_offset >= s->buffer_offset
572 && s->buffer_offset + s->active >= s->logical_offset)
573 {
574 nread = s->active - (s->logical_offset - s->buffer_offset);
575 memcpy (buf, s->buffer + (s->logical_offset - s->buffer_offset),
576 nread);
577 p += nread;
578 }
579 /* At this point we consider all bytes in the buffer discarded. */
580 to_read = nbyte - nread;
581 new_logical = s->logical_offset + nread;
cc65b133 582 if (s->physical_offset != new_logical
714f1fe2 583 && raw_seek (s, new_logical, SEEK_SET) < 0)
65f15010 584 return -1;
585 s->buffer_offset = s->physical_offset = new_logical;
586 if (to_read <= BUFFER_SIZE/2)
587 {
588 did_read = raw_read (s, s->buffer, BUFFER_SIZE);
3287030a 589 if (likely (did_read >= 0))
590 {
591 s->physical_offset += did_read;
592 s->active = did_read;
593 did_read = (did_read > to_read) ? to_read : did_read;
594 memcpy (p, s->buffer, did_read);
595 }
596 else
597 return did_read;
65f15010 598 }
599 else
600 {
601 did_read = raw_read (s, p, to_read);
3287030a 602 if (likely (did_read >= 0))
603 {
604 s->physical_offset += did_read;
605 s->active = 0;
606 }
607 else
608 return did_read;
65f15010 609 }
610 nbyte = did_read + nread;
4ee9c684 611 }
65f15010 612 s->logical_offset += nbyte;
613 return nbyte;
4ee9c684 614}
615
65f15010 616static ssize_t
25a5ce27 617buf_write (unix_stream *s, const void *buf, ssize_t nbyte)
4ee9c684 618{
f724d42d 619 if (nbyte == 0)
620 return 0;
621
65f15010 622 if (s->ndirty == 0)
623 s->buffer_offset = s->logical_offset;
624
625 /* Does the data fit into the buffer? As a special case, if the
626 buffer is empty and the request is bigger than BUFFER_SIZE/2,
627 write directly. This avoids the case where the buffer would have
628 to be flushed at every write. */
629 if (!(s->ndirty == 0 && nbyte > BUFFER_SIZE/2)
630 && s->logical_offset + nbyte <= s->buffer_offset + BUFFER_SIZE
631 && s->buffer_offset <= s->logical_offset
632 && s->buffer_offset + s->ndirty >= s->logical_offset)
fef3501c 633 {
65f15010 634 memcpy (s->buffer + (s->logical_offset - s->buffer_offset), buf, nbyte);
635 int nd = (s->logical_offset - s->buffer_offset) + nbyte;
636 if (nd > s->ndirty)
637 s->ndirty = nd;
fef3501c 638 }
639 else
640 {
65f15010 641 /* Flush, and either fill the buffer with the new data, or if
642 the request is bigger than the buffer size, write directly
643 bypassing the buffer. */
644 buf_flush (s);
645 if (nbyte <= BUFFER_SIZE/2)
646 {
647 memcpy (s->buffer, buf, nbyte);
648 s->buffer_offset = s->logical_offset;
649 s->ndirty += nbyte;
650 }
651 else
35a97371 652 {
cc65b133 653 if (s->physical_offset != s->logical_offset)
35a97371 654 {
714f1fe2 655 if (raw_seek (s, s->logical_offset, SEEK_SET) < 0)
35a97371 656 return -1;
657 s->physical_offset = s->logical_offset;
658 }
659
660 nbyte = raw_write (s, buf, nbyte);
661 s->physical_offset += nbyte;
662 }
4ee9c684 663 }
65f15010 664 s->logical_offset += nbyte;
cc65b133 665 if (s->logical_offset > s->file_length)
65f15010 666 s->file_length = s->logical_offset;
667 return nbyte;
4ee9c684 668}
669
155fbd31 670
671/* "Unbuffered" really means I/O statement buffering. For formatted
672 I/O, the fbuf manages this, and then uses raw I/O. For unformatted
673 I/O, buffered I/O is used, and the buffer is flushed at the end of
674 each I/O statement, where this function is called. Alternatively,
675 the buffer is flushed at the end of the record if the buffer is
676 more than half full; this prevents needless seeking back and forth
677 when writing sequential unformatted. */
678
679static int
25a5ce27 680buf_markeor (unix_stream *s)
155fbd31 681{
682 if (s->unbuffered || s->ndirty >= BUFFER_SIZE / 2)
683 return buf_flush (s);
684 return 0;
685}
686
4dbc0658 687static gfc_offset
25a5ce27 688buf_seek (unix_stream *s, gfc_offset offset, int whence)
4ee9c684 689{
65f15010 690 switch (whence)
352597f9 691 {
65f15010 692 case SEEK_SET:
693 break;
694 case SEEK_CUR:
695 offset += s->logical_offset;
696 break;
697 case SEEK_END:
698 offset += s->file_length;
699 break;
700 default:
701 return -1;
352597f9 702 }
65f15010 703 if (offset < 0)
72909c79 704 {
65f15010 705 errno = EINVAL;
706 return -1;
72909c79 707 }
65f15010 708 s->logical_offset = offset;
709 return offset;
4ee9c684 710}
711
4dbc0658 712static gfc_offset
25a5ce27 713buf_tell (unix_stream *s)
56f281a2 714{
f22f0b38 715 return buf_seek (s, 0, SEEK_CUR);
56f281a2 716}
b2a112ca 717
41178014 718static gfc_offset
25a5ce27 719buf_size (unix_stream *s)
41178014 720{
721 return s->file_length;
722}
723
b2a112ca 724static int
25a5ce27 725buf_truncate (unix_stream *s, gfc_offset length)
b2a112ca 726{
65f15010 727 int r;
b2a112ca 728
65f15010 729 if (buf_flush (s) != 0)
730 return -1;
731 r = raw_truncate (s, length);
732 if (r == 0)
733 s->file_length = length;
734 return r;
b2a112ca 735}
736
b2a112ca 737static int
25a5ce27 738buf_close (unix_stream *s)
4ee9c684 739{
65f15010 740 if (buf_flush (s) != 0)
741 return -1;
5e62a3cc 742 free (s->buffer);
65f15010 743 return raw_close (s);
4ee9c684 744}
745
292d5498 746static const struct stream_vtable buf_vtable = {
747 .read = (void *) buf_read,
748 .write = (void *) buf_write,
749 .seek = (void *) buf_seek,
750 .tell = (void *) buf_tell,
751 .size = (void *) buf_size,
752 .trunc = (void *) buf_truncate,
753 .close = (void *) buf_close,
155fbd31 754 .flush = (void *) buf_flush,
755 .markeor = (void *) buf_markeor
292d5498 756};
757
65f15010 758static int
25a5ce27 759buf_init (unix_stream *s)
4ee9c684 760{
292d5498 761 s->st.vptr = &buf_vtable;
4ee9c684 762
25c067ae 763 s->buffer = xmalloc (BUFFER_SIZE);
65f15010 764 return 0;
4ee9c684 765}
766
767
4ee9c684 768/*********************************************************************
769 memory stream functions - These are used for internal files
770
771 The idea here is that a single stream structure is created and all
772 requests must be satisfied from it. The location and size of the
773 buffer is the character variable supplied to the READ or WRITE
774 statement.
775
776*********************************************************************/
777
65f15010 778char *
d683dd3a 779mem_alloc_r (stream *strm, size_t *len)
4ee9c684 780{
25a5ce27 781 unix_stream *s = (unix_stream *) strm;
b093181d 782 gfc_offset n;
d875179d 783 gfc_offset where = s->logical_offset;
4ee9c684 784
785 if (where < s->buffer_offset || where > s->buffer_offset + s->active)
786 return NULL;
787
11de4bf9 788 n = s->buffer_offset + s->active - where;
d683dd3a 789 if ((gfc_offset) *len > n)
4ee9c684 790 *len = n;
791
65f15010 792 s->logical_offset = where + *len;
793
4ee9c684 794 return s->buffer + (where - s->buffer_offset);
795}
796
797
e0aaacb7 798char *
d683dd3a 799mem_alloc_r4 (stream *strm, size_t *len)
e0aaacb7 800{
25a5ce27 801 unix_stream *s = (unix_stream *) strm;
e0aaacb7 802 gfc_offset n;
803 gfc_offset where = s->logical_offset;
804
805 if (where < s->buffer_offset || where > s->buffer_offset + s->active)
806 return NULL;
807
808 n = s->buffer_offset + s->active - where;
d683dd3a 809 if ((gfc_offset) *len > n)
e0aaacb7 810 *len = n;
811
812 s->logical_offset = where + *len;
813
814 return s->buffer + (where - s->buffer_offset) * 4;
815}
816
817
65f15010 818char *
d683dd3a 819mem_alloc_w (stream *strm, size_t *len)
4ee9c684 820{
25a5ce27 821 unix_stream *s = (unix_stream *)strm;
b093181d 822 gfc_offset m;
d875179d 823 gfc_offset where = s->logical_offset;
4ee9c684 824
4ee9c684 825 m = where + *len;
826
2639e4cd 827 if (where < s->buffer_offset)
4ee9c684 828 return NULL;
829
2639e4cd 830 if (m > s->file_length)
72231bd6 831 return NULL;
2639e4cd 832
4ee9c684 833 s->logical_offset = m;
834
835 return s->buffer + (where - s->buffer_offset);
836}
837
838
1bb7bffb 839gfc_char4_t *
d683dd3a 840mem_alloc_w4 (stream *strm, size_t *len)
e0aaacb7 841{
25a5ce27 842 unix_stream *s = (unix_stream *)strm;
e0aaacb7 843 gfc_offset m;
844 gfc_offset where = s->logical_offset;
1bb7bffb 845 gfc_char4_t *result = (gfc_char4_t *) s->buffer;
e0aaacb7 846
847 m = where + *len;
848
849 if (where < s->buffer_offset)
850 return NULL;
851
852 if (m > s->file_length)
853 return NULL;
854
855 s->logical_offset = m;
1bb7bffb 856 return &result[where - s->buffer_offset];
e0aaacb7 857}
858
859
655c7caa 860/* Stream read function for character(kind=1) internal units. */
b2a112ca 861
65f15010 862static ssize_t
25a5ce27 863mem_read (stream *s, void *buf, ssize_t nbytes)
b2a112ca 864{
865 void *p;
d683dd3a 866 size_t nb = nbytes;
b2a112ca 867
65f15010 868 p = mem_alloc_r (s, &nb);
b2a112ca 869 if (p)
870 {
65f15010 871 memcpy (buf, p, nb);
872 return (ssize_t) nb;
b2a112ca 873 }
874 else
65f15010 875 return 0;
b2a112ca 876}
877
878
e0aaacb7 879/* Stream read function for chracter(kind=4) internal units. */
880
881static ssize_t
25a5ce27 882mem_read4 (stream *s, void *buf, ssize_t nbytes)
e0aaacb7 883{
884 void *p;
d683dd3a 885 size_t nb = nbytes;
e0aaacb7 886
fe0171a5 887 p = mem_alloc_r4 (s, &nb);
e0aaacb7 888 if (p)
889 {
fe0171a5 890 memcpy (buf, p, nb * 4);
e0aaacb7 891 return (ssize_t) nb;
892 }
893 else
894 return 0;
895}
896
897
898/* Stream write function for character(kind=1) internal units. */
b2a112ca 899
65f15010 900static ssize_t
25a5ce27 901mem_write (stream *s, const void *buf, ssize_t nbytes)
b2a112ca 902{
903 void *p;
d683dd3a 904 size_t nb = nbytes;
b2a112ca 905
65f15010 906 p = mem_alloc_w (s, &nb);
b2a112ca 907 if (p)
908 {
65f15010 909 memcpy (p, buf, nb);
910 return (ssize_t) nb;
b2a112ca 911 }
912 else
65f15010 913 return 0;
b2a112ca 914}
915
916
e0aaacb7 917/* Stream write function for character(kind=4) internal units. */
918
919static ssize_t
25a5ce27 920mem_write4 (stream *s, const void *buf, ssize_t nwords)
e0aaacb7 921{
922 gfc_char4_t *p;
d683dd3a 923 size_t nw = nwords;
e0aaacb7 924
1bb7bffb 925 p = mem_alloc_w4 (s, &nw);
e0aaacb7 926 if (p)
927 {
928 while (nw--)
929 *p++ = (gfc_char4_t) *((char *) buf);
930 return nwords;
931 }
932 else
933 return 0;
934}
935
936
4dbc0658 937static gfc_offset
25a5ce27 938mem_seek (stream *strm, gfc_offset offset, int whence)
4ee9c684 939{
25a5ce27 940 unix_stream *s = (unix_stream *)strm;
65f15010 941 switch (whence)
942 {
943 case SEEK_SET:
944 break;
945 case SEEK_CUR:
946 offset += s->logical_offset;
947 break;
948 case SEEK_END:
949 offset += s->file_length;
950 break;
951 default:
952 return -1;
953 }
954
955 /* Note that for internal array I/O it's actually possible to have a
956 negative offset, so don't check for that. */
4ee9c684 957 if (offset > s->file_length)
958 {
65f15010 959 errno = EINVAL;
960 return -1;
4ee9c684 961 }
962
963 s->logical_offset = offset;
65f15010 964
965 /* Returning < 0 is the error indicator for sseek(), so return 0 if
966 offset is negative. Thus if the return value is 0, the caller
967 has to use stell() to get the real value of logical_offset. */
968 if (offset >= 0)
969 return offset;
970 return 0;
4ee9c684 971}
972
973
4dbc0658 974static gfc_offset
25a5ce27 975mem_tell (stream *s)
56f281a2 976{
65f15010 977 return ((unix_stream *)s)->logical_offset;
56f281a2 978}
979
980
4ee9c684 981static int
25a5ce27 982mem_truncate (unix_stream *s __attribute__ ((unused)),
4dbc0658 983 gfc_offset length __attribute__ ((unused)))
4ee9c684 984{
65f15010 985 return 0;
4ee9c684 986}
987
988
65f15010 989static int
25a5ce27 990mem_flush (unix_stream *s __attribute__ ((unused)))
4ee9c684 991{
65f15010 992 return 0;
4ee9c684 993}
994
995
65f15010 996static int
25a5ce27 997mem_close (unix_stream *s)
4ee9c684 998{
7d9dac31 999 if (s)
1000 free (s);
65f15010 1001 return 0;
1002}
4ee9c684 1003
292d5498 1004static const struct stream_vtable mem_vtable = {
1005 .read = (void *) mem_read,
1006 .write = (void *) mem_write,
1007 .seek = (void *) mem_seek,
1008 .tell = (void *) mem_tell,
1009 /* buf_size is not a typo, we just reuse an identical
1010 implementation. */
1011 .size = (void *) buf_size,
1012 .trunc = (void *) mem_truncate,
1013 .close = (void *) mem_close,
155fbd31 1014 .flush = (void *) mem_flush,
1015 .markeor = (void *) raw_markeor
292d5498 1016};
1017
1018static const struct stream_vtable mem4_vtable = {
1019 .read = (void *) mem_read4,
1020 .write = (void *) mem_write4,
1021 .seek = (void *) mem_seek,
1022 .tell = (void *) mem_tell,
1023 /* buf_size is not a typo, we just reuse an identical
1024 implementation. */
1025 .size = (void *) buf_size,
1026 .trunc = (void *) mem_truncate,
1027 .close = (void *) mem_close,
155fbd31 1028 .flush = (void *) mem_flush,
1029 .markeor = (void *) raw_markeor
292d5498 1030};
4ee9c684 1031
1032/*********************************************************************
1033 Public functions -- A reimplementation of this module needs to
1034 define functional equivalents of the following.
1035*********************************************************************/
1036
e0aaacb7 1037/* open_internal()-- Returns a stream structure from a character(kind=1)
1038 internal file */
4ee9c684 1039
1040stream *
d683dd3a 1041open_internal (char *base, size_t length, gfc_offset offset)
4ee9c684 1042{
65f15010 1043 unix_stream *s;
4ee9c684 1044
33123ed7 1045 s = xcalloc (1, sizeof (unix_stream));
4ee9c684 1046
1047 s->buffer = base;
cf4abc57 1048 s->buffer_offset = offset;
4ee9c684 1049
4ee9c684 1050 s->active = s->file_length = length;
1051
292d5498 1052 s->st.vptr = &mem_vtable;
4ee9c684 1053
e0aaacb7 1054 return (stream *) s;
1055}
1056
1057/* open_internal4()-- Returns a stream structure from a character(kind=4)
1058 internal file */
1059
1060stream *
d683dd3a 1061open_internal4 (char *base, size_t length, gfc_offset offset)
e0aaacb7 1062{
1063 unix_stream *s;
1064
33123ed7 1065 s = xcalloc (1, sizeof (unix_stream));
e0aaacb7 1066
1067 s->buffer = base;
1068 s->buffer_offset = offset;
1069
33ea6150 1070 s->active = s->file_length = length * sizeof (gfc_char4_t);
e0aaacb7 1071
292d5498 1072 s->st.vptr = &mem4_vtable;
e0aaacb7 1073
25a5ce27 1074 return (stream *)s;
4ee9c684 1075}
1076
1077
1078/* fd_to_stream()-- Given an open file descriptor, build a stream
25a5ce27 1079 around it. */
4ee9c684 1080
1081static stream *
fe34985d 1082fd_to_stream (int fd, bool unformatted)
4ee9c684 1083{
f6854450 1084 struct stat statbuf;
4ee9c684 1085 unix_stream *s;
1086
33123ed7 1087 s = xcalloc (1, sizeof (unix_stream));
4ee9c684 1088
1089 s->fd = fd;
4ee9c684 1090
1091 /* Get the current length of the file. */
1092
714f1fe2 1093 if (TEMP_FAILURE_RETRY (fstat (fd, &statbuf)) == -1)
7b89cd4f 1094 {
1095 s->st_dev = s->st_ino = -1;
1096 s->file_length = 0;
1097 if (errno == EBADF)
1098 s->fd = -1;
1099 raw_init (s);
1100 return (stream *) s;
1101 }
352597f9 1102
01cd2c93 1103 s->st_dev = statbuf.st_dev;
1104 s->st_ino = statbuf.st_ino;
cc65b133 1105 s->file_length = statbuf.st_size;
1106
1107 /* Only use buffered IO for regular files. */
1108 if (S_ISREG (statbuf.st_mode)
1109 && !options.all_unbuffered
1110 && !(options.unbuffered_preconnected &&
1111 (s->fd == STDIN_FILENO
1112 || s->fd == STDOUT_FILENO
1113 || s->fd == STDERR_FILENO)))
1114 buf_init (s);
9bfd25a7 1115 else
fe34985d 1116 {
1117 if (unformatted)
1118 {
1119 s->unbuffered = true;
1120 buf_init (s);
1121 }
1122 else
1123 raw_init (s);
1124 }
4ee9c684 1125
1126 return (stream *) s;
1127}
1128
1129
771c1b50 1130/* Given the Fortran unit number, convert it to a C file descriptor. */
1131
1132int
60c514ba 1133unit_to_fd (int unit)
771c1b50 1134{
771c1b50 1135 gfc_unit *us;
60c514ba 1136 int fd;
771c1b50 1137
60c514ba 1138 us = find_unit (unit);
771c1b50 1139 if (us == NULL)
1140 return -1;
1141
60c514ba 1142 fd = ((unix_stream *) us->s)->fd;
1143 unlock_unit (us);
1144 return fd;
771c1b50 1145}
1146
1147
544db64f 1148/* Set the close-on-exec flag for an existing fd, if the system
1149 supports such. */
1150
1151static void __attribute__ ((unused))
1152set_close_on_exec (int fd __attribute__ ((unused)))
1153{
1154 /* Mingw does not define F_SETFD. */
7520a494 1155#if defined(HAVE_FCNTL) && defined(F_SETFD) && defined(FD_CLOEXEC)
544db64f 1156 if (fd >= 0)
1157 fcntl(fd, F_SETFD, FD_CLOEXEC);
1158#endif
1159}
1160
1161
a291e3b6 1162/* Helper function for tempfile(). Tries to open a temporary file in
1163 the directory specified by tempdir. If successful, the file name is
1164 stored in fname and the descriptor returned. Returns -1 on
1165 failure. */
4ee9c684 1166
1167static int
a291e3b6 1168tempfile_open (const char *tempdir, char **fname)
4ee9c684 1169{
4ee9c684 1170 int fd;
a291e3b6 1171 const char *slash = "/";
34f4b81f 1172#if defined(HAVE_UMASK) && defined(HAVE_MKSTEMP)
1173 mode_t mode_mask;
1174#endif
4ee9c684 1175
a291e3b6 1176 if (!tempdir)
1177 return -1;
d06c5aaa 1178
a291e3b6 1179 /* Check for the special case that tempdir ends with a slash or
1180 backslash. */
1181 size_t tempdirlen = strlen (tempdir);
d06c5aaa 1182 if (*tempdir == 0 || tempdir[tempdirlen - 1] == '/'
db23ac43 1183#ifdef __MINGW32__
d06c5aaa 1184 || tempdir[tempdirlen - 1] == '\\'
db23ac43 1185#endif
1186 )
1187 slash = "";
4ee9c684 1188
9f732c4e 1189 /* Take care that the template is longer in the mktemp() branch. */
25a5ce27 1190 char *template = xmalloc (tempdirlen + 23);
4ee9c684 1191
7dfba97b 1192#ifdef HAVE_MKSTEMP
d151c82c 1193 snprintf (template, tempdirlen + 23, "%s%sgfortrantmpXXXXXX",
1194 tempdir, slash);
4ee9c684 1195
34f4b81f 1196#ifdef HAVE_UMASK
1197 /* Temporarily set the umask such that the file has 0600 permissions. */
1198 mode_mask = umask (S_IXUSR | S_IRWXG | S_IRWXO);
1199#endif
1200
544db64f 1201#if defined(HAVE_MKOSTEMP) && defined(O_CLOEXEC)
714f1fe2 1202 TEMP_FAILURE_RETRY (fd = mkostemp (template, O_CLOEXEC));
544db64f 1203#else
714f1fe2 1204 TEMP_FAILURE_RETRY (fd = mkstemp (template));
544db64f 1205 set_close_on_exec (fd);
1206#endif
4ee9c684 1207
34f4b81f 1208#ifdef HAVE_UMASK
1209 (void) umask (mode_mask);
1210#endif
1211
7dfba97b 1212#else /* HAVE_MKSTEMP */
726fd258 1213 fd = -1;
a291e3b6 1214 int count = 0;
1215 size_t slashlen = strlen (slash);
544db64f 1216 int flags = O_RDWR | O_CREAT | O_EXCL;
1217#if defined(HAVE_CRLF) && defined(O_BINARY)
1218 flags |= O_BINARY;
1219#endif
1220#ifdef O_CLOEXEC
1221 flags |= O_CLOEXEC;
1222#endif
726fd258 1223 do
1224 {
d151c82c 1225 snprintf (template, tempdirlen + 23, "%s%sgfortrantmpaaaXXXXXX",
1226 tempdir, slash);
d06c5aaa 1227 if (count > 0)
1228 {
1229 int c = count;
1230 template[tempdirlen + slashlen + 13] = 'a' + (c% 26);
1231 c /= 26;
1232 template[tempdirlen + slashlen + 12] = 'a' + (c % 26);
1233 c /= 26;
1234 template[tempdirlen + slashlen + 11] = 'a' + (c % 26);
1235 if (c >= 26)
1236 break;
1237 }
1238
726fd258 1239 if (!mktemp (template))
d06c5aaa 1240 {
1241 errno = EEXIST;
1242 count++;
1243 continue;
1244 }
1245
714f1fe2 1246 TEMP_FAILURE_RETRY (fd = open (template, flags, S_IRUSR | S_IWUSR));
726fd258 1247 }
1248 while (fd == -1 && errno == EEXIST);
544db64f 1249#ifndef O_CLOEXEC
1250 set_close_on_exec (fd);
1251#endif
7dfba97b 1252#endif /* HAVE_MKSTEMP */
1253
a291e3b6 1254 *fname = template;
1255 return fd;
1256}
1257
1258
1259/* tempfile()-- Generate a temporary filename for a scratch file and
25a5ce27 1260 open it. mkstemp() opens the file for reading and writing, but the
1261 library mode prevents anything that is not allowed. The descriptor
1262 is returned, which is -1 on error. The template is pointed to by
1263 opp->file, which is copied into the unit structure
1264 and freed later. */
a291e3b6 1265
1266static int
1267tempfile (st_parameter_open *opp)
1268{
1269 const char *tempdir;
1270 char *fname;
1271 int fd = -1;
1272
1273 tempdir = secure_getenv ("TMPDIR");
1274 fd = tempfile_open (tempdir, &fname);
1275#ifdef __MINGW32__
1276 if (fd == -1)
1277 {
1278 char buffer[MAX_PATH + 1];
1279 DWORD ret;
1280 ret = GetTempPath (MAX_PATH, buffer);
1281 /* If we are not able to get a temp-directory, we use
1282 current directory. */
1283 if (ret > MAX_PATH || !ret)
1284 buffer[0] = 0;
1285 else
1286 buffer[ret] = 0;
1287 tempdir = strdup (buffer);
1288 fd = tempfile_open (tempdir, &fname);
1289 }
1290#elif defined(__CYGWIN__)
1291 if (fd == -1)
1292 {
1293 tempdir = secure_getenv ("TMP");
1294 fd = tempfile_open (tempdir, &fname);
1295 }
1296 if (fd == -1)
1297 {
1298 tempdir = secure_getenv ("TEMP");
1299 fd = tempfile_open (tempdir, &fname);
1300 }
1301#endif
1302 if (fd == -1)
1303 fd = tempfile_open (P_tmpdir, &fname);
1304
1305 opp->file = fname;
1306 opp->file_len = strlen (fname); /* Don't include trailing nul */
4ee9c684 1307
1308 return fd;
1309}
1310
1311
fc3d374a 1312/* regular_file2()-- Open a regular file.
25a5ce27 1313 Change flags->action if it is ACTION_UNSPECIFIED on entry,
1314 unless an error occurs.
1315 Returns the descriptor, which is less than zero on error. */
4ee9c684 1316
1317static int
fc3d374a 1318regular_file2 (const char *path, st_parameter_open *opp, unit_flags *flags)
4ee9c684 1319{
4ee9c684 1320 int mode;
6d12c489 1321 int rwflag;
327beda5 1322 int crflag, crflag2;
6d12c489 1323 int fd;
4ee9c684 1324
3d17984e 1325#ifdef __CYGWIN__
1326 if (opp->file_len == 7)
1327 {
1328 if (strncmp (path, "CONOUT$", 7) == 0
1329 || strncmp (path, "CONERR$", 7) == 0)
1330 {
1331 fd = open ("/dev/conout", O_WRONLY);
1332 flags->action = ACTION_WRITE;
1333 return fd;
1334 }
1335 }
1336
1337 if (opp->file_len == 6 && strncmp (path, "CONIN$", 6) == 0)
1338 {
1339 fd = open ("/dev/conin", O_RDONLY);
1340 flags->action = ACTION_READ;
1341 return fd;
1342 }
1343#endif
1344
2058bc7e 1345
1346#ifdef __MINGW32__
1347 if (opp->file_len == 7)
1348 {
1349 if (strncmp (path, "CONOUT$", 7) == 0
1350 || strncmp (path, "CONERR$", 7) == 0)
1351 {
1352 fd = open ("CONOUT$", O_WRONLY);
1353 flags->action = ACTION_WRITE;
1354 return fd;
1355 }
1356 }
1357
1358 if (opp->file_len == 6 && strncmp (path, "CONIN$", 6) == 0)
1359 {
1360 fd = open ("CONIN$", O_RDONLY);
1361 flags->action = ACTION_READ;
1362 return fd;
1363 }
1364#endif
1365
6d12c489 1366 switch (flags->action)
4ee9c684 1367 {
1368 case ACTION_READ:
6d12c489 1369 rwflag = O_RDONLY;
4ee9c684 1370 break;
1371
1372 case ACTION_WRITE:
6d12c489 1373 rwflag = O_WRONLY;
4ee9c684 1374 break;
1375
1376 case ACTION_READWRITE:
6d12c489 1377 case ACTION_UNSPECIFIED:
1378 rwflag = O_RDWR;
4ee9c684 1379 break;
1380
1381 default:
60c514ba 1382 internal_error (&opp->common, "regular_file(): Bad action");
4ee9c684 1383 }
1384
6d12c489 1385 switch (flags->status)
4ee9c684 1386 {
1387 case STATUS_NEW:
2d6ba0f9 1388 crflag = O_CREAT | O_EXCL;
4ee9c684 1389 break;
1390
2d6ba0f9 1391 case STATUS_OLD: /* open will fail if the file does not exist*/
1392 crflag = 0;
4ee9c684 1393 break;
1394
1395 case STATUS_UNKNOWN:
327beda5 1396 if (rwflag == O_RDONLY)
1397 crflag = 0;
1398 else
1399 crflag = O_CREAT;
4ee9c684 1400 break;
1401
1402 case STATUS_REPLACE:
a638be8f 1403 crflag = O_CREAT | O_TRUNC;
4ee9c684 1404 break;
1405
1406 default:
327beda5 1407 /* Note: STATUS_SCRATCH is handled by tempfile () and should
1408 never be seen here. */
60c514ba 1409 internal_error (&opp->common, "regular_file(): Bad status");
4ee9c684 1410 }
1411
6d12c489 1412 /* rwflag |= O_LARGEFILE; */
4ee9c684 1413
cf6a3896 1414#if defined(HAVE_CRLF) && defined(O_BINARY)
cf55c3cf 1415 crflag |= O_BINARY;
1416#endif
1417
544db64f 1418#ifdef O_CLOEXEC
1419 crflag |= O_CLOEXEC;
1420#endif
1421
6d12c489 1422 mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
714f1fe2 1423 TEMP_FAILURE_RETRY (fd = open (path, rwflag | crflag, mode));
2d6ba0f9 1424 if (flags->action != ACTION_UNSPECIFIED)
a638be8f 1425 return fd;
2d6ba0f9 1426
1427 if (fd >= 0)
6d12c489 1428 {
2d6ba0f9 1429 flags->action = ACTION_READWRITE;
1430 return fd;
6d12c489 1431 }
771e2b1c 1432 if (errno != EACCES && errno != EPERM && errno != EROFS)
2d6ba0f9 1433 return fd;
1434
1435 /* retry for read-only access */
1436 rwflag = O_RDONLY;
327beda5 1437 if (flags->status == STATUS_UNKNOWN)
1438 crflag2 = crflag & ~(O_CREAT);
1439 else
1440 crflag2 = crflag;
714f1fe2 1441 TEMP_FAILURE_RETRY (fd = open (path, rwflag | crflag2, mode));
2d6ba0f9 1442 if (fd >=0)
1443 {
1444 flags->action = ACTION_READ;
84d33b91 1445 return fd; /* success */
2d6ba0f9 1446 }
1447
771e2b1c 1448 if (errno != EACCES && errno != EPERM && errno != ENOENT)
84d33b91 1449 return fd; /* failure */
2d6ba0f9 1450
1451 /* retry for write-only access */
1452 rwflag = O_WRONLY;
714f1fe2 1453 TEMP_FAILURE_RETRY (fd = open (path, rwflag | crflag, mode));
2d6ba0f9 1454 if (fd >=0)
1455 {
1456 flags->action = ACTION_WRITE;
84d33b91 1457 return fd; /* success */
2d6ba0f9 1458 }
84d33b91 1459 return fd; /* failure */
4ee9c684 1460}
1461
1462
b3db57e8 1463/* Lock the file, if necessary, based on SHARE flags. */
1464
1465#if defined(HAVE_FCNTL) && defined(F_SETLK) && defined(F_UNLCK)
1466static int
1467open_share (st_parameter_open *opp, int fd, unit_flags *flags)
1468{
1469 int r = 0;
1470 struct flock f;
1471 if (fd == STDOUT_FILENO || fd == STDERR_FILENO || fd == STDIN_FILENO)
1472 return 0;
1473
1474 f.l_start = 0;
1475 f.l_len = 0;
1476 f.l_whence = SEEK_SET;
1477
1478 switch (flags->share)
1479 {
1480 case SHARE_DENYNONE:
1481 f.l_type = F_RDLCK;
1482 r = fcntl (fd, F_SETLK, &f);
1483 break;
1484 case SHARE_DENYRW:
1485 /* Must be writable to hold write lock. */
1486 if (flags->action == ACTION_READ)
1487 {
1488 generate_error (&opp->common, LIBERROR_BAD_ACTION,
1489 "Cannot set write lock on file opened for READ");
1490 return -1;
1491 }
1492 f.l_type = F_WRLCK;
1493 r = fcntl (fd, F_SETLK, &f);
1494 break;
1495 case SHARE_UNSPECIFIED:
1496 default:
1497 break;
1498 }
1499
1500 return r;
1501}
1502#else
1503static int
1504open_share (st_parameter_open *opp __attribute__ ((unused)),
1505 int fd __attribute__ ((unused)),
1506 unit_flags *flags __attribute__ ((unused)))
1507{
1508 return 0;
1509}
1510#endif /* defined(HAVE_FCNTL) ... */
1511
1512
fc3d374a 1513/* Wrapper around regular_file2, to make sure we free the path after
1514 we're done. */
1515
1516static int
1517regular_file (st_parameter_open *opp, unit_flags *flags)
1518{
1519 char *path = fc_strdup (opp->file, opp->file_len);
1520 int fd = regular_file2 (path, opp, flags);
1521 free (path);
1522 return fd;
1523}
1524
4ee9c684 1525/* open_external()-- Open an external file, unix specific version.
25a5ce27 1526 Change flags->action if it is ACTION_UNSPECIFIED on entry.
1527 Returns NULL on operating system error. */
4ee9c684 1528
1529stream *
60c514ba 1530open_external (st_parameter_open *opp, unit_flags *flags)
4ee9c684 1531{
aadbd4ae 1532 int fd;
4ee9c684 1533
6d12c489 1534 if (flags->status == STATUS_SCRATCH)
1535 {
60c514ba 1536 fd = tempfile (opp);
6d12c489 1537 if (flags->action == ACTION_UNSPECIFIED)
b3db57e8 1538 flags->action = flags->readonly ? ACTION_READ : ACTION_READWRITE;
1dc95e51 1539
1540#if HAVE_UNLINK_OPEN_FILE
6d12c489 1541 /* We can unlink scratch files now and it will go away when closed. */
60c514ba 1542 if (fd >= 0)
1543 unlink (opp->file);
1dc95e51 1544#endif
6d12c489 1545 }
1546 else
1547 {
2d6ba0f9 1548 /* regular_file resets flags->action if it is ACTION_UNSPECIFIED and
25a5ce27 1549 if it succeeds */
60c514ba 1550 fd = regular_file (opp, flags);
544db64f 1551#ifndef O_CLOEXEC
1552 set_close_on_exec (fd);
1553#endif
6d12c489 1554 }
4ee9c684 1555
1556 if (fd < 0)
1557 return NULL;
1558 fd = fix_fd (fd);
1559
b3db57e8 1560 if (open_share (opp, fd, flags) < 0)
1561 return NULL;
1562
fe34985d 1563 return fd_to_stream (fd, flags->form == FORM_UNFORMATTED);
4ee9c684 1564}
1565
1566
1567/* input_stream()-- Return a stream pointer to the default input stream.
25a5ce27 1568 Called on initialization. */
4ee9c684 1569
1570stream *
1571input_stream (void)
1572{
fe34985d 1573 return fd_to_stream (STDIN_FILENO, false);
4ee9c684 1574}
1575
1576
ff81ee3b 1577/* output_stream()-- Return a stream pointer to the default output stream.
25a5ce27 1578 Called on initialization. */
4ee9c684 1579
1580stream *
1581output_stream (void)
1582{
25a5ce27 1583 stream *s;
3e45a719 1584
e693d7f1 1585#if defined(HAVE_CRLF) && defined(HAVE_SETMODE)
1586 setmode (STDOUT_FILENO, O_BINARY);
1587#endif
3e45a719 1588
fe34985d 1589 s = fd_to_stream (STDOUT_FILENO, false);
3e45a719 1590 return s;
4ee9c684 1591}
1592
1593
ff81ee3b 1594/* error_stream()-- Return a stream pointer to the default error stream.
25a5ce27 1595 Called on initialization. */
ff81ee3b 1596
1597stream *
1598error_stream (void)
1599{
25a5ce27 1600 stream *s;
3e45a719 1601
e693d7f1 1602#if defined(HAVE_CRLF) && defined(HAVE_SETMODE)
1603 setmode (STDERR_FILENO, O_BINARY);
1604#endif
3e45a719 1605
fe34985d 1606 s = fd_to_stream (STDERR_FILENO, false);
3e45a719 1607 return s;
ff81ee3b 1608}
1609
4ee9c684 1610
4ee9c684 1611/* compare_file_filename()-- Given an open stream and a fortran string
25a5ce27 1612 that is a filename, figure out if the file is the same as the
1613 filename. */
4ee9c684 1614
1615int
daad4fd5 1616compare_file_filename (gfc_unit *u, const char *name, int len)
4ee9c684 1617{
f6854450 1618 struct stat st;
fc3d374a 1619 int ret;
daad4fd5 1620#ifdef HAVE_WORKING_STAT
01cd2c93 1621 unix_stream *s;
c0ecd33c 1622#else
1623# ifdef __MINGW32__
1624 uint64_t id1, id2;
1625# endif
daad4fd5 1626#endif
4ee9c684 1627
fc3d374a 1628 char *path = fc_strdup (name, len);
4ee9c684 1629
1630 /* If the filename doesn't exist, then there is no match with the
25a5ce27 1631 existing file. */
4ee9c684 1632
714f1fe2 1633 if (TEMP_FAILURE_RETRY (stat (path, &st)) < 0)
fc3d374a 1634 {
1635 ret = 0;
1636 goto done;
1637 }
4ee9c684 1638
daad4fd5 1639#ifdef HAVE_WORKING_STAT
01cd2c93 1640 s = (unix_stream *) (u->s);
fc3d374a 1641 ret = (st.st_dev == s->st_dev) && (st.st_ino == s->st_ino);
1642 goto done;
daad4fd5 1643#else
c0ecd33c 1644
1645# ifdef __MINGW32__
1646 /* We try to match files by a unique ID. On some filesystems (network
1647 fs and FAT), we can't generate this unique ID, and will simply compare
1648 filenames. */
1649 id1 = id_from_path (path);
1650 id2 = id_from_fd (((unix_stream *) (u->s))->fd);
1651 if (id1 || id2)
fc3d374a 1652 {
1653 ret = (id1 == id2);
1654 goto done;
1655 }
c0ecd33c 1656# endif
98044b92 1657 if (u->filename)
1658 ret = (strcmp(path, u->filename) == 0);
1659 else
1660 ret = 0;
daad4fd5 1661#endif
fc3d374a 1662 done:
1663 free (path);
1664 return ret;
4ee9c684 1665}
1666
1667
60c514ba 1668#ifdef HAVE_WORKING_STAT
f6854450 1669# define FIND_FILE0_DECL struct stat *st
60c514ba 1670# define FIND_FILE0_ARGS st
1671#else
8d832ee4 1672# define FIND_FILE0_DECL uint64_t id, const char *path
1673# define FIND_FILE0_ARGS id, path
60c514ba 1674#endif
1675
4ee9c684 1676/* find_file0()-- Recursive work function for find_file() */
1677
f02dd226 1678static gfc_unit *
60c514ba 1679find_file0 (gfc_unit *u, FIND_FILE0_DECL)
4ee9c684 1680{
f02dd226 1681 gfc_unit *v;
c0ecd33c 1682#if defined(__MINGW32__) && !HAVE_WORKING_STAT
1683 uint64_t id1;
1684#endif
4ee9c684 1685
1686 if (u == NULL)
1687 return NULL;
1688
daad4fd5 1689#ifdef HAVE_WORKING_STAT
01cd2c93 1690 if (u->s != NULL)
1691 {
1692 unix_stream *s = (unix_stream *) (u->s);
1693 if (st[0].st_dev == s->st_dev && st[0].st_ino == s->st_ino)
1694 return u;
1695 }
daad4fd5 1696#else
c0ecd33c 1697# ifdef __MINGW32__
1698 if (u->s && ((id1 = id_from_fd (((unix_stream *) u->s)->fd)) || id1))
1699 {
1700 if (id == id1)
1701 return u;
1702 }
1703 else
1704# endif
98044b92 1705 if (u->filename && strcmp (u->filename, path) == 0)
c0ecd33c 1706 return u;
daad4fd5 1707#endif
4ee9c684 1708
60c514ba 1709 v = find_file0 (u->left, FIND_FILE0_ARGS);
4ee9c684 1710 if (v != NULL)
1711 return v;
1712
60c514ba 1713 v = find_file0 (u->right, FIND_FILE0_ARGS);
4ee9c684 1714 if (v != NULL)
1715 return v;
1716
1717 return NULL;
1718}
1719
1720
1721/* find_file()-- Take the current filename and see if there is a unit
25a5ce27 1722 that has the file already open. Returns a pointer to the unit if so. */
4ee9c684 1723
f02dd226 1724gfc_unit *
60c514ba 1725find_file (const char *file, gfc_charlen_type file_len)
4ee9c684 1726{
f6854450 1727 struct stat st[1];
60c514ba 1728 gfc_unit *u;
c12dc7d7 1729#if defined(__MINGW32__) && !HAVE_WORKING_STAT
1730 uint64_t id = 0ULL;
1731#endif
4ee9c684 1732
fc3d374a 1733 char *path = fc_strdup (file, file_len);
4ee9c684 1734
714f1fe2 1735 if (TEMP_FAILURE_RETRY (stat (path, &st[0])) < 0)
fc3d374a 1736 {
1737 u = NULL;
1738 goto done;
1739 }
4ee9c684 1740
c0ecd33c 1741#if defined(__MINGW32__) && !HAVE_WORKING_STAT
c12dc7d7 1742 id = id_from_path (path);
c0ecd33c 1743#endif
1744
85df3aea 1745 __gthread_mutex_lock (&unit_lock);
60c514ba 1746retry:
1747 u = find_file0 (unit_root, FIND_FILE0_ARGS);
1748 if (u != NULL)
1749 {
1750 /* Fast path. */
1751 if (! __gthread_mutex_trylock (&u->lock))
1752 {
1753 /* assert (u->closed == 0); */
85df3aea 1754 __gthread_mutex_unlock (&unit_lock);
fc3d374a 1755 goto done;
60c514ba 1756 }
1757
1758 inc_waiting_locked (u);
1759 }
85df3aea 1760 __gthread_mutex_unlock (&unit_lock);
60c514ba 1761 if (u != NULL)
1762 {
85df3aea 1763 __gthread_mutex_lock (&u->lock);
60c514ba 1764 if (u->closed)
1765 {
85df3aea 1766 __gthread_mutex_lock (&unit_lock);
1767 __gthread_mutex_unlock (&u->lock);
60c514ba 1768 if (predec_waiting_locked (u) == 0)
5e62a3cc 1769 free (u);
60c514ba 1770 goto retry;
1771 }
1772
1773 dec_waiting_unlocked (u);
1774 }
fc3d374a 1775 done:
1776 free (path);
60c514ba 1777 return u;
1778}
1779
1780static gfc_unit *
1781flush_all_units_1 (gfc_unit *u, int min_unit)
1782{
1783 while (u != NULL)
1784 {
1785 if (u->unit_number > min_unit)
1786 {
1787 gfc_unit *r = flush_all_units_1 (u->left, min_unit);
1788 if (r != NULL)
1789 return r;
1790 }
1791 if (u->unit_number >= min_unit)
1792 {
1793 if (__gthread_mutex_trylock (&u->lock))
1794 return u;
1795 if (u->s)
65f15010 1796 sflush (u->s);
85df3aea 1797 __gthread_mutex_unlock (&u->lock);
60c514ba 1798 }
1799 u = u->right;
1800 }
1801 return NULL;
1802}
1803
1804void
1805flush_all_units (void)
1806{
1807 gfc_unit *u;
1808 int min_unit = 0;
1809
85df3aea 1810 __gthread_mutex_lock (&unit_lock);
60c514ba 1811 do
1812 {
1813 u = flush_all_units_1 (unit_root, min_unit);
1814 if (u != NULL)
1815 inc_waiting_locked (u);
85df3aea 1816 __gthread_mutex_unlock (&unit_lock);
60c514ba 1817 if (u == NULL)
1818 return;
1819
85df3aea 1820 __gthread_mutex_lock (&u->lock);
60c514ba 1821
1822 min_unit = u->unit_number + 1;
1823
1824 if (u->closed == 0)
1825 {
65f15010 1826 sflush (u->s);
85df3aea 1827 __gthread_mutex_lock (&unit_lock);
1828 __gthread_mutex_unlock (&u->lock);
60c514ba 1829 (void) predec_waiting_locked (u);
1830 }
1831 else
1832 {
85df3aea 1833 __gthread_mutex_lock (&unit_lock);
1834 __gthread_mutex_unlock (&u->lock);
60c514ba 1835 if (predec_waiting_locked (u) == 0)
5e62a3cc 1836 free (u);
60c514ba 1837 }
1838 }
1839 while (1);
4ee9c684 1840}
1841
1842
b3db57e8 1843/* Unlock the unit if necessary, based on SHARE flags. */
1844
1845int
1846close_share (gfc_unit *u __attribute__ ((unused)))
1847{
1848 int r = 0;
1849#if defined(HAVE_FCNTL) && defined(F_SETLK) && defined(F_UNLCK)
1850 unix_stream *s = (unix_stream *) u->s;
1851 int fd = s->fd;
1852 struct flock f;
1853
1854 switch (u->flags.share)
1855 {
1856 case SHARE_DENYRW:
1857 case SHARE_DENYNONE:
1858 if (fd != STDOUT_FILENO && fd != STDERR_FILENO && fd != STDIN_FILENO)
1859 {
1860 f.l_start = 0;
1861 f.l_len = 0;
1862 f.l_whence = SEEK_SET;
1863 f.l_type = F_UNLCK;
1864 r = fcntl (fd, F_SETLK, &f);
1865 }
1866 break;
1867 case SHARE_UNSPECIFIED:
1868 default:
1869 break;
1870 }
1871
1872#endif
1873 return r;
1874}
1875
1876
4ee9c684 1877/* file_exists()-- Returns nonzero if the current filename exists on
25a5ce27 1878 the system */
4ee9c684 1879
1880int
60c514ba 1881file_exists (const char *file, gfc_charlen_type file_len)
4ee9c684 1882{
fc3d374a 1883 char *path = fc_strdup (file, file_len);
1884 int res = !(access (path, F_OK));
1885 free (path);
1886 return res;
4ee9c684 1887}
1888
1889
f4e9c676 1890/* file_size()-- Returns the size of the file. */
1891
1892GFC_IO_INT
1893file_size (const char *file, gfc_charlen_type file_len)
1894{
fc3d374a 1895 char *path = fc_strdup (file, file_len);
f6854450 1896 struct stat statbuf;
714f1fe2 1897 int err;
1898 TEMP_FAILURE_RETRY (err = stat (path, &statbuf));
fc3d374a 1899 free (path);
1900 if (err == -1)
f4e9c676 1901 return -1;
f4e9c676 1902 return (GFC_IO_INT) statbuf.st_size;
1903}
4ee9c684 1904
fb35179a 1905static const char yes[] = "YES", no[] = "NO", unknown[] = "UNKNOWN";
4ee9c684 1906
1907/* inquire_sequential()-- Given a fortran string, determine if the
25a5ce27 1908 file is suitable for sequential access. Returns a C-style
1909 string. */
4ee9c684 1910
1911const char *
1912inquire_sequential (const char *string, int len)
1913{
f6854450 1914 struct stat statbuf;
4ee9c684 1915
fc3d374a 1916 if (string == NULL)
1917 return unknown;
1918
1919 char *path = fc_strdup (string, len);
714f1fe2 1920 int err;
1921 TEMP_FAILURE_RETRY (err = stat (path, &statbuf));
fc3d374a 1922 free (path);
1923 if (err == -1)
4ee9c684 1924 return unknown;
1925
1926 if (S_ISREG (statbuf.st_mode) ||
1927 S_ISCHR (statbuf.st_mode) || S_ISFIFO (statbuf.st_mode))
2e1fa727 1928 return unknown;
4ee9c684 1929
1930 if (S_ISDIR (statbuf.st_mode) || S_ISBLK (statbuf.st_mode))
1931 return no;
1932
1933 return unknown;
1934}
1935
1936
1937/* inquire_direct()-- Given a fortran string, determine if the file is
25a5ce27 1938 suitable for direct access. Returns a C-style string. */
4ee9c684 1939
1940const char *
1941inquire_direct (const char *string, int len)
1942{
f6854450 1943 struct stat statbuf;
4ee9c684 1944
fc3d374a 1945 if (string == NULL)
1946 return unknown;
1947
1948 char *path = fc_strdup (string, len);
714f1fe2 1949 int err;
1950 TEMP_FAILURE_RETRY (err = stat (path, &statbuf));
fc3d374a 1951 free (path);
1952 if (err == -1)
4ee9c684 1953 return unknown;
1954
1955 if (S_ISREG (statbuf.st_mode) || S_ISBLK (statbuf.st_mode))
2e1fa727 1956 return unknown;
4ee9c684 1957
1958 if (S_ISDIR (statbuf.st_mode) ||
1959 S_ISCHR (statbuf.st_mode) || S_ISFIFO (statbuf.st_mode))
1960 return no;
1961
1962 return unknown;
1963}
1964
1965
1966/* inquire_formatted()-- Given a fortran string, determine if the file
25a5ce27 1967 is suitable for formatted form. Returns a C-style string. */
4ee9c684 1968
1969const char *
1970inquire_formatted (const char *string, int len)
1971{
f6854450 1972 struct stat statbuf;
4ee9c684 1973
fc3d374a 1974 if (string == NULL)
1975 return unknown;
1976
1977 char *path = fc_strdup (string, len);
714f1fe2 1978 int err;
1979 TEMP_FAILURE_RETRY (err = stat (path, &statbuf));
fc3d374a 1980 free (path);
1981 if (err == -1)
4ee9c684 1982 return unknown;
1983
1984 if (S_ISREG (statbuf.st_mode) ||
1985 S_ISBLK (statbuf.st_mode) ||
1986 S_ISCHR (statbuf.st_mode) || S_ISFIFO (statbuf.st_mode))
2e1fa727 1987 return unknown;
4ee9c684 1988
1989 if (S_ISDIR (statbuf.st_mode))
1990 return no;
1991
1992 return unknown;
1993}
1994
1995
1996/* inquire_unformatted()-- Given a fortran string, determine if the file
25a5ce27 1997 is suitable for unformatted form. Returns a C-style string. */
4ee9c684 1998
1999const char *
2000inquire_unformatted (const char *string, int len)
2001{
4ee9c684 2002 return inquire_formatted (string, len);
2003}
2004
2005
2006/* inquire_access()-- Given a fortran string, determine if the file is
25a5ce27 2007 suitable for access. */
4ee9c684 2008
2009static const char *
2010inquire_access (const char *string, int len, int mode)
2011{
fc3d374a 2012 if (string == NULL)
2013 return no;
2014 char *path = fc_strdup (string, len);
2015 int res = access (path, mode);
2016 free (path);
2017 if (res == -1)
4ee9c684 2018 return no;
2019
2020 return yes;
2021}
2022
2023
2024/* inquire_read()-- Given a fortran string, determine if the file is
25a5ce27 2025 suitable for READ access. */
4ee9c684 2026
2027const char *
2028inquire_read (const char *string, int len)
2029{
4ee9c684 2030 return inquire_access (string, len, R_OK);
2031}
2032
2033
2034/* inquire_write()-- Given a fortran string, determine if the file is
25a5ce27 2035 suitable for READ access. */
4ee9c684 2036
2037const char *
2038inquire_write (const char *string, int len)
2039{
4ee9c684 2040 return inquire_access (string, len, W_OK);
2041}
2042
2043
2044/* inquire_readwrite()-- Given a fortran string, determine if the file is
25a5ce27 2045 suitable for read and write access. */
4ee9c684 2046
2047const char *
2048inquire_readwrite (const char *string, int len)
2049{
4ee9c684 2050 return inquire_access (string, len, R_OK | W_OK);
2051}
2052
2053
60d77e0d 2054int
2055stream_isatty (stream *s)
2056{
2057 return isatty (((unix_stream *) s)->fd);
2058}
2059
57f34837 2060int
2061stream_ttyname (stream *s __attribute__ ((unused)),
25a5ce27 2062 char *buf __attribute__ ((unused)),
57f34837 2063 size_t buflen __attribute__ ((unused)))
2064{
2065#ifdef HAVE_TTYNAME_R
25a5ce27 2066 return ttyname_r (((unix_stream *)s)->fd, buf, buflen);
57f34837 2067#elif defined HAVE_TTYNAME
2068 char *p;
2069 size_t plen;
25a5ce27 2070 p = ttyname (((unix_stream *)s)->fd);
57f34837 2071 if (!p)
2072 return errno;
2073 plen = strlen (p);
2074 if (buflen < plen)
2075 plen = buflen;
2076 memcpy (buf, p, plen);
2077 return 0;
f2c0a16d 2078#else
57f34837 2079 return ENOSYS;
3479b863 2080#endif
57f34837 2081}
2082
3479b863 2083
60d77e0d 2084
4ee9c684 2085
2086/* How files are stored: This is an operating-system specific issue,
2087 and therefore belongs here. There are three cases to consider.
2088
2089 Direct Access:
2090 Records are written as block of bytes corresponding to the record
2091 length of the file. This goes for both formatted and unformatted
2092 records. Positioning is done explicitly for each data transfer,
2093 so positioning is not much of an issue.
2094
2095 Sequential Formatted:
2096 Records are separated by newline characters. The newline character
2097 is prohibited from appearing in a string. If it does, this will be
2098 messed up on the next read. End of file is also the end of a record.
2099
2100 Sequential Unformatted:
2101 In this case, we are merely copying bytes to and from main storage,
2102 yet we need to keep track of varying record lengths. We adopt
2103 the solution used by f2c. Each record contains a pair of length
2104 markers:
2105
84d33b91 2106 Length of record n in bytes
2107 Data of record n
2108 Length of record n in bytes
4ee9c684 2109
84d33b91 2110 Length of record n+1 in bytes
2111 Data of record n+1
2112 Length of record n+1 in bytes
4ee9c684 2113
2114 The length is stored at the end of a record to allow backspacing to the
2115 previous record. Between data transfer statements, the file pointer
2116 is left pointing to the first length of the current record.
2117
2118 ENDFILE records are never explicitly stored.
2119
2120*/