blob: 3e0a4f5aab97466b412bf3fb83f23b1a25ff2ec6 [file] [log] [blame]
Rafael Espindolaf1fc3822013-06-26 19:33:03 +00001//===-- Path.cpp - Implement OS Path Concept ------------------------------===//
Michael J. Spencerebad2f92010-11-29 22:28:51 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Rafael Espindolaf1fc3822013-06-26 19:33:03 +000010// This file implements the operating system Path API.
Michael J. Spencerebad2f92010-11-29 22:28:51 +000011//
12//===----------------------------------------------------------------------===//
13
Rui Ueyama5c69ff52014-09-11 22:34:32 +000014#include "llvm/Support/COFF.h"
15#include "llvm/Support/Endian.h"
Rafael Espindola2a826e42014-06-13 17:20:48 +000016#include "llvm/Support/Errc.h"
Michael J. Spencerebad2f92010-11-29 22:28:51 +000017#include "llvm/Support/ErrorHandling.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include "llvm/Support/FileSystem.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000019#include "llvm/Support/Path.h"
Aaron Ballman07e76182014-02-11 03:40:14 +000020#include "llvm/Support/Process.h"
Michael J. Spencerebad2f92010-11-29 22:28:51 +000021#include <cctype>
Michael J. Spencer848f46b2010-12-28 01:49:01 +000022#include <cstdio>
23#include <cstring>
Rafael Espindola6d354812013-07-16 19:44:17 +000024#include <fcntl.h>
Rafael Espindola4526b1d2013-06-18 17:01:00 +000025
26#if !defined(_MSC_VER) && !defined(__MINGW32__)
Douglas Gregora86ddf02013-03-21 21:46:10 +000027#include <unistd.h>
Rafael Espindola4526b1d2013-06-18 17:01:00 +000028#else
29#include <io.h>
Douglas Gregora86ddf02013-03-21 21:46:10 +000030#endif
Michael J. Spencerebad2f92010-11-29 22:28:51 +000031
Rafael Espindola7a0b6402014-02-24 03:07:41 +000032using namespace llvm;
33
Michael J. Spencerebad2f92010-11-29 22:28:51 +000034namespace {
35 using llvm::StringRef;
Zhanyong Wan606bb1a2011-02-11 21:24:40 +000036 using llvm::sys::path::is_separator;
Michael J. Spencerebad2f92010-11-29 22:28:51 +000037
38#ifdef LLVM_ON_WIN32
Benjamin Kramer5e4f0a42012-02-08 13:13:47 +000039 const char *separators = "\\/";
Alp Tokercb402912014-01-24 17:20:08 +000040 const char preferred_separator = '\\';
Michael J. Spencerebad2f92010-11-29 22:28:51 +000041#else
Benjamin Kramer5e4f0a42012-02-08 13:13:47 +000042 const char separators = '/';
Alp Tokercb402912014-01-24 17:20:08 +000043 const char preferred_separator = '/';
Michael J. Spencerebad2f92010-11-29 22:28:51 +000044#endif
45
Benjamin Kramercb520cd2010-12-17 18:59:09 +000046 StringRef find_first_component(StringRef path) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +000047 // Look for this first component in the following order.
48 // * empty (in this case we return an empty string)
49 // * either C: or {//,\\}net.
50 // * {/,\}
51 // * {.,..}
52 // * {file,directory}name
53
54 if (path.empty())
55 return path;
56
Michael J. Spencerbfea3c72010-12-07 03:57:48 +000057#ifdef LLVM_ON_WIN32
Michael J. Spencerebad2f92010-11-29 22:28:51 +000058 // C:
Guy Benyei83c74e92013-02-12 21:21:59 +000059 if (path.size() >= 2 && std::isalpha(static_cast<unsigned char>(path[0])) &&
60 path[1] == ':')
Benjamin Kramerffa42ce2010-12-17 20:27:37 +000061 return path.substr(0, 2);
Michael J. Spencerbfea3c72010-12-07 03:57:48 +000062#endif
Michael J. Spencerebad2f92010-11-29 22:28:51 +000063
64 // //net
65 if ((path.size() > 2) &&
Michael J. Spencerbfea3c72010-12-07 03:57:48 +000066 is_separator(path[0]) &&
67 path[0] == path[1] &&
68 !is_separator(path[2])) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +000069 // Find the next directory separator.
Michael J. Spencerbfea3c72010-12-07 03:57:48 +000070 size_t end = path.find_first_of(separators, 2);
Benjamin Kramerffa42ce2010-12-17 20:27:37 +000071 return path.substr(0, end);
Michael J. Spencerebad2f92010-11-29 22:28:51 +000072 }
73
74 // {/,\}
Michael J. Spencerbfea3c72010-12-07 03:57:48 +000075 if (is_separator(path[0]))
Benjamin Kramerffa42ce2010-12-17 20:27:37 +000076 return path.substr(0, 1);
Michael J. Spencerebad2f92010-11-29 22:28:51 +000077
78 if (path.startswith(".."))
Benjamin Kramerffa42ce2010-12-17 20:27:37 +000079 return path.substr(0, 2);
Michael J. Spencerebad2f92010-11-29 22:28:51 +000080
81 if (path[0] == '.')
Benjamin Kramerffa42ce2010-12-17 20:27:37 +000082 return path.substr(0, 1);
Michael J. Spencerebad2f92010-11-29 22:28:51 +000083
84 // * {file,directory}name
Tareq A. Siraj73537ea2013-08-12 17:10:49 +000085 size_t end = path.find_first_of(separators);
Benjamin Kramerffa42ce2010-12-17 20:27:37 +000086 return path.substr(0, end);
Michael J. Spencerebad2f92010-11-29 22:28:51 +000087 }
Michael J. Spencer545cbdf2010-11-30 23:28:07 +000088
Benjamin Kramer292b44b2010-12-17 18:19:06 +000089 size_t filename_pos(StringRef str) {
Michael J. Spencer545cbdf2010-11-30 23:28:07 +000090 if (str.size() == 2 &&
91 is_separator(str[0]) &&
Michael J. Spencerbfea3c72010-12-07 03:57:48 +000092 str[0] == str[1])
Michael J. Spencer545cbdf2010-11-30 23:28:07 +000093 return 0;
94
95 if (str.size() > 0 && is_separator(str[str.size() - 1]))
96 return str.size() - 1;
97
98 size_t pos = str.find_last_of(separators, str.size() - 1);
99
100#ifdef LLVM_ON_WIN32
Zachary Turner3e766432015-02-11 21:16:35 +0000101 if (pos == StringRef::npos) {
102 // Skip the drive letter, if one exists.
103 if (str.size() >= 2 && str[1] == ':')
104 pos = 2;
105 }
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000106#endif
107
108 if (pos == StringRef::npos ||
109 (pos == 1 && is_separator(str[0])))
110 return 0;
111
112 return pos + 1;
113 }
114
Benjamin Kramer292b44b2010-12-17 18:19:06 +0000115 size_t root_dir_start(StringRef str) {
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000116 // case "c:/"
117#ifdef LLVM_ON_WIN32
118 if (str.size() > 2 &&
119 str[1] == ':' &&
120 is_separator(str[2]))
121 return 2;
122#endif
123
124 // case "//"
125 if (str.size() == 2 &&
126 is_separator(str[0]) &&
127 str[0] == str[1])
128 return StringRef::npos;
129
130 // case "//net"
131 if (str.size() > 3 &&
132 is_separator(str[0]) &&
133 str[0] == str[1] &&
134 !is_separator(str[2])) {
135 return str.find_first_of(separators, 2);
136 }
137
138 // case "/"
139 if (str.size() > 0 && is_separator(str[0]))
140 return 0;
141
142 return StringRef::npos;
143 }
144
Benjamin Kramer292b44b2010-12-17 18:19:06 +0000145 size_t parent_path_end(StringRef path) {
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000146 size_t end_pos = filename_pos(path);
147
148 bool filename_was_sep = path.size() > 0 && is_separator(path[end_pos]);
149
150 // Skip separators except for root dir.
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000151 size_t root_dir_pos = root_dir_start(path.substr(0, end_pos));
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000152
153 while(end_pos > 0 &&
154 (end_pos - 1) != root_dir_pos &&
155 is_separator(path[end_pos - 1]))
156 --end_pos;
157
158 if (end_pos == 1 && root_dir_pos == 0 && filename_was_sep)
159 return StringRef::npos;
160
161 return end_pos;
162 }
Zhanyong Wan606bb1a2011-02-11 21:24:40 +0000163} // end unnamed namespace
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000164
Rafael Espindolae79a8722013-06-28 03:48:47 +0000165enum FSEntity {
166 FS_Dir,
167 FS_File,
168 FS_Name
169};
170
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000171static std::error_code createUniqueEntity(const Twine &Model, int &ResultFD,
172 SmallVectorImpl<char> &ResultPath,
173 bool MakeAbsolute, unsigned Mode,
174 FSEntity Type) {
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000175 SmallString<128> ModelStorage;
176 Model.toVector(ModelStorage);
177
178 if (MakeAbsolute) {
179 // Make model absolute by prepending a temp directory if it's not already.
180 if (!sys::path::is_absolute(Twine(ModelStorage))) {
181 SmallString<128> TDir;
Rafael Espindola016a6d52014-08-26 14:47:52 +0000182 sys::path::system_temp_directory(true, TDir);
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000183 sys::path::append(TDir, Twine(ModelStorage));
184 ModelStorage.swap(TDir);
185 }
186 }
187
188 // From here on, DO NOT modify model. It may be needed if the randomly chosen
189 // path already exists.
190 ResultPath = ModelStorage;
191 // Null terminate.
192 ResultPath.push_back(0);
193 ResultPath.pop_back();
194
195retry_random_path:
196 // Replace '%' with random chars.
197 for (unsigned i = 0, e = ModelStorage.size(); i != e; ++i) {
198 if (ModelStorage[i] == '%')
199 ResultPath[i] = "0123456789abcdef"[sys::Process::GetRandomNumber() & 15];
200 }
201
202 // Try to open + create the file.
203 switch (Type) {
204 case FS_File: {
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000205 if (std::error_code EC =
Rafael Espindola90c7f1c2014-02-24 18:20:12 +0000206 sys::fs::openFileForWrite(Twine(ResultPath.begin()), ResultFD,
207 sys::fs::F_RW | sys::fs::F_Excl, Mode)) {
Rafael Espindola2a826e42014-06-13 17:20:48 +0000208 if (EC == errc::file_exists)
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000209 goto retry_random_path;
210 return EC;
211 }
212
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000213 return std::error_code();
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000214 }
215
216 case FS_Name: {
Rafael Espindola281f23a2014-09-11 20:30:02 +0000217 std::error_code EC =
218 sys::fs::access(ResultPath.begin(), sys::fs::AccessMode::Exist);
219 if (EC == errc::no_such_file_or_directory)
220 return std::error_code();
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000221 if (EC)
222 return EC;
Rafael Espindola281f23a2014-09-11 20:30:02 +0000223 goto retry_random_path;
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000224 }
225
226 case FS_Dir: {
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000227 if (std::error_code EC =
228 sys::fs::create_directory(ResultPath.begin(), false)) {
Rafael Espindola2a826e42014-06-13 17:20:48 +0000229 if (EC == errc::file_exists)
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000230 goto retry_random_path;
231 return EC;
232 }
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000233 return std::error_code();
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000234 }
235 }
236 llvm_unreachable("Invalid Type");
237}
Rafael Espindolae79a8722013-06-28 03:48:47 +0000238
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000239namespace llvm {
240namespace sys {
241namespace path {
242
Benjamin Kramer292b44b2010-12-17 18:19:06 +0000243const_iterator begin(StringRef path) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000244 const_iterator i;
245 i.Path = path;
246 i.Component = find_first_component(path);
247 i.Position = 0;
248 return i;
249}
250
Benjamin Kramer292b44b2010-12-17 18:19:06 +0000251const_iterator end(StringRef path) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000252 const_iterator i;
253 i.Path = path;
254 i.Position = path.size();
255 return i;
256}
257
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000258const_iterator &const_iterator::operator++() {
259 assert(Position < Path.size() && "Tried to increment past end!");
260
261 // Increment Position to past the current component
262 Position += Component.size();
263
264 // Check for end.
265 if (Position == Path.size()) {
266 Component = StringRef();
267 return *this;
268 }
269
270 // Both POSIX and Windows treat paths that begin with exactly two separators
271 // specially.
272 bool was_net = Component.size() > 2 &&
273 is_separator(Component[0]) &&
274 Component[1] == Component[0] &&
275 !is_separator(Component[2]);
276
277 // Handle separators.
278 if (is_separator(Path[Position])) {
279 // Root dir.
280 if (was_net
281#ifdef LLVM_ON_WIN32
282 // c:/
283 || Component.endswith(":")
284#endif
285 ) {
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000286 Component = Path.substr(Position, 1);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000287 return *this;
288 }
289
290 // Skip extra separators.
291 while (Position != Path.size() &&
292 is_separator(Path[Position])) {
293 ++Position;
294 }
295
296 // Treat trailing '/' as a '.'.
297 if (Position == Path.size()) {
298 --Position;
299 Component = ".";
300 return *this;
301 }
302 }
303
304 // Find next component.
305 size_t end_pos = Path.find_first_of(separators, Position);
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000306 Component = Path.slice(Position, end_pos);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000307
308 return *this;
309}
310
Justin Bogner487e7642014-08-04 17:36:41 +0000311bool const_iterator::operator==(const const_iterator &RHS) const {
312 return Path.begin() == RHS.Path.begin() && Position == RHS.Position;
313}
314
315ptrdiff_t const_iterator::operator-(const const_iterator &RHS) const {
316 return Position - RHS.Position;
317}
318
319reverse_iterator rbegin(StringRef Path) {
320 reverse_iterator I;
321 I.Path = Path;
322 I.Position = Path.size();
323 return ++I;
324}
325
326reverse_iterator rend(StringRef Path) {
327 reverse_iterator I;
328 I.Path = Path;
329 I.Component = Path.substr(0, 0);
330 I.Position = 0;
331 return I;
332}
333
334reverse_iterator &reverse_iterator::operator++() {
Ben Langmuir8d116392014-03-05 19:56:30 +0000335 // If we're at the end and the previous char was a '/', return '.' unless
336 // we are the root path.
337 size_t root_dir_pos = root_dir_start(Path);
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000338 if (Position == Path.size() &&
Ben Langmuir8d116392014-03-05 19:56:30 +0000339 Path.size() > root_dir_pos + 1 &&
340 is_separator(Path[Position - 1])) {
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000341 --Position;
342 Component = ".";
343 return *this;
344 }
345
346 // Skip separators unless it's the root directory.
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000347 size_t end_pos = Position;
348
349 while(end_pos > 0 &&
350 (end_pos - 1) != root_dir_pos &&
351 is_separator(Path[end_pos - 1]))
352 --end_pos;
353
354 // Find next separator.
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000355 size_t start_pos = filename_pos(Path.substr(0, end_pos));
356 Component = Path.slice(start_pos, end_pos);
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000357 Position = start_pos;
358 return *this;
359}
360
Justin Bogner487e7642014-08-04 17:36:41 +0000361bool reverse_iterator::operator==(const reverse_iterator &RHS) const {
362 return Path.begin() == RHS.Path.begin() && Component == RHS.Component &&
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000363 Position == RHS.Position;
364}
365
Craig Topper6dc4a8bc2014-08-30 16:48:02 +0000366StringRef root_path(StringRef path) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000367 const_iterator b = begin(path),
368 pos = b,
369 e = end(path);
370 if (b != e) {
371 bool has_net = b->size() > 2 && is_separator((*b)[0]) && (*b)[1] == (*b)[0];
372 bool has_drive =
373#ifdef LLVM_ON_WIN32
374 b->endswith(":");
375#else
376 false;
377#endif
378
379 if (has_net || has_drive) {
380 if ((++pos != e) && is_separator((*pos)[0])) {
381 // {C:/,//net/}, so get the first two components.
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000382 return path.substr(0, b->size() + pos->size());
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000383 } else {
384 // just {C:,//net}, return the first component.
Michael J. Spencerf616b212010-12-07 17:04:04 +0000385 return *b;
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000386 }
387 }
388
389 // POSIX style root directory.
390 if (is_separator((*b)[0])) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000391 return *b;
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000392 }
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000393 }
394
Michael J. Spencerf616b212010-12-07 17:04:04 +0000395 return StringRef();
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000396}
397
Craig Topper6dc4a8bc2014-08-30 16:48:02 +0000398StringRef root_name(StringRef path) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000399 const_iterator b = begin(path),
400 e = end(path);
401 if (b != e) {
402 bool has_net = b->size() > 2 && is_separator((*b)[0]) && (*b)[1] == (*b)[0];
403 bool has_drive =
404#ifdef LLVM_ON_WIN32
405 b->endswith(":");
406#else
407 false;
408#endif
409
410 if (has_net || has_drive) {
411 // just {C:,//net}, return the first component.
Michael J. Spencerf616b212010-12-07 17:04:04 +0000412 return *b;
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000413 }
414 }
415
416 // No path or no name.
Michael J. Spencerf616b212010-12-07 17:04:04 +0000417 return StringRef();
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000418}
419
Craig Topper6dc4a8bc2014-08-30 16:48:02 +0000420StringRef root_directory(StringRef path) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000421 const_iterator b = begin(path),
422 pos = b,
423 e = end(path);
424 if (b != e) {
425 bool has_net = b->size() > 2 && is_separator((*b)[0]) && (*b)[1] == (*b)[0];
426 bool has_drive =
427#ifdef LLVM_ON_WIN32
428 b->endswith(":");
429#else
430 false;
431#endif
432
433 if ((has_net || has_drive) &&
434 // {C:,//net}, skip to the next component.
435 (++pos != e) && is_separator((*pos)[0])) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000436 return *pos;
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000437 }
438
439 // POSIX style root directory.
440 if (!has_net && is_separator((*b)[0])) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000441 return *b;
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000442 }
443 }
444
445 // No path or no root.
Michael J. Spencerf616b212010-12-07 17:04:04 +0000446 return StringRef();
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000447}
448
Craig Topper6dc4a8bc2014-08-30 16:48:02 +0000449StringRef relative_path(StringRef path) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000450 StringRef root = root_path(path);
Michael J. Spencere6462392012-02-29 00:06:24 +0000451 return path.substr(root.size());
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000452}
453
Michael J. Spencer1e090f02010-12-07 03:57:37 +0000454void append(SmallVectorImpl<char> &path, const Twine &a,
455 const Twine &b,
456 const Twine &c,
457 const Twine &d) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000458 SmallString<32> a_storage;
459 SmallString<32> b_storage;
460 SmallString<32> c_storage;
461 SmallString<32> d_storage;
462
463 SmallVector<StringRef, 4> components;
464 if (!a.isTriviallyEmpty()) components.push_back(a.toStringRef(a_storage));
465 if (!b.isTriviallyEmpty()) components.push_back(b.toStringRef(b_storage));
466 if (!c.isTriviallyEmpty()) components.push_back(c.toStringRef(c_storage));
467 if (!d.isTriviallyEmpty()) components.push_back(d.toStringRef(d_storage));
468
469 for (SmallVectorImpl<StringRef>::const_iterator i = components.begin(),
470 e = components.end();
471 i != e; ++i) {
472 bool path_has_sep = !path.empty() && is_separator(path[path.size() - 1]);
473 bool component_has_sep = !i->empty() && is_separator((*i)[0]);
Michael J. Spencerf616b212010-12-07 17:04:04 +0000474 bool is_root_name = has_root_name(*i);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000475
476 if (path_has_sep) {
477 // Strip separators from beginning of component.
478 size_t loc = i->find_first_not_of(separators);
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000479 StringRef c = i->substr(loc);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000480
481 // Append it.
482 path.append(c.begin(), c.end());
483 continue;
484 }
485
Michael J. Spencer95e4ac12010-12-06 04:28:23 +0000486 if (!component_has_sep && !(path.empty() || is_root_name)) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000487 // Add a separator.
Alp Tokercb402912014-01-24 17:20:08 +0000488 path.push_back(preferred_separator);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000489 }
490
491 path.append(i->begin(), i->end());
492 }
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000493}
494
Argyrios Kyrtzidisa61736f2011-02-15 17:51:19 +0000495void append(SmallVectorImpl<char> &path,
496 const_iterator begin, const_iterator end) {
497 for (; begin != end; ++begin)
498 path::append(path, *begin);
499}
500
Craig Topper6dc4a8bc2014-08-30 16:48:02 +0000501StringRef parent_path(StringRef path) {
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000502 size_t end_pos = parent_path_end(path);
503 if (end_pos == StringRef::npos)
Michael J. Spencerf616b212010-12-07 17:04:04 +0000504 return StringRef();
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000505 else
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000506 return path.substr(0, end_pos);
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000507}
508
Michael J. Spencer1e090f02010-12-07 03:57:37 +0000509void remove_filename(SmallVectorImpl<char> &path) {
Michael J. Spencer9c594092010-12-01 00:52:28 +0000510 size_t end_pos = parent_path_end(StringRef(path.begin(), path.size()));
Michael J. Spencer1e090f02010-12-07 03:57:37 +0000511 if (end_pos != StringRef::npos)
512 path.set_size(end_pos);
Michael J. Spencer9c594092010-12-01 00:52:28 +0000513}
514
Michael J. Spencerf616b212010-12-07 17:04:04 +0000515void replace_extension(SmallVectorImpl<char> &path, const Twine &extension) {
Michael J. Spencerfb3a95d2010-12-01 00:52:55 +0000516 StringRef p(path.begin(), path.size());
517 SmallString<32> ext_storage;
518 StringRef ext = extension.toStringRef(ext_storage);
519
520 // Erase existing extension.
521 size_t pos = p.find_last_of('.');
522 if (pos != StringRef::npos && pos >= filename_pos(p))
523 path.set_size(pos);
524
525 // Append '.' if needed.
526 if (ext.size() > 0 && ext[0] != '.')
527 path.push_back('.');
528
529 // Append extension.
530 path.append(ext.begin(), ext.end());
Michael J. Spencerfb3a95d2010-12-01 00:52:55 +0000531}
532
Michael J. Spencer1e090f02010-12-07 03:57:37 +0000533void native(const Twine &path, SmallVectorImpl<char> &result) {
Benjamin Kramerbd4ac9b2013-09-11 10:45:21 +0000534 assert((!path.isSingleStringRef() ||
535 path.getSingleStringRef().data() != result.data()) &&
536 "path and result are not allowed to overlap!");
Michael J. Spencer80025002010-12-01 02:48:27 +0000537 // Clear result.
Michael J. Spencer98c7a112010-12-07 01:23:19 +0000538 result.clear();
Michael J. Spencer80025002010-12-01 02:48:27 +0000539 path.toVector(result);
Benjamin Kramerbd4ac9b2013-09-11 10:45:21 +0000540 native(result);
541}
542
Rafael Espindolad649b9d2014-08-08 21:29:34 +0000543void native(SmallVectorImpl<char> &Path) {
Benjamin Kramerbd4ac9b2013-09-11 10:45:21 +0000544#ifdef LLVM_ON_WIN32
Rafael Espindola674ef1d2014-08-08 22:09:31 +0000545 std::replace(Path.begin(), Path.end(), '/', '\\');
Rafael Espindolad649b9d2014-08-08 21:29:34 +0000546#else
547 for (auto PI = Path.begin(), PE = Path.end(); PI < PE; ++PI) {
548 if (*PI == '\\') {
549 auto PN = PI + 1;
550 if (PN < PE && *PN == '\\')
551 ++PI; // increment once, the for loop will move over the escaped slash
552 else
553 *PI = '/';
554 }
555 }
Michael J. Spencer80025002010-12-01 02:48:27 +0000556#endif
Michael J. Spencer80025002010-12-01 02:48:27 +0000557}
558
Craig Topper6dc4a8bc2014-08-30 16:48:02 +0000559StringRef filename(StringRef path) {
Justin Bogner487e7642014-08-04 17:36:41 +0000560 return *rbegin(path);
Michael J. Spencer14269202010-12-01 03:18:17 +0000561}
562
Craig Topper6dc4a8bc2014-08-30 16:48:02 +0000563StringRef stem(StringRef path) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000564 StringRef fname = filename(path);
Michael J. Spencer956955e2010-12-01 03:18:33 +0000565 size_t pos = fname.find_last_of('.');
566 if (pos == StringRef::npos)
Michael J. Spencerf616b212010-12-07 17:04:04 +0000567 return fname;
Michael J. Spencer956955e2010-12-01 03:18:33 +0000568 else
569 if ((fname.size() == 1 && fname == ".") ||
570 (fname.size() == 2 && fname == ".."))
Michael J. Spencerf616b212010-12-07 17:04:04 +0000571 return fname;
Michael J. Spencer956955e2010-12-01 03:18:33 +0000572 else
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000573 return fname.substr(0, pos);
Michael J. Spencer956955e2010-12-01 03:18:33 +0000574}
575
Craig Topper6dc4a8bc2014-08-30 16:48:02 +0000576StringRef extension(StringRef path) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000577 StringRef fname = filename(path);
Michael J. Spencer87106c52010-12-01 03:37:41 +0000578 size_t pos = fname.find_last_of('.');
579 if (pos == StringRef::npos)
Michael J. Spencerf616b212010-12-07 17:04:04 +0000580 return StringRef();
Michael J. Spencer87106c52010-12-01 03:37:41 +0000581 else
582 if ((fname.size() == 1 && fname == ".") ||
583 (fname.size() == 2 && fname == ".."))
Michael J. Spencerf616b212010-12-07 17:04:04 +0000584 return StringRef();
Michael J. Spencer87106c52010-12-01 03:37:41 +0000585 else
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000586 return fname.substr(pos);
Michael J. Spencer87106c52010-12-01 03:37:41 +0000587}
588
Zhanyong Wan606bb1a2011-02-11 21:24:40 +0000589bool is_separator(char value) {
590 switch(value) {
591#ifdef LLVM_ON_WIN32
592 case '\\': // fall through
593#endif
594 case '/': return true;
595 default: return false;
596 }
597}
598
Yaron Keren15217202014-05-16 13:16:30 +0000599static const char preferred_separator_string[] = { preferred_separator, '\0' };
600
Craig Topper6dc4a8bc2014-08-30 16:48:02 +0000601StringRef get_separator() {
Yaron Keren15217202014-05-16 13:16:30 +0000602 return preferred_separator_string;
603}
604
Michael J. Spencera68282c2010-12-07 18:12:07 +0000605bool has_root_name(const Twine &path) {
Michael J. Spencer112a7692010-12-01 06:03:50 +0000606 SmallString<128> path_storage;
607 StringRef p = path.toStringRef(path_storage);
608
Michael J. Spencerf616b212010-12-07 17:04:04 +0000609 return !root_name(p).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000610}
611
Michael J. Spencera68282c2010-12-07 18:12:07 +0000612bool has_root_directory(const Twine &path) {
Michael J. Spencer112a7692010-12-01 06:03:50 +0000613 SmallString<128> path_storage;
614 StringRef p = path.toStringRef(path_storage);
615
Michael J. Spencerf616b212010-12-07 17:04:04 +0000616 return !root_directory(p).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000617}
618
Michael J. Spencera68282c2010-12-07 18:12:07 +0000619bool has_root_path(const Twine &path) {
Michael J. Spencer112a7692010-12-01 06:03:50 +0000620 SmallString<128> path_storage;
621 StringRef p = path.toStringRef(path_storage);
622
Michael J. Spencerf616b212010-12-07 17:04:04 +0000623 return !root_path(p).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000624}
625
Michael J. Spencer6d4b7e72010-12-20 13:30:28 +0000626bool has_relative_path(const Twine &path) {
627 SmallString<128> path_storage;
628 StringRef p = path.toStringRef(path_storage);
629
630 return !relative_path(p).empty();
631}
632
Michael J. Spencera68282c2010-12-07 18:12:07 +0000633bool has_filename(const Twine &path) {
Michael J. Spencer112a7692010-12-01 06:03:50 +0000634 SmallString<128> path_storage;
635 StringRef p = path.toStringRef(path_storage);
636
Michael J. Spencerf616b212010-12-07 17:04:04 +0000637 return !filename(p).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000638}
639
Michael J. Spencera68282c2010-12-07 18:12:07 +0000640bool has_parent_path(const Twine &path) {
Michael J. Spencer112a7692010-12-01 06:03:50 +0000641 SmallString<128> path_storage;
642 StringRef p = path.toStringRef(path_storage);
643
Michael J. Spencerf616b212010-12-07 17:04:04 +0000644 return !parent_path(p).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000645}
646
Michael J. Spencera68282c2010-12-07 18:12:07 +0000647bool has_stem(const Twine &path) {
Michael J. Spencer112a7692010-12-01 06:03:50 +0000648 SmallString<128> path_storage;
649 StringRef p = path.toStringRef(path_storage);
650
Michael J. Spencerf616b212010-12-07 17:04:04 +0000651 return !stem(p).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000652}
653
Michael J. Spencera68282c2010-12-07 18:12:07 +0000654bool has_extension(const Twine &path) {
Michael J. Spencer112a7692010-12-01 06:03:50 +0000655 SmallString<128> path_storage;
656 StringRef p = path.toStringRef(path_storage);
657
Michael J. Spencerf616b212010-12-07 17:04:04 +0000658 return !extension(p).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000659}
660
Michael J. Spencera68282c2010-12-07 18:12:07 +0000661bool is_absolute(const Twine &path) {
Michael J. Spencera72df5f2010-12-01 06:21:53 +0000662 SmallString<128> path_storage;
663 StringRef p = path.toStringRef(path_storage);
664
Michael J. Spencerf616b212010-12-07 17:04:04 +0000665 bool rootDir = has_root_directory(p),
Michael J. Spencera72df5f2010-12-01 06:21:53 +0000666#ifdef LLVM_ON_WIN32
Michael J. Spencerf616b212010-12-07 17:04:04 +0000667 rootName = has_root_name(p);
Michael J. Spencera72df5f2010-12-01 06:21:53 +0000668#else
Michael J. Spencerf616b212010-12-07 17:04:04 +0000669 rootName = true;
Michael J. Spencera72df5f2010-12-01 06:21:53 +0000670#endif
671
Michael J. Spencerf616b212010-12-07 17:04:04 +0000672 return rootDir && rootName;
Michael J. Spencera72df5f2010-12-01 06:21:53 +0000673}
674
Michael J. Spencera68282c2010-12-07 18:12:07 +0000675bool is_relative(const Twine &path) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000676 return !is_absolute(path);
Michael J. Spencera72df5f2010-12-01 06:21:53 +0000677}
678
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +0000679} // end namespace path
680
681namespace fs {
682
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000683std::error_code getUniqueID(const Twine Path, UniqueID &Result) {
Rafael Espindola7f822a92013-07-29 21:26:49 +0000684 file_status Status;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000685 std::error_code EC = status(Path, Status);
Rafael Espindola7f822a92013-07-29 21:26:49 +0000686 if (EC)
687 return EC;
688 Result = Status.getUniqueID();
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000689 return std::error_code();
Rafael Espindola7f822a92013-07-29 21:26:49 +0000690}
691
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000692std::error_code createUniqueFile(const Twine &Model, int &ResultFd,
693 SmallVectorImpl<char> &ResultPath,
694 unsigned Mode) {
Rafael Espindolac9d2e5b2013-07-05 21:01:08 +0000695 return createUniqueEntity(Model, ResultFd, ResultPath, false, Mode, FS_File);
696}
697
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000698std::error_code createUniqueFile(const Twine &Model,
699 SmallVectorImpl<char> &ResultPath) {
Rafael Espindolac9d2e5b2013-07-05 21:01:08 +0000700 int Dummy;
701 return createUniqueEntity(Model, Dummy, ResultPath, false, 0, FS_Name);
702}
703
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000704static std::error_code
705createTemporaryFile(const Twine &Model, int &ResultFD,
706 llvm::SmallVectorImpl<char> &ResultPath, FSEntity Type) {
Rafael Espindola325fa0f2013-07-05 19:56:49 +0000707 SmallString<128> Storage;
708 StringRef P = Model.toNullTerminatedStringRef(Storage);
709 assert(P.find_first_of(separators) == StringRef::npos &&
710 "Model must be a simple filename.");
711 // Use P.begin() so that createUniqueEntity doesn't need to recreate Storage.
712 return createUniqueEntity(P.begin(), ResultFD, ResultPath,
713 true, owner_read | owner_write, Type);
714}
715
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000716static std::error_code
Rafael Espindola325fa0f2013-07-05 19:56:49 +0000717createTemporaryFile(const Twine &Prefix, StringRef Suffix, int &ResultFD,
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000718 llvm::SmallVectorImpl<char> &ResultPath, FSEntity Type) {
Rafael Espindolad3c89042013-07-25 15:00:17 +0000719 const char *Middle = Suffix.empty() ? "-%%%%%%" : "-%%%%%%.";
720 return createTemporaryFile(Prefix + Middle + Suffix, ResultFD, ResultPath,
Rafael Espindola325fa0f2013-07-05 19:56:49 +0000721 Type);
722}
723
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000724std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
725 int &ResultFD,
726 SmallVectorImpl<char> &ResultPath) {
Rafael Espindola325fa0f2013-07-05 19:56:49 +0000727 return createTemporaryFile(Prefix, Suffix, ResultFD, ResultPath, FS_File);
728}
729
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000730std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
731 SmallVectorImpl<char> &ResultPath) {
Rafael Espindola325fa0f2013-07-05 19:56:49 +0000732 int Dummy;
733 return createTemporaryFile(Prefix, Suffix, Dummy, ResultPath, FS_Name);
734}
735
736
Rafael Espindolae79a8722013-06-28 03:48:47 +0000737// This is a mkdtemp with a different pattern. We use createUniqueEntity mostly
Rafael Espindola31a24432013-06-28 10:55:41 +0000738// for consistency. We should try using mkdtemp.
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000739std::error_code createUniqueDirectory(const Twine &Prefix,
740 SmallVectorImpl<char> &ResultPath) {
Rafael Espindolae79a8722013-06-28 03:48:47 +0000741 int Dummy;
742 return createUniqueEntity(Prefix + "-%%%%%%", Dummy, ResultPath,
743 true, 0, FS_Dir);
Rafael Espindola7ffacc42013-06-27 03:45:31 +0000744}
745
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000746std::error_code make_absolute(SmallVectorImpl<char> &path) {
Michael J. Spencer92903a32010-12-07 03:57:17 +0000747 StringRef p(path.data(), path.size());
748
Daniel Dunbarb23158c2012-02-29 00:20:37 +0000749 bool rootDirectory = path::has_root_directory(p),
750#ifdef LLVM_ON_WIN32
Daniel Dunbar39ea4582012-02-29 00:46:46 +0000751 rootName = path::has_root_name(p);
Daniel Dunbarb23158c2012-02-29 00:20:37 +0000752#else
753 rootName = true;
754#endif
Michael J. Spencer92903a32010-12-07 03:57:17 +0000755
756 // Already absolute.
757 if (rootName && rootDirectory)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000758 return std::error_code();
Michael J. Spencer92903a32010-12-07 03:57:17 +0000759
760 // All of the following conditions will need the current directory.
761 SmallString<128> current_dir;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000762 if (std::error_code ec = current_path(current_dir))
763 return ec;
Michael J. Spencer92903a32010-12-07 03:57:17 +0000764
765 // Relative path. Prepend the current directory.
766 if (!rootName && !rootDirectory) {
767 // Append path to the current directory.
Michael J. Spencer1e090f02010-12-07 03:57:37 +0000768 path::append(current_dir, p);
Michael J. Spencer92903a32010-12-07 03:57:17 +0000769 // Set path to the result.
770 path.swap(current_dir);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000771 return std::error_code();
Michael J. Spencer92903a32010-12-07 03:57:17 +0000772 }
773
774 if (!rootName && rootDirectory) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000775 StringRef cdrn = path::root_name(current_dir);
Michael J. Spencer92903a32010-12-07 03:57:17 +0000776 SmallString<128> curDirRootName(cdrn.begin(), cdrn.end());
Michael J. Spencer1e090f02010-12-07 03:57:37 +0000777 path::append(curDirRootName, p);
Michael J. Spencer92903a32010-12-07 03:57:17 +0000778 // Set path to the result.
779 path.swap(curDirRootName);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000780 return std::error_code();
Michael J. Spencer92903a32010-12-07 03:57:17 +0000781 }
782
783 if (rootName && !rootDirectory) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000784 StringRef pRootName = path::root_name(p);
785 StringRef bRootDirectory = path::root_directory(current_dir);
786 StringRef bRelativePath = path::relative_path(current_dir);
787 StringRef pRelativePath = path::relative_path(p);
Michael J. Spencer92903a32010-12-07 03:57:17 +0000788
789 SmallString<128> res;
Michael J. Spencer1e090f02010-12-07 03:57:37 +0000790 path::append(res, pRootName, bRootDirectory, bRelativePath, pRelativePath);
Michael J. Spencer92903a32010-12-07 03:57:17 +0000791 path.swap(res);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000792 return std::error_code();
Michael J. Spencer92903a32010-12-07 03:57:17 +0000793 }
794
795 llvm_unreachable("All rootName and rootDirectory combinations should have "
796 "occurred above!");
797}
798
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000799std::error_code create_directories(const Twine &Path, bool IgnoreExisting) {
Rafael Espindolab6f72b22014-02-13 16:58:19 +0000800 SmallString<128> PathStorage;
801 StringRef P = Path.toStringRef(PathStorage);
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000802
Rafael Espindolab6f72b22014-02-13 16:58:19 +0000803 // Be optimistic and try to create the directory
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000804 std::error_code EC = create_directory(P, IgnoreExisting);
Rafael Espindolab6f72b22014-02-13 16:58:19 +0000805 // If we succeeded, or had any error other than the parent not existing, just
806 // return it.
Rafael Espindola2a826e42014-06-13 17:20:48 +0000807 if (EC != errc::no_such_file_or_directory)
Rafael Espindolab6f72b22014-02-13 16:58:19 +0000808 return EC;
Michael J. Spencerf616b212010-12-07 17:04:04 +0000809
Rafael Espindolab6f72b22014-02-13 16:58:19 +0000810 // We failed because of a no_such_file_or_directory, try to create the
811 // parent.
812 StringRef Parent = path::parent_path(P);
813 if (Parent.empty())
814 return EC;
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000815
Rafael Espindolab6f72b22014-02-13 16:58:19 +0000816 if ((EC = create_directories(Parent)))
817 return EC;
818
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000819 return create_directory(P, IgnoreExisting);
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000820}
821
Justin Bognercd45f962014-06-19 19:35:39 +0000822std::error_code copy_file(const Twine &From, const Twine &To) {
823 int ReadFD, WriteFD;
824 if (std::error_code EC = openFileForRead(From, ReadFD))
825 return EC;
826 if (std::error_code EC = openFileForWrite(To, WriteFD, F_None)) {
827 close(ReadFD);
828 return EC;
829 }
830
831 const size_t BufSize = 4096;
Dylan Noblesmith42836d92014-08-26 02:03:30 +0000832 char *Buf = new char[BufSize];
Justin Bognercd45f962014-06-19 19:35:39 +0000833 int BytesRead = 0, BytesWritten = 0;
834 for (;;) {
835 BytesRead = read(ReadFD, Buf, BufSize);
836 if (BytesRead <= 0)
837 break;
838 while (BytesRead) {
839 BytesWritten = write(WriteFD, Buf, BytesRead);
840 if (BytesWritten < 0)
841 break;
842 BytesRead -= BytesWritten;
843 }
844 if (BytesWritten < 0)
845 break;
846 }
847 close(ReadFD);
848 close(WriteFD);
Dylan Noblesmith42836d92014-08-26 02:03:30 +0000849 delete[] Buf;
Justin Bognercd45f962014-06-19 19:35:39 +0000850
851 if (BytesRead < 0 || BytesWritten < 0)
852 return std::error_code(errno, std::generic_category());
853 return std::error_code();
854}
855
Michael J. Spencer730f51a2010-12-09 17:37:02 +0000856bool exists(file_status status) {
857 return status_known(status) && status.type() != file_type::file_not_found;
858}
859
860bool status_known(file_status s) {
861 return s.type() != file_type::status_error;
862}
863
864bool is_directory(file_status status) {
865 return status.type() == file_type::directory_file;
866}
867
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000868std::error_code is_directory(const Twine &path, bool &result) {
Michael J. Spencer0d771ed2011-01-11 01:21:55 +0000869 file_status st;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000870 if (std::error_code ec = status(path, st))
Michael J. Spencer0d771ed2011-01-11 01:21:55 +0000871 return ec;
872 result = is_directory(st);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000873 return std::error_code();
Michael J. Spencer0d771ed2011-01-11 01:21:55 +0000874}
875
Michael J. Spencer730f51a2010-12-09 17:37:02 +0000876bool is_regular_file(file_status status) {
877 return status.type() == file_type::regular_file;
878}
879
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000880std::error_code is_regular_file(const Twine &path, bool &result) {
Michael J. Spencer0d771ed2011-01-11 01:21:55 +0000881 file_status st;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000882 if (std::error_code ec = status(path, st))
Michael J. Spencer0d771ed2011-01-11 01:21:55 +0000883 return ec;
884 result = is_regular_file(st);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000885 return std::error_code();
Michael J. Spencer0d771ed2011-01-11 01:21:55 +0000886}
887
Michael J. Spencer730f51a2010-12-09 17:37:02 +0000888bool is_other(file_status status) {
889 return exists(status) &&
890 !is_regular_file(status) &&
Rafael Espindola20063062014-03-20 17:39:04 +0000891 !is_directory(status);
Michael J. Spencer730f51a2010-12-09 17:37:02 +0000892}
893
Juergen Ributzka84ba3422014-12-18 18:19:47 +0000894std::error_code is_other(const Twine &Path, bool &Result) {
895 file_status FileStatus;
896 if (std::error_code EC = status(Path, FileStatus))
897 return EC;
898 Result = is_other(FileStatus);
899 return std::error_code();
900}
901
Benjamin Kramer91ead3c2011-09-14 01:14:36 +0000902void directory_entry::replace_filename(const Twine &filename, file_status st) {
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000903 SmallString<128> path(Path.begin(), Path.end());
904 path::remove_filename(path);
905 path::append(path, filename);
906 Path = path.str();
907 Status = st;
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000908}
909
Michael J. Spencer4f8a8322011-12-13 23:17:12 +0000910/// @brief Identify the magic in magic.
Logan Chienc0f691d2014-06-25 13:46:17 +0000911file_magic identify_magic(StringRef Magic) {
Rafael Espindola9b404292013-06-11 17:22:12 +0000912 if (Magic.size() < 4)
Michael J. Spencer96ebd912012-06-19 05:29:57 +0000913 return file_magic::unknown;
Rafael Espindola9b404292013-06-11 17:22:12 +0000914 switch ((unsigned char)Magic[0]) {
Rui Ueyamafc149a62013-10-15 22:45:38 +0000915 case 0x00: {
Rui Ueyama2acb0582014-09-11 21:09:57 +0000916 // COFF bigobj or short import library file
Rui Ueyamae448f9e2013-11-15 21:22:02 +0000917 if (Magic[1] == (char)0x00 && Magic[2] == (char)0xff &&
Rui Ueyama2acb0582014-09-11 21:09:57 +0000918 Magic[3] == (char)0xff) {
Rui Ueyama5c69ff52014-09-11 22:34:32 +0000919 size_t MinSize = offsetof(COFF::BigObjHeader, UUID) + sizeof(COFF::BigObjMagic);
920 if (Magic.size() < MinSize)
921 return file_magic::coff_import_library;
922
923 int BigObjVersion = *reinterpret_cast<const support::ulittle16_t*>(
924 Magic.data() + offsetof(COFF::BigObjHeader, Version));
925 if (BigObjVersion < COFF::BigObjHeader::MinBigObjectVersion)
926 return file_magic::coff_import_library;
927
928 const char *Start = Magic.data() + offsetof(COFF::BigObjHeader, UUID);
929 if (memcmp(Start, COFF::BigObjMagic, sizeof(COFF::BigObjMagic)) != 0)
930 return file_magic::coff_import_library;
931 return file_magic::coff_object;
Rui Ueyama2acb0582014-09-11 21:09:57 +0000932 }
Rui Ueyamafc149a62013-10-15 22:45:38 +0000933 // Windows resource file
Rui Ueyama50a86e12013-10-16 03:29:49 +0000934 const char Expected[] = { 0, 0, 0, 0, '\x20', 0, 0, 0, '\xff' };
Rui Ueyamafc149a62013-10-15 22:45:38 +0000935 if (Magic.size() >= sizeof(Expected) &&
936 memcmp(Magic.data(), Expected, sizeof(Expected)) == 0)
937 return file_magic::windows_resource;
Rui Ueyama829c4392013-11-14 22:09:08 +0000938 // 0x0000 = COFF unknown machine type
939 if (Magic[1] == 0)
940 return file_magic::coff_object;
Rui Ueyamafc149a62013-10-15 22:45:38 +0000941 break;
942 }
Michael J. Spencer4f8a8322011-12-13 23:17:12 +0000943 case 0xDE: // 0x0B17C0DE = BC wraper
Rafael Espindola9b404292013-06-11 17:22:12 +0000944 if (Magic[1] == (char)0xC0 && Magic[2] == (char)0x17 &&
945 Magic[3] == (char)0x0B)
Michael J. Spencer4f8a8322011-12-13 23:17:12 +0000946 return file_magic::bitcode;
947 break;
948 case 'B':
Rafael Espindola9b404292013-06-11 17:22:12 +0000949 if (Magic[1] == 'C' && Magic[2] == (char)0xC0 && Magic[3] == (char)0xDE)
Michael J. Spencer4f8a8322011-12-13 23:17:12 +0000950 return file_magic::bitcode;
951 break;
952 case '!':
Rafael Espindola9b404292013-06-11 17:22:12 +0000953 if (Magic.size() >= 8)
954 if (memcmp(Magic.data(),"!<arch>\n",8) == 0)
Michael J. Spencer4f8a8322011-12-13 23:17:12 +0000955 return file_magic::archive;
956 break;
957
958 case '\177':
Rafael Espindola823de7c2013-06-11 17:25:45 +0000959 if (Magic.size() >= 18 && Magic[1] == 'E' && Magic[2] == 'L' &&
960 Magic[3] == 'F') {
Rafael Espindola9b404292013-06-11 17:22:12 +0000961 bool Data2MSB = Magic[5] == 2;
Michael J. Spencerb8055cb2013-04-05 20:10:04 +0000962 unsigned high = Data2MSB ? 16 : 17;
963 unsigned low = Data2MSB ? 17 : 16;
Rafael Espindola823de7c2013-06-11 17:25:45 +0000964 if (Magic[high] == 0)
Rafael Espindola9b404292013-06-11 17:22:12 +0000965 switch (Magic[low]) {
Michael J. Spencere368a622015-01-23 21:58:09 +0000966 default: return file_magic::elf;
Michael J. Spencer4f8a8322011-12-13 23:17:12 +0000967 case 1: return file_magic::elf_relocatable;
968 case 2: return file_magic::elf_executable;
969 case 3: return file_magic::elf_shared_object;
970 case 4: return file_magic::elf_core;
971 }
Michael J. Spencerbbd875b2014-11-18 01:14:25 +0000972 else
973 // It's still some type of ELF file.
974 return file_magic::elf;
Michael J. Spencer4f8a8322011-12-13 23:17:12 +0000975 }
976 break;
977
978 case 0xCA:
Rafael Espindola9b404292013-06-11 17:22:12 +0000979 if (Magic[1] == char(0xFE) && Magic[2] == char(0xBA) &&
980 Magic[3] == char(0xBE)) {
Michael J. Spencer4f8a8322011-12-13 23:17:12 +0000981 // This is complicated by an overlap with Java class files.
982 // See the Mach-O section in /usr/share/file/magic for details.
Rafael Espindola9b404292013-06-11 17:22:12 +0000983 if (Magic.size() >= 8 && Magic[7] < 43)
Alexey Samsonove6388e62013-06-18 15:03:28 +0000984 return file_magic::macho_universal_binary;
Michael J. Spencer4f8a8322011-12-13 23:17:12 +0000985 }
986 break;
987
988 // The two magic numbers for mach-o are:
989 // 0xfeedface - 32-bit mach-o
990 // 0xfeedfacf - 64-bit mach-o
991 case 0xFE:
992 case 0xCE:
993 case 0xCF: {
994 uint16_t type = 0;
Rafael Espindola9b404292013-06-11 17:22:12 +0000995 if (Magic[0] == char(0xFE) && Magic[1] == char(0xED) &&
996 Magic[2] == char(0xFA) &&
997 (Magic[3] == char(0xCE) || Magic[3] == char(0xCF))) {
Michael J. Spencer4f8a8322011-12-13 23:17:12 +0000998 /* Native endian */
Rafael Espindola9b404292013-06-11 17:22:12 +0000999 if (Magic.size() >= 16) type = Magic[14] << 8 | Magic[15];
1000 } else if ((Magic[0] == char(0xCE) || Magic[0] == char(0xCF)) &&
1001 Magic[1] == char(0xFA) && Magic[2] == char(0xED) &&
1002 Magic[3] == char(0xFE)) {
Michael J. Spencer4f8a8322011-12-13 23:17:12 +00001003 /* Reverse endian */
Rafael Espindola9b404292013-06-11 17:22:12 +00001004 if (Magic.size() >= 14) type = Magic[13] << 8 | Magic[12];
Michael J. Spencer4f8a8322011-12-13 23:17:12 +00001005 }
1006 switch (type) {
1007 default: break;
1008 case 1: return file_magic::macho_object;
1009 case 2: return file_magic::macho_executable;
1010 case 3: return file_magic::macho_fixed_virtual_memory_shared_lib;
1011 case 4: return file_magic::macho_core;
Rafael Espindola134cc992013-06-10 20:32:27 +00001012 case 5: return file_magic::macho_preload_executable;
Michael J. Spencer4f8a8322011-12-13 23:17:12 +00001013 case 6: return file_magic::macho_dynamically_linked_shared_lib;
1014 case 7: return file_magic::macho_dynamic_linker;
1015 case 8: return file_magic::macho_bundle;
Nick Kledzik2d2b2542014-09-17 00:53:44 +00001016 case 9: return file_magic::macho_dynamically_linked_shared_lib_stub;
Michael J. Spencer4f8a8322011-12-13 23:17:12 +00001017 case 10: return file_magic::macho_dsym_companion;
1018 }
1019 break;
1020 }
1021 case 0xF0: // PowerPC Windows
1022 case 0x83: // Alpha 32-bit
1023 case 0x84: // Alpha 64-bit
1024 case 0x66: // MPS R4000 Windows
1025 case 0x50: // mc68K
1026 case 0x4c: // 80386 Windows
Saleem Abdulrasool9b7c0af2014-03-13 07:02:35 +00001027 case 0xc4: // ARMNT Windows
Rafael Espindola9b404292013-06-11 17:22:12 +00001028 if (Magic[1] == 0x01)
Michael J. Spencer4f8a8322011-12-13 23:17:12 +00001029 return file_magic::coff_object;
1030
1031 case 0x90: // PA-RISC Windows
1032 case 0x68: // mc68K Windows
Rafael Espindola9b404292013-06-11 17:22:12 +00001033 if (Magic[1] == 0x02)
Michael J. Spencer4f8a8322011-12-13 23:17:12 +00001034 return file_magic::coff_object;
1035 break;
1036
David Majnemer50267222014-11-05 06:24:35 +00001037 case 'M': // Possible MS-DOS stub on Windows PE file
1038 if (Magic[1] == 'Z') {
Michael J. Spencer4f8a8322011-12-13 23:17:12 +00001039 uint32_t off =
Rafael Espindola9b404292013-06-11 17:22:12 +00001040 *reinterpret_cast<const support::ulittle32_t*>(Magic.data() + 0x3c);
Michael J. Spencer4f8a8322011-12-13 23:17:12 +00001041 // PE/COFF file, either EXE or DLL.
David Majnemer50267222014-11-05 06:24:35 +00001042 if (off < Magic.size() &&
1043 memcmp(Magic.data()+off, COFF::PEMagic, sizeof(COFF::PEMagic)) == 0)
Michael J. Spencer4f8a8322011-12-13 23:17:12 +00001044 return file_magic::pecoff_executable;
1045 }
1046 break;
1047
1048 case 0x64: // x86-64 Windows.
Rafael Espindola9b404292013-06-11 17:22:12 +00001049 if (Magic[1] == char(0x86))
Michael J. Spencer4f8a8322011-12-13 23:17:12 +00001050 return file_magic::coff_object;
1051 break;
1052
1053 default:
1054 break;
1055 }
1056 return file_magic::unknown;
1057}
1058
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001059std::error_code identify_magic(const Twine &Path, file_magic &Result) {
Rafael Espindolada70bfd2014-06-11 22:53:00 +00001060 int FD;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001061 if (std::error_code EC = openFileForRead(Path, FD))
Rafael Espindolada70bfd2014-06-11 22:53:00 +00001062 return EC;
Michael J. Spencer94b2ab32011-01-15 20:39:36 +00001063
Rafael Espindolada70bfd2014-06-11 22:53:00 +00001064 char Buffer[32];
1065 int Length = read(FD, Buffer, sizeof(Buffer));
Rafael Espindolaa8acef62014-06-25 14:35:59 +00001066 if (close(FD) != 0 || Length < 0)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001067 return std::error_code(errno, std::generic_category());
Rafael Espindolada70bfd2014-06-11 22:53:00 +00001068
1069 Result = identify_magic(StringRef(Buffer, Length));
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001070 return std::error_code();
Michael J. Spencer94b2ab32011-01-15 20:39:36 +00001071}
1072
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001073std::error_code directory_entry::status(file_status &result) const {
Michael J. Spencerf8dc1862011-01-05 16:39:13 +00001074 return fs::status(Path, result);
1075}
1076
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +00001077} // end namespace fs
1078} // end namespace sys
1079} // end namespace llvm
Michael J. Spencerebad2f92010-11-29 22:28:51 +00001080
1081// Include the truly platform-specific parts.
1082#if defined(LLVM_ON_UNIX)
Rafael Espindolaf1fc3822013-06-26 19:33:03 +00001083#include "Unix/Path.inc"
Michael J. Spencerebad2f92010-11-29 22:28:51 +00001084#endif
1085#if defined(LLVM_ON_WIN32)
Rafael Espindolaf1fc3822013-06-26 19:33:03 +00001086#include "Windows/Path.inc"
Michael J. Spencerebad2f92010-11-29 22:28:51 +00001087#endif