util/os_file: fix double-close()
[mesa.git] / src / util / os_file.c
1 /*
2 * Copyright 2019 Intel Corporation
3 * SPDX-License-Identifier: MIT
4 */
5
6 #include "os_file.h"
7
8 #include <errno.h>
9 #include <fcntl.h>
10 #include <stdlib.h>
11 #include <sys/stat.h>
12
13
14 #if defined(WIN32)
15 #include <io.h>
16 #define open _open
17 #define fdopen _fdopen
18 #define O_CREAT _O_CREAT
19 #define O_EXCL _O_EXCL
20 #define O_WRONLY _O_WRONLY
21 #endif
22
23
24 FILE *
25 os_file_create_unique(const char *filename, int filemode)
26 {
27 int fd = open(filename, O_CREAT | O_EXCL | O_WRONLY, filemode);
28 if (fd == -1)
29 return NULL;
30 return fdopen(fd, "w");
31 }
32
33
34 #if defined(__linux__)
35
36 #include <fcntl.h>
37 #include <sys/stat.h>
38 #include <unistd.h>
39
40
41 static ssize_t
42 readN(int fd, char *buf, size_t len)
43 {
44 int err = -ENODATA;
45 size_t total = 0;
46 do {
47 ssize_t ret = read(fd, buf + total, len - total);
48
49 if (ret < 0)
50 ret = -errno;
51
52 if (ret == -EINTR || ret == -EAGAIN)
53 continue;
54
55 if (ret <= 0) {
56 err = ret;
57 break;
58 }
59
60 total += ret;
61 } while (total != len);
62
63 return total ? (ssize_t)total : err;
64 }
65
66 char *
67 os_read_file(const char *filename)
68 {
69 /* Note that this also serves as a slight margin to avoid a 2x grow when
70 * the file is just a few bytes larger when we read it than when we
71 * fstat'ed it.
72 * The string's NULL terminator is also included in here.
73 */
74 size_t len = 64;
75
76 int fd = open(filename, O_RDONLY);
77 if (fd == -1) {
78 /* errno set by open() */
79 return NULL;
80 }
81
82 /* Pre-allocate a buffer at least the size of the file if we can read
83 * that information.
84 */
85 struct stat stat;
86 if (fstat(fd, &stat) == 0)
87 len += stat.st_size;
88
89 char *buf = malloc(len);
90 if (!buf) {
91 close(fd);
92 errno = -ENOMEM;
93 return NULL;
94 }
95
96 ssize_t actually_read;
97 size_t offset = 0, remaining = len - 1;
98 while ((actually_read = readN(fd, buf + offset, remaining)) == (ssize_t)remaining) {
99 char *newbuf = realloc(buf, 2 * len);
100 if (!newbuf) {
101 free(buf);
102 close(fd);
103 errno = -ENOMEM;
104 return NULL;
105 }
106
107 buf = newbuf;
108 len *= 2;
109 offset += actually_read;
110 remaining = len - offset - 1;
111 }
112
113 close(fd);
114
115 if (actually_read > 0)
116 offset += actually_read;
117
118 /* Final resize to actual size */
119 len = offset + 1;
120 char *newbuf = realloc(buf, len);
121 if (!newbuf) {
122 free(buf);
123 errno = -ENOMEM;
124 return NULL;
125 }
126 buf = newbuf;
127
128 buf[offset] = '\0';
129
130 return buf;
131 }
132
133 #else
134
135 char *
136 os_read_file(const char *filename)
137 {
138 errno = -ENOSYS;
139 return NULL;
140 }
141
142 #endif