Debian Codegraph @

gcc/d/dmd/root/file.d

raw
1 /**
2 * Read a file from disk and store it in memory.
3 *
4 * Copyright: Copyright (C) 1999-2025 by The D Language Foundation, All Rights Reserved
5 * Authors: Walter Bright, https://www.digitalmars.com
6 * License: $(LINK2 https://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
7 * Source: $(LINK2 https://github.com/dlang/dmd/blob/master/compiler/src/dmd/root/file.d, root/_file.d)
8 * Documentation: https://dlang.org/phobos/dmd_root_file.html
9 * Coverage: https://codecov.io/gh/dlang/dmd/src/master/compiler/src/dmd/root/file.d
10 */
11
12 module dmd.root.file;
13
14 import core.stdc.errno;
15 import core.stdc.stdio;
16 import core.stdc.stdlib;
17 import core.stdc.string : strerror;
18 import core.sys.posix.fcntl;
19 import core.sys.posix.unistd;
20 import core.sys.windows.winbase;
21 import core.sys.windows.winnt;
22
23 import dmd.root.filename;
24 import dmd.root.rmem;
25 import dmd.root.string;
26
27 import dmd.common.file;
28 import dmd.common.outbuffer;
29 import dmd.common.smallbuffer;
30
31 nothrow:
32
33 /// Owns a (rmem-managed) buffer.
34 struct Buffer
35 {
36 ubyte[] data;
37
38 nothrow:
39
40 this(this) @disable;
41
42 ~this() pure nothrow
43 {
44 mem.xfree(data.ptr);
45 }
46
47 /// Transfers ownership of the buffer to the caller.
48 ubyte[] extractSlice() pure nothrow @nogc @safe
49 {
50 auto result = data;
51 data = null;
52 return result;
53 }
54 }
55
56 ///
57 struct File
58 {
59 ///
60 static struct ReadResult
61 {
62 bool success;
63 Buffer buffer;
64
65 /// Transfers ownership of the buffer to the caller.
66 ubyte[] extractSlice() pure nothrow @nogc @safe
67 {
68 return buffer.extractSlice();
69 }
70
71 /// ditto
72 /// Include the null-terminator at the end of the buffer in the returned array.
73 ubyte[] extractDataZ() @nogc nothrow pure
74 {
75 auto result = buffer.extractSlice();
76 return result.ptr[0 .. result.length + 1];
77 }
78 }
79
80 nothrow:
81 /** Read the full content of a file, and append it to `buffer`
82 * Params:
83 * name = name of file
84 * buffer = file contents appended to it
85 * Returns:
86 * false = success, true = failed
87 */
88 static bool read(const char[] name, ref OutBuffer buffer)
89 {
90 enum Success = false;
91 enum Failure = true;
92
93 version (Posix)
94 {
95 //printf("File::read('%.*s')\n", cast(int)name.length, name.ptr);
96 int fd = name.toCStringThen!(slice => open(slice.ptr, O_RDONLY));
97 if (fd == -1)
98 {
99 //perror("\topen error");
100 return Failure;
101 }
102 //printf("\tfile opened\n");
103 stat_t statbuf;
104 if (fstat(fd, &statbuf))
105 {
106 //perror("\tfstat error");
107 close(fd);
108 return Failure;
109 }
110 size_t size = cast(size_t)statbuf.st_size;
111 auto buf = buffer.allocate(size);
112 ssize_t numread = .read(fd, buf.ptr, size);
113 if (numread != size)
114 {
115 //perror("\tread error");
116 close(fd);
117 return Failure;
118 }
119 if (close(fd) == -1)
120 {
121 //perror("\tclose error");
122 return Failure;
123 }
124 }
125 else version (Windows)
126 {
127 // work around Windows file path length limitation
128 // (see documentation for extendedPathThen).
129 HANDLE h = name.extendedPathThen!
130 (p => CreateFileW(p.ptr,
131 GENERIC_READ,
132 FILE_SHARE_READ,
133 null,
134 OPEN_EXISTING,
135 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN,
136 null));
137 if (h == INVALID_HANDLE_VALUE)
138 return Failure;
139 DWORD size = GetFileSize(h, null);
140 auto buf = buffer.allocate(size);
141 DWORD numread;
142 if (ReadFile(h, buf.ptr, size, &numread, null) != TRUE ||
143 numread != size)
144 {
145 CloseHandle(h);
146 return Failure;
147 }
148 if (!CloseHandle(h))
149 return Failure;
150 }
151 else
152 {
153 static assert(0);
154 }
155 return Success;
156 }
157
158 /// Write a file, returning `true` on success.
159 static bool write(const(char)* name, const void[] data)
160 {
161 import dmd.common.file : writeFile;
162 return writeFile(name, data);
163 }
164
165 ///ditto
166 static bool write(const(char)[] name, const void[] data)
167 {
168 return name.toCStringThen!((fname) => write(fname.ptr, data));
169 }
170
171 /// Delete a file.
172 extern (C++) static void remove(const(char)* name)
173 {
174 version (Posix)
175 {
176 .remove(name);
177 }
178 else version (Windows)
179 {
180 name.toDString.extendedPathThen!(p => DeleteFileW(p.ptr));
181 }
182 else
183 {
184 static assert(0);
185 }
186 }
187
188 /***************************************************
189 * Update file
190 *
191 * If the file exists and is identical to what is to be written,
192 * merely update the timestamp on the file.
193 * Otherwise, write the file.
194 *
195 * The idea is writes are much slower than reads, and build systems
196 * often wind up generating identical files.
197 * Params:
198 * name = name of file to update
199 * data = updated contents of file
200 * Returns:
201 * `true` on success
202 */
203 static bool update(const(char)* namez, const void[] data)
204 {
205 enum log = false;
206 if (log) printf("update %s\n", namez);
207
208 if (data.length != File.size(namez))
209 return write(namez, data); // write new file
210
211 if (log) printf("same size\n");
212
213 /* The file already exists, and is the same size.
214 * Read it in, and compare for equality.
215 */
216 //if (FileMapping!(const ubyte)(namez)[] != data[])
217 return write(namez, data); // contents not same, so write new file
218 //if (log) printf("same contents\n");
219
220 /* Contents are identical, so set timestamp of existing file to current time
221 */
222 //return touch(namez);
223 }
224
225 ///ditto
226 static bool update(const(char)[] name, const void[] data)
227 {
228 return name.toCStringThen!(fname => update(fname.ptr, data));
229 }
230
231 /// Size of a file in bytes.
232 /// Params: namez = null-terminated filename
233 /// Returns: `ulong.max` on any error, the length otherwise.
234 static ulong size(const char* namez)
235 {
236 version (Posix)
237 {
238 stat_t buf;
239 if (stat(namez, &buf) == 0)
240 return buf.st_size;
241 }
242 else version (Windows)
243 {
244 const nameStr = namez.toDString();
245 import core.sys.windows.windows;
246 WIN32_FILE_ATTRIBUTE_DATA fad = void;
247 // Doesn't exist, not a regular file, different size
248 if (nameStr.extendedPathThen!(p => GetFileAttributesExW(p.ptr, GET_FILEEX_INFO_LEVELS.GetFileExInfoStandard, &fad)) != 0)
249 return (ulong(fad.nFileSizeHigh) << 32UL) | fad.nFileSizeLow;
250 }
251 else static assert(0);
252 // Error cases go here.
253 return ulong.max;
254 }
255 }
256
257 private
258 {
259 version (linux) version (PPC)
260 {
261 // https://issues.dlang.org/show_bug.cgi?id=22823
262 // Define our own version of stat_t, as older versions of the compiler
263 // had the st_size field at the wrong offset on PPC.
264 alias stat_t_imported = core.sys.posix.sys.stat.stat_t;
265 static if (stat_t_imported.st_size.offsetof != 48)
266 {
267 extern (C) nothrow @nogc:
268 struct stat_t
269 {
270 ulong[6] __pad1;
271 ulong st_size;
272 ulong[6] __pad2;
273 }
274 version (CRuntime_Glibc)
275 {
276 int fstat64(int, stat_t*) @trusted;
277 alias fstat = fstat64;
278 int stat64(const scope char*, stat_t*) @system;
279 alias stat = stat64;
280 }
281 else
282 {
283 int fstat(int, stat_t*) @trusted;
284 int stat(const scope char*, stat_t*) @system;
285 }
286 }
287 }
288 }