blob: 4952f59fc24dd62db383ce328d341f8ec1ee611f [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 <cstring>
Rafael Espindola4526b1d2013-06-18 17:01:00 +000023
24#if !defined(_MSC_VER) && !defined(__MINGW32__)
Douglas Gregora86ddf02013-03-21 21:46:10 +000025#include <unistd.h>
Rafael Espindola4526b1d2013-06-18 17:01:00 +000026#else
27#include <io.h>
Douglas Gregora86ddf02013-03-21 21:46:10 +000028#endif
Michael J. Spencerebad2f92010-11-29 22:28:51 +000029
Rafael Espindola7a0b6402014-02-24 03:07:41 +000030using namespace llvm;
Rui Ueyama3206b792015-03-02 21:19:12 +000031using namespace llvm::support::endian;
Rafael Espindola7a0b6402014-02-24 03:07:41 +000032
Michael J. Spencerebad2f92010-11-29 22:28:51 +000033namespace {
34 using llvm::StringRef;
Zhanyong Wan606bb1a2011-02-11 21:24:40 +000035 using llvm::sys::path::is_separator;
Michael J. Spencerebad2f92010-11-29 22:28:51 +000036
37#ifdef LLVM_ON_WIN32
Benjamin Kramer5e4f0a42012-02-08 13:13:47 +000038 const char *separators = "\\/";
Alp Tokercb402912014-01-24 17:20:08 +000039 const char preferred_separator = '\\';
Michael J. Spencerebad2f92010-11-29 22:28:51 +000040#else
Benjamin Kramer5e4f0a42012-02-08 13:13:47 +000041 const char separators = '/';
Alp Tokercb402912014-01-24 17:20:08 +000042 const char preferred_separator = '/';
Michael J. Spencerebad2f92010-11-29 22:28:51 +000043#endif
44
Benjamin Kramercb520cd2010-12-17 18:59:09 +000045 StringRef find_first_component(StringRef path) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +000046 // Look for this first component in the following order.
47 // * empty (in this case we return an empty string)
48 // * either C: or {//,\\}net.
49 // * {/,\}
Michael J. Spencerebad2f92010-11-29 22:28:51 +000050 // * {file,directory}name
51
52 if (path.empty())
53 return path;
54
Michael J. Spencerbfea3c72010-12-07 03:57:48 +000055#ifdef LLVM_ON_WIN32
Michael J. Spencerebad2f92010-11-29 22:28:51 +000056 // C:
Guy Benyei83c74e92013-02-12 21:21:59 +000057 if (path.size() >= 2 && std::isalpha(static_cast<unsigned char>(path[0])) &&
58 path[1] == ':')
Benjamin Kramerffa42ce2010-12-17 20:27:37 +000059 return path.substr(0, 2);
Michael J. Spencerbfea3c72010-12-07 03:57:48 +000060#endif
Michael J. Spencerebad2f92010-11-29 22:28:51 +000061
62 // //net
63 if ((path.size() > 2) &&
Michael J. Spencerbfea3c72010-12-07 03:57:48 +000064 is_separator(path[0]) &&
65 path[0] == path[1] &&
66 !is_separator(path[2])) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +000067 // Find the next directory separator.
Michael J. Spencerbfea3c72010-12-07 03:57:48 +000068 size_t end = path.find_first_of(separators, 2);
Benjamin Kramerffa42ce2010-12-17 20:27:37 +000069 return path.substr(0, end);
Michael J. Spencerebad2f92010-11-29 22:28:51 +000070 }
71
72 // {/,\}
Michael J. Spencerbfea3c72010-12-07 03:57:48 +000073 if (is_separator(path[0]))
Benjamin Kramerffa42ce2010-12-17 20:27:37 +000074 return path.substr(0, 1);
Michael J. Spencerebad2f92010-11-29 22:28:51 +000075
Michael J. Spencerebad2f92010-11-29 22:28:51 +000076 // * {file,directory}name
Tareq A. Siraj73537ea2013-08-12 17:10:49 +000077 size_t end = path.find_first_of(separators);
Benjamin Kramerffa42ce2010-12-17 20:27:37 +000078 return path.substr(0, end);
Michael J. Spencerebad2f92010-11-29 22:28:51 +000079 }
Michael J. Spencer545cbdf2010-11-30 23:28:07 +000080
Benjamin Kramer292b44b2010-12-17 18:19:06 +000081 size_t filename_pos(StringRef str) {
Michael J. Spencer545cbdf2010-11-30 23:28:07 +000082 if (str.size() == 2 &&
83 is_separator(str[0]) &&
Michael J. Spencerbfea3c72010-12-07 03:57:48 +000084 str[0] == str[1])
Michael J. Spencer545cbdf2010-11-30 23:28:07 +000085 return 0;
86
87 if (str.size() > 0 && is_separator(str[str.size() - 1]))
88 return str.size() - 1;
89
90 size_t pos = str.find_last_of(separators, str.size() - 1);
91
92#ifdef LLVM_ON_WIN32
Zachary Turner36f807c2015-02-12 00:05:49 +000093 if (pos == StringRef::npos)
94 pos = str.find_last_of(':', str.size() - 2);
Michael J. Spencer545cbdf2010-11-30 23:28:07 +000095#endif
96
97 if (pos == StringRef::npos ||
98 (pos == 1 && is_separator(str[0])))
99 return 0;
100
101 return pos + 1;
102 }
103
Benjamin Kramer292b44b2010-12-17 18:19:06 +0000104 size_t root_dir_start(StringRef str) {
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000105 // case "c:/"
106#ifdef LLVM_ON_WIN32
107 if (str.size() > 2 &&
108 str[1] == ':' &&
109 is_separator(str[2]))
110 return 2;
111#endif
112
113 // case "//"
114 if (str.size() == 2 &&
115 is_separator(str[0]) &&
116 str[0] == str[1])
117 return StringRef::npos;
118
119 // case "//net"
120 if (str.size() > 3 &&
121 is_separator(str[0]) &&
122 str[0] == str[1] &&
123 !is_separator(str[2])) {
124 return str.find_first_of(separators, 2);
125 }
126
127 // case "/"
128 if (str.size() > 0 && is_separator(str[0]))
129 return 0;
130
131 return StringRef::npos;
132 }
133
Benjamin Kramer292b44b2010-12-17 18:19:06 +0000134 size_t parent_path_end(StringRef path) {
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000135 size_t end_pos = filename_pos(path);
136
137 bool filename_was_sep = path.size() > 0 && is_separator(path[end_pos]);
138
139 // Skip separators except for root dir.
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000140 size_t root_dir_pos = root_dir_start(path.substr(0, end_pos));
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000141
142 while(end_pos > 0 &&
143 (end_pos - 1) != root_dir_pos &&
144 is_separator(path[end_pos - 1]))
145 --end_pos;
146
147 if (end_pos == 1 && root_dir_pos == 0 && filename_was_sep)
148 return StringRef::npos;
149
150 return end_pos;
151 }
Zhanyong Wan606bb1a2011-02-11 21:24:40 +0000152} // end unnamed namespace
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000153
Rafael Espindolae79a8722013-06-28 03:48:47 +0000154enum FSEntity {
155 FS_Dir,
156 FS_File,
157 FS_Name
158};
159
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000160static std::error_code createUniqueEntity(const Twine &Model, int &ResultFD,
161 SmallVectorImpl<char> &ResultPath,
162 bool MakeAbsolute, unsigned Mode,
163 FSEntity Type) {
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000164 SmallString<128> ModelStorage;
165 Model.toVector(ModelStorage);
166
167 if (MakeAbsolute) {
168 // Make model absolute by prepending a temp directory if it's not already.
169 if (!sys::path::is_absolute(Twine(ModelStorage))) {
170 SmallString<128> TDir;
Rafael Espindola016a6d52014-08-26 14:47:52 +0000171 sys::path::system_temp_directory(true, TDir);
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000172 sys::path::append(TDir, Twine(ModelStorage));
173 ModelStorage.swap(TDir);
174 }
175 }
176
177 // From here on, DO NOT modify model. It may be needed if the randomly chosen
178 // path already exists.
179 ResultPath = ModelStorage;
180 // Null terminate.
181 ResultPath.push_back(0);
182 ResultPath.pop_back();
183
184retry_random_path:
185 // Replace '%' with random chars.
186 for (unsigned i = 0, e = ModelStorage.size(); i != e; ++i) {
187 if (ModelStorage[i] == '%')
188 ResultPath[i] = "0123456789abcdef"[sys::Process::GetRandomNumber() & 15];
189 }
190
191 // Try to open + create the file.
192 switch (Type) {
193 case FS_File: {
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000194 if (std::error_code EC =
Rafael Espindola90c7f1c2014-02-24 18:20:12 +0000195 sys::fs::openFileForWrite(Twine(ResultPath.begin()), ResultFD,
196 sys::fs::F_RW | sys::fs::F_Excl, Mode)) {
Rafael Espindola2a826e42014-06-13 17:20:48 +0000197 if (EC == errc::file_exists)
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000198 goto retry_random_path;
199 return EC;
200 }
201
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000202 return std::error_code();
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000203 }
204
205 case FS_Name: {
Rafael Espindola281f23a2014-09-11 20:30:02 +0000206 std::error_code EC =
207 sys::fs::access(ResultPath.begin(), sys::fs::AccessMode::Exist);
208 if (EC == errc::no_such_file_or_directory)
209 return std::error_code();
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000210 if (EC)
211 return EC;
Rafael Espindola281f23a2014-09-11 20:30:02 +0000212 goto retry_random_path;
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000213 }
214
215 case FS_Dir: {
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000216 if (std::error_code EC =
217 sys::fs::create_directory(ResultPath.begin(), false)) {
Rafael Espindola2a826e42014-06-13 17:20:48 +0000218 if (EC == errc::file_exists)
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000219 goto retry_random_path;
220 return EC;
221 }
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000222 return std::error_code();
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000223 }
224 }
225 llvm_unreachable("Invalid Type");
226}
Rafael Espindolae79a8722013-06-28 03:48:47 +0000227
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000228namespace llvm {
229namespace sys {
230namespace path {
231
Benjamin Kramer292b44b2010-12-17 18:19:06 +0000232const_iterator begin(StringRef path) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000233 const_iterator i;
234 i.Path = path;
235 i.Component = find_first_component(path);
236 i.Position = 0;
237 return i;
238}
239
Benjamin Kramer292b44b2010-12-17 18:19:06 +0000240const_iterator end(StringRef path) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000241 const_iterator i;
242 i.Path = path;
243 i.Position = path.size();
244 return i;
245}
246
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000247const_iterator &const_iterator::operator++() {
248 assert(Position < Path.size() && "Tried to increment past end!");
249
250 // Increment Position to past the current component
251 Position += Component.size();
252
253 // Check for end.
254 if (Position == Path.size()) {
255 Component = StringRef();
256 return *this;
257 }
258
259 // Both POSIX and Windows treat paths that begin with exactly two separators
260 // specially.
261 bool was_net = Component.size() > 2 &&
262 is_separator(Component[0]) &&
263 Component[1] == Component[0] &&
264 !is_separator(Component[2]);
265
266 // Handle separators.
267 if (is_separator(Path[Position])) {
268 // Root dir.
269 if (was_net
270#ifdef LLVM_ON_WIN32
271 // c:/
272 || Component.endswith(":")
273#endif
274 ) {
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000275 Component = Path.substr(Position, 1);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000276 return *this;
277 }
278
279 // Skip extra separators.
280 while (Position != Path.size() &&
281 is_separator(Path[Position])) {
282 ++Position;
283 }
284
285 // Treat trailing '/' as a '.'.
286 if (Position == Path.size()) {
287 --Position;
288 Component = ".";
289 return *this;
290 }
291 }
292
293 // Find next component.
294 size_t end_pos = Path.find_first_of(separators, Position);
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000295 Component = Path.slice(Position, end_pos);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000296
297 return *this;
298}
299
Justin Bogner487e7642014-08-04 17:36:41 +0000300bool const_iterator::operator==(const const_iterator &RHS) const {
301 return Path.begin() == RHS.Path.begin() && Position == RHS.Position;
302}
303
304ptrdiff_t const_iterator::operator-(const const_iterator &RHS) const {
305 return Position - RHS.Position;
306}
307
308reverse_iterator rbegin(StringRef Path) {
309 reverse_iterator I;
310 I.Path = Path;
311 I.Position = Path.size();
312 return ++I;
313}
314
315reverse_iterator rend(StringRef Path) {
316 reverse_iterator I;
317 I.Path = Path;
318 I.Component = Path.substr(0, 0);
319 I.Position = 0;
320 return I;
321}
322
323reverse_iterator &reverse_iterator::operator++() {
Ben Langmuir8d116392014-03-05 19:56:30 +0000324 // If we're at the end and the previous char was a '/', return '.' unless
325 // we are the root path.
326 size_t root_dir_pos = root_dir_start(Path);
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000327 if (Position == Path.size() &&
Ben Langmuir8d116392014-03-05 19:56:30 +0000328 Path.size() > root_dir_pos + 1 &&
329 is_separator(Path[Position - 1])) {
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000330 --Position;
331 Component = ".";
332 return *this;
333 }
334
335 // Skip separators unless it's the root directory.
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000336 size_t end_pos = Position;
337
338 while(end_pos > 0 &&
339 (end_pos - 1) != root_dir_pos &&
340 is_separator(Path[end_pos - 1]))
341 --end_pos;
342
343 // Find next separator.
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000344 size_t start_pos = filename_pos(Path.substr(0, end_pos));
345 Component = Path.slice(start_pos, end_pos);
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000346 Position = start_pos;
347 return *this;
348}
349
Justin Bogner487e7642014-08-04 17:36:41 +0000350bool reverse_iterator::operator==(const reverse_iterator &RHS) const {
351 return Path.begin() == RHS.Path.begin() && Component == RHS.Component &&
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000352 Position == RHS.Position;
353}
354
Craig Topper6dc4a8bc2014-08-30 16:48:02 +0000355StringRef root_path(StringRef path) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000356 const_iterator b = begin(path),
357 pos = b,
358 e = end(path);
359 if (b != e) {
360 bool has_net = b->size() > 2 && is_separator((*b)[0]) && (*b)[1] == (*b)[0];
361 bool has_drive =
362#ifdef LLVM_ON_WIN32
363 b->endswith(":");
364#else
365 false;
366#endif
367
368 if (has_net || has_drive) {
369 if ((++pos != e) && is_separator((*pos)[0])) {
370 // {C:/,//net/}, so get the first two components.
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000371 return path.substr(0, b->size() + pos->size());
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000372 } else {
373 // just {C:,//net}, return the first component.
Michael J. Spencerf616b212010-12-07 17:04:04 +0000374 return *b;
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000375 }
376 }
377
378 // POSIX style root directory.
379 if (is_separator((*b)[0])) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000380 return *b;
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000381 }
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000382 }
383
Michael J. Spencerf616b212010-12-07 17:04:04 +0000384 return StringRef();
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000385}
386
Craig Topper6dc4a8bc2014-08-30 16:48:02 +0000387StringRef root_name(StringRef path) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000388 const_iterator b = begin(path),
389 e = end(path);
390 if (b != e) {
391 bool has_net = b->size() > 2 && is_separator((*b)[0]) && (*b)[1] == (*b)[0];
392 bool has_drive =
393#ifdef LLVM_ON_WIN32
394 b->endswith(":");
395#else
396 false;
397#endif
398
399 if (has_net || has_drive) {
400 // just {C:,//net}, return the first component.
Michael J. Spencerf616b212010-12-07 17:04:04 +0000401 return *b;
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000402 }
403 }
404
405 // No path or no name.
Michael J. Spencerf616b212010-12-07 17:04:04 +0000406 return StringRef();
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000407}
408
Craig Topper6dc4a8bc2014-08-30 16:48:02 +0000409StringRef root_directory(StringRef path) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000410 const_iterator b = begin(path),
411 pos = b,
412 e = end(path);
413 if (b != e) {
414 bool has_net = b->size() > 2 && is_separator((*b)[0]) && (*b)[1] == (*b)[0];
415 bool has_drive =
416#ifdef LLVM_ON_WIN32
417 b->endswith(":");
418#else
419 false;
420#endif
421
422 if ((has_net || has_drive) &&
423 // {C:,//net}, skip to the next component.
424 (++pos != e) && is_separator((*pos)[0])) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000425 return *pos;
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000426 }
427
428 // POSIX style root directory.
429 if (!has_net && is_separator((*b)[0])) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000430 return *b;
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000431 }
432 }
433
434 // No path or no root.
Michael J. Spencerf616b212010-12-07 17:04:04 +0000435 return StringRef();
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000436}
437
Craig Topper6dc4a8bc2014-08-30 16:48:02 +0000438StringRef relative_path(StringRef path) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000439 StringRef root = root_path(path);
Michael J. Spencere6462392012-02-29 00:06:24 +0000440 return path.substr(root.size());
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000441}
442
Michael J. Spencer1e090f02010-12-07 03:57:37 +0000443void append(SmallVectorImpl<char> &path, const Twine &a,
444 const Twine &b,
445 const Twine &c,
446 const Twine &d) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000447 SmallString<32> a_storage;
448 SmallString<32> b_storage;
449 SmallString<32> c_storage;
450 SmallString<32> d_storage;
451
452 SmallVector<StringRef, 4> components;
453 if (!a.isTriviallyEmpty()) components.push_back(a.toStringRef(a_storage));
454 if (!b.isTriviallyEmpty()) components.push_back(b.toStringRef(b_storage));
455 if (!c.isTriviallyEmpty()) components.push_back(c.toStringRef(c_storage));
456 if (!d.isTriviallyEmpty()) components.push_back(d.toStringRef(d_storage));
457
Pawel Bylica64d08ff2015-10-22 08:12:15 +0000458 for (auto &component : components) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000459 bool path_has_sep = !path.empty() && is_separator(path[path.size() - 1]);
Pawel Bylica64d08ff2015-10-22 08:12:15 +0000460 bool component_has_sep = !component.empty() && is_separator(component[0]);
461 bool is_root_name = has_root_name(component);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000462
463 if (path_has_sep) {
464 // Strip separators from beginning of component.
Pawel Bylica64d08ff2015-10-22 08:12:15 +0000465 size_t loc = component.find_first_not_of(separators);
466 StringRef c = component.substr(loc);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000467
468 // Append it.
469 path.append(c.begin(), c.end());
470 continue;
471 }
472
Michael J. Spencer95e4ac12010-12-06 04:28:23 +0000473 if (!component_has_sep && !(path.empty() || is_root_name)) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000474 // Add a separator.
Alp Tokercb402912014-01-24 17:20:08 +0000475 path.push_back(preferred_separator);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000476 }
477
Pawel Bylica64d08ff2015-10-22 08:12:15 +0000478 path.append(component.begin(), component.end());
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000479 }
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000480}
481
Argyrios Kyrtzidisa61736f2011-02-15 17:51:19 +0000482void append(SmallVectorImpl<char> &path,
483 const_iterator begin, const_iterator end) {
484 for (; begin != end; ++begin)
485 path::append(path, *begin);
486}
487
Craig Topper6dc4a8bc2014-08-30 16:48:02 +0000488StringRef parent_path(StringRef path) {
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000489 size_t end_pos = parent_path_end(path);
490 if (end_pos == StringRef::npos)
Michael J. Spencerf616b212010-12-07 17:04:04 +0000491 return StringRef();
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000492 else
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000493 return path.substr(0, end_pos);
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000494}
495
Michael J. Spencer1e090f02010-12-07 03:57:37 +0000496void remove_filename(SmallVectorImpl<char> &path) {
Michael J. Spencer9c594092010-12-01 00:52:28 +0000497 size_t end_pos = parent_path_end(StringRef(path.begin(), path.size()));
Michael J. Spencer1e090f02010-12-07 03:57:37 +0000498 if (end_pos != StringRef::npos)
499 path.set_size(end_pos);
Michael J. Spencer9c594092010-12-01 00:52:28 +0000500}
501
Michael J. Spencerf616b212010-12-07 17:04:04 +0000502void replace_extension(SmallVectorImpl<char> &path, const Twine &extension) {
Michael J. Spencerfb3a95d2010-12-01 00:52:55 +0000503 StringRef p(path.begin(), path.size());
504 SmallString<32> ext_storage;
505 StringRef ext = extension.toStringRef(ext_storage);
506
507 // Erase existing extension.
508 size_t pos = p.find_last_of('.');
509 if (pos != StringRef::npos && pos >= filename_pos(p))
510 path.set_size(pos);
511
512 // Append '.' if needed.
513 if (ext.size() > 0 && ext[0] != '.')
514 path.push_back('.');
515
516 // Append extension.
517 path.append(ext.begin(), ext.end());
Michael J. Spencerfb3a95d2010-12-01 00:52:55 +0000518}
519
Michael J. Spencer1e090f02010-12-07 03:57:37 +0000520void native(const Twine &path, SmallVectorImpl<char> &result) {
Benjamin Kramerbd4ac9b2013-09-11 10:45:21 +0000521 assert((!path.isSingleStringRef() ||
522 path.getSingleStringRef().data() != result.data()) &&
523 "path and result are not allowed to overlap!");
Michael J. Spencer80025002010-12-01 02:48:27 +0000524 // Clear result.
Michael J. Spencer98c7a112010-12-07 01:23:19 +0000525 result.clear();
Michael J. Spencer80025002010-12-01 02:48:27 +0000526 path.toVector(result);
Benjamin Kramerbd4ac9b2013-09-11 10:45:21 +0000527 native(result);
528}
529
Rafael Espindolad649b9d2014-08-08 21:29:34 +0000530void native(SmallVectorImpl<char> &Path) {
Benjamin Kramerbd4ac9b2013-09-11 10:45:21 +0000531#ifdef LLVM_ON_WIN32
Rafael Espindola674ef1d2014-08-08 22:09:31 +0000532 std::replace(Path.begin(), Path.end(), '/', '\\');
Rafael Espindolad649b9d2014-08-08 21:29:34 +0000533#else
534 for (auto PI = Path.begin(), PE = Path.end(); PI < PE; ++PI) {
535 if (*PI == '\\') {
536 auto PN = PI + 1;
537 if (PN < PE && *PN == '\\')
538 ++PI; // increment once, the for loop will move over the escaped slash
539 else
540 *PI = '/';
541 }
542 }
Michael J. Spencer80025002010-12-01 02:48:27 +0000543#endif
Michael J. Spencer80025002010-12-01 02:48:27 +0000544}
545
Craig Topper6dc4a8bc2014-08-30 16:48:02 +0000546StringRef filename(StringRef path) {
Justin Bogner487e7642014-08-04 17:36:41 +0000547 return *rbegin(path);
Michael J. Spencer14269202010-12-01 03:18:17 +0000548}
549
Craig Topper6dc4a8bc2014-08-30 16:48:02 +0000550StringRef stem(StringRef path) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000551 StringRef fname = filename(path);
Michael J. Spencer956955e2010-12-01 03:18:33 +0000552 size_t pos = fname.find_last_of('.');
553 if (pos == StringRef::npos)
Michael J. Spencerf616b212010-12-07 17:04:04 +0000554 return fname;
Michael J. Spencer956955e2010-12-01 03:18:33 +0000555 else
556 if ((fname.size() == 1 && fname == ".") ||
557 (fname.size() == 2 && fname == ".."))
Michael J. Spencerf616b212010-12-07 17:04:04 +0000558 return fname;
Michael J. Spencer956955e2010-12-01 03:18:33 +0000559 else
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000560 return fname.substr(0, pos);
Michael J. Spencer956955e2010-12-01 03:18:33 +0000561}
562
Craig Topper6dc4a8bc2014-08-30 16:48:02 +0000563StringRef extension(StringRef path) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000564 StringRef fname = filename(path);
Michael J. Spencer87106c52010-12-01 03:37:41 +0000565 size_t pos = fname.find_last_of('.');
566 if (pos == StringRef::npos)
Michael J. Spencerf616b212010-12-07 17:04:04 +0000567 return StringRef();
Michael J. Spencer87106c52010-12-01 03:37:41 +0000568 else
569 if ((fname.size() == 1 && fname == ".") ||
570 (fname.size() == 2 && fname == ".."))
Michael J. Spencerf616b212010-12-07 17:04:04 +0000571 return StringRef();
Michael J. Spencer87106c52010-12-01 03:37:41 +0000572 else
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000573 return fname.substr(pos);
Michael J. Spencer87106c52010-12-01 03:37:41 +0000574}
575
Zhanyong Wan606bb1a2011-02-11 21:24:40 +0000576bool is_separator(char value) {
577 switch(value) {
578#ifdef LLVM_ON_WIN32
579 case '\\': // fall through
580#endif
581 case '/': return true;
582 default: return false;
583 }
584}
585
Yaron Keren15217202014-05-16 13:16:30 +0000586static const char preferred_separator_string[] = { preferred_separator, '\0' };
587
Craig Topper6dc4a8bc2014-08-30 16:48:02 +0000588StringRef get_separator() {
Yaron Keren15217202014-05-16 13:16:30 +0000589 return preferred_separator_string;
590}
591
Michael J. Spencera68282c2010-12-07 18:12:07 +0000592bool has_root_name(const Twine &path) {
Michael J. Spencer112a7692010-12-01 06:03:50 +0000593 SmallString<128> path_storage;
594 StringRef p = path.toStringRef(path_storage);
595
Michael J. Spencerf616b212010-12-07 17:04:04 +0000596 return !root_name(p).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000597}
598
Michael J. Spencera68282c2010-12-07 18:12:07 +0000599bool has_root_directory(const Twine &path) {
Michael J. Spencer112a7692010-12-01 06:03:50 +0000600 SmallString<128> path_storage;
601 StringRef p = path.toStringRef(path_storage);
602
Michael J. Spencerf616b212010-12-07 17:04:04 +0000603 return !root_directory(p).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000604}
605
Michael J. Spencera68282c2010-12-07 18:12:07 +0000606bool has_root_path(const Twine &path) {
Michael J. Spencer112a7692010-12-01 06:03:50 +0000607 SmallString<128> path_storage;
608 StringRef p = path.toStringRef(path_storage);
609
Michael J. Spencerf616b212010-12-07 17:04:04 +0000610 return !root_path(p).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000611}
612
Michael J. Spencer6d4b7e72010-12-20 13:30:28 +0000613bool has_relative_path(const Twine &path) {
614 SmallString<128> path_storage;
615 StringRef p = path.toStringRef(path_storage);
616
617 return !relative_path(p).empty();
618}
619
Michael J. Spencera68282c2010-12-07 18:12:07 +0000620bool has_filename(const Twine &path) {
Michael J. Spencer112a7692010-12-01 06:03:50 +0000621 SmallString<128> path_storage;
622 StringRef p = path.toStringRef(path_storage);
623
Michael J. Spencerf616b212010-12-07 17:04:04 +0000624 return !filename(p).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000625}
626
Michael J. Spencera68282c2010-12-07 18:12:07 +0000627bool has_parent_path(const Twine &path) {
Michael J. Spencer112a7692010-12-01 06:03:50 +0000628 SmallString<128> path_storage;
629 StringRef p = path.toStringRef(path_storage);
630
Michael J. Spencerf616b212010-12-07 17:04:04 +0000631 return !parent_path(p).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000632}
633
Michael J. Spencera68282c2010-12-07 18:12:07 +0000634bool has_stem(const Twine &path) {
Michael J. Spencer112a7692010-12-01 06:03:50 +0000635 SmallString<128> path_storage;
636 StringRef p = path.toStringRef(path_storage);
637
Michael J. Spencerf616b212010-12-07 17:04:04 +0000638 return !stem(p).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000639}
640
Michael J. Spencera68282c2010-12-07 18:12:07 +0000641bool has_extension(const Twine &path) {
Michael J. Spencer112a7692010-12-01 06:03:50 +0000642 SmallString<128> path_storage;
643 StringRef p = path.toStringRef(path_storage);
644
Michael J. Spencerf616b212010-12-07 17:04:04 +0000645 return !extension(p).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000646}
647
Michael J. Spencera68282c2010-12-07 18:12:07 +0000648bool is_absolute(const Twine &path) {
Michael J. Spencera72df5f2010-12-01 06:21:53 +0000649 SmallString<128> path_storage;
650 StringRef p = path.toStringRef(path_storage);
651
Michael J. Spencerf616b212010-12-07 17:04:04 +0000652 bool rootDir = has_root_directory(p),
Michael J. Spencera72df5f2010-12-01 06:21:53 +0000653#ifdef LLVM_ON_WIN32
Michael J. Spencerf616b212010-12-07 17:04:04 +0000654 rootName = has_root_name(p);
Michael J. Spencera72df5f2010-12-01 06:21:53 +0000655#else
Michael J. Spencerf616b212010-12-07 17:04:04 +0000656 rootName = true;
Michael J. Spencera72df5f2010-12-01 06:21:53 +0000657#endif
658
Michael J. Spencerf616b212010-12-07 17:04:04 +0000659 return rootDir && rootName;
Michael J. Spencera72df5f2010-12-01 06:21:53 +0000660}
661
Douglas Katzmana26be4a2015-09-02 21:02:10 +0000662bool is_relative(const Twine &path) { return !is_absolute(path); }
663
664StringRef remove_leading_dotslash(StringRef Path) {
665 // Remove leading "./" (or ".//" or "././" etc.)
666 while (Path.size() > 2 && Path[0] == '.' && is_separator(Path[1])) {
667 Path = Path.substr(2);
668 while (Path.size() > 0 && is_separator(Path[0]))
669 Path = Path.substr(1);
670 }
671 return Path;
Michael J. Spencera72df5f2010-12-01 06:21:53 +0000672}
673
Mike Aizatsky662b4fd2015-11-09 18:56:31 +0000674static SmallString<256> remove_dots(StringRef path, bool remove_dot_dot) {
675 SmallVector<StringRef, 16> components;
676
677 // Skip the root path, then look for traversal in the components.
678 StringRef rel = path::relative_path(path);
679 for (StringRef C : llvm::make_range(path::begin(rel), path::end(rel))) {
680 if (C == ".")
681 continue;
682 if (remove_dot_dot) {
683 if (C == "..") {
684 if (!components.empty())
685 components.pop_back();
686 continue;
687 }
688 }
689 components.push_back(C);
690 }
691
692 SmallString<256> buffer = path::root_path(path);
693 for (StringRef C : components)
694 path::append(buffer, C);
695 return buffer;
696}
697
698bool remove_dots(SmallVectorImpl<char> &path, bool remove_dot_dot) {
699 StringRef p(path.data(), path.size());
700
701 SmallString<256> result = remove_dots(p, remove_dot_dot);
702 if (result == path)
703 return false;
704
705 path.swap(result);
706 return true;
707}
708
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +0000709} // end namespace path
710
711namespace fs {
712
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000713std::error_code getUniqueID(const Twine Path, UniqueID &Result) {
Rafael Espindola7f822a92013-07-29 21:26:49 +0000714 file_status Status;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000715 std::error_code EC = status(Path, Status);
Rafael Espindola7f822a92013-07-29 21:26:49 +0000716 if (EC)
717 return EC;
718 Result = Status.getUniqueID();
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000719 return std::error_code();
Rafael Espindola7f822a92013-07-29 21:26:49 +0000720}
721
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000722std::error_code createUniqueFile(const Twine &Model, int &ResultFd,
723 SmallVectorImpl<char> &ResultPath,
724 unsigned Mode) {
Rafael Espindolac9d2e5b2013-07-05 21:01:08 +0000725 return createUniqueEntity(Model, ResultFd, ResultPath, false, Mode, FS_File);
726}
727
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000728std::error_code createUniqueFile(const Twine &Model,
729 SmallVectorImpl<char> &ResultPath) {
Rafael Espindolac9d2e5b2013-07-05 21:01:08 +0000730 int Dummy;
731 return createUniqueEntity(Model, Dummy, ResultPath, false, 0, FS_Name);
732}
733
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000734static std::error_code
735createTemporaryFile(const Twine &Model, int &ResultFD,
736 llvm::SmallVectorImpl<char> &ResultPath, FSEntity Type) {
Rafael Espindola325fa0f2013-07-05 19:56:49 +0000737 SmallString<128> Storage;
738 StringRef P = Model.toNullTerminatedStringRef(Storage);
739 assert(P.find_first_of(separators) == StringRef::npos &&
740 "Model must be a simple filename.");
741 // Use P.begin() so that createUniqueEntity doesn't need to recreate Storage.
742 return createUniqueEntity(P.begin(), ResultFD, ResultPath,
743 true, owner_read | owner_write, Type);
744}
745
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000746static std::error_code
Rafael Espindola325fa0f2013-07-05 19:56:49 +0000747createTemporaryFile(const Twine &Prefix, StringRef Suffix, int &ResultFD,
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000748 llvm::SmallVectorImpl<char> &ResultPath, FSEntity Type) {
Rafael Espindolad3c89042013-07-25 15:00:17 +0000749 const char *Middle = Suffix.empty() ? "-%%%%%%" : "-%%%%%%.";
750 return createTemporaryFile(Prefix + Middle + Suffix, ResultFD, ResultPath,
Rafael Espindola325fa0f2013-07-05 19:56:49 +0000751 Type);
752}
753
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000754std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
755 int &ResultFD,
756 SmallVectorImpl<char> &ResultPath) {
Rafael Espindola325fa0f2013-07-05 19:56:49 +0000757 return createTemporaryFile(Prefix, Suffix, ResultFD, ResultPath, FS_File);
758}
759
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000760std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
761 SmallVectorImpl<char> &ResultPath) {
Rafael Espindola325fa0f2013-07-05 19:56:49 +0000762 int Dummy;
763 return createTemporaryFile(Prefix, Suffix, Dummy, ResultPath, FS_Name);
764}
765
766
Rafael Espindolae79a8722013-06-28 03:48:47 +0000767// This is a mkdtemp with a different pattern. We use createUniqueEntity mostly
Rafael Espindola31a24432013-06-28 10:55:41 +0000768// for consistency. We should try using mkdtemp.
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000769std::error_code createUniqueDirectory(const Twine &Prefix,
770 SmallVectorImpl<char> &ResultPath) {
Rafael Espindolae79a8722013-06-28 03:48:47 +0000771 int Dummy;
772 return createUniqueEntity(Prefix + "-%%%%%%", Dummy, ResultPath,
773 true, 0, FS_Dir);
Rafael Espindola7ffacc42013-06-27 03:45:31 +0000774}
775
Benjamin Kramerae1d5992015-10-05 13:02:43 +0000776static std::error_code make_absolute(const Twine &current_directory,
777 SmallVectorImpl<char> &path,
778 bool use_current_directory) {
Michael J. Spencer92903a32010-12-07 03:57:17 +0000779 StringRef p(path.data(), path.size());
780
Daniel Dunbarb23158c2012-02-29 00:20:37 +0000781 bool rootDirectory = path::has_root_directory(p),
782#ifdef LLVM_ON_WIN32
Daniel Dunbar39ea4582012-02-29 00:46:46 +0000783 rootName = path::has_root_name(p);
Daniel Dunbarb23158c2012-02-29 00:20:37 +0000784#else
785 rootName = true;
786#endif
Michael J. Spencer92903a32010-12-07 03:57:17 +0000787
788 // Already absolute.
789 if (rootName && rootDirectory)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000790 return std::error_code();
Michael J. Spencer92903a32010-12-07 03:57:17 +0000791
792 // All of the following conditions will need the current directory.
793 SmallString<128> current_dir;
Benjamin Kramerae1d5992015-10-05 13:02:43 +0000794 if (use_current_directory)
795 current_directory.toVector(current_dir);
796 else if (std::error_code ec = current_path(current_dir))
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000797 return ec;
Michael J. Spencer92903a32010-12-07 03:57:17 +0000798
799 // Relative path. Prepend the current directory.
800 if (!rootName && !rootDirectory) {
801 // Append path to the current directory.
Michael J. Spencer1e090f02010-12-07 03:57:37 +0000802 path::append(current_dir, p);
Michael J. Spencer92903a32010-12-07 03:57:17 +0000803 // Set path to the result.
804 path.swap(current_dir);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000805 return std::error_code();
Michael J. Spencer92903a32010-12-07 03:57:17 +0000806 }
807
808 if (!rootName && rootDirectory) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000809 StringRef cdrn = path::root_name(current_dir);
Michael J. Spencer92903a32010-12-07 03:57:17 +0000810 SmallString<128> curDirRootName(cdrn.begin(), cdrn.end());
Michael J. Spencer1e090f02010-12-07 03:57:37 +0000811 path::append(curDirRootName, p);
Michael J. Spencer92903a32010-12-07 03:57:17 +0000812 // Set path to the result.
813 path.swap(curDirRootName);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000814 return std::error_code();
Michael J. Spencer92903a32010-12-07 03:57:17 +0000815 }
816
817 if (rootName && !rootDirectory) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000818 StringRef pRootName = path::root_name(p);
819 StringRef bRootDirectory = path::root_directory(current_dir);
820 StringRef bRelativePath = path::relative_path(current_dir);
821 StringRef pRelativePath = path::relative_path(p);
Michael J. Spencer92903a32010-12-07 03:57:17 +0000822
823 SmallString<128> res;
Michael J. Spencer1e090f02010-12-07 03:57:37 +0000824 path::append(res, pRootName, bRootDirectory, bRelativePath, pRelativePath);
Michael J. Spencer92903a32010-12-07 03:57:17 +0000825 path.swap(res);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000826 return std::error_code();
Michael J. Spencer92903a32010-12-07 03:57:17 +0000827 }
828
829 llvm_unreachable("All rootName and rootDirectory combinations should have "
830 "occurred above!");
831}
832
Benjamin Kramerae1d5992015-10-05 13:02:43 +0000833std::error_code make_absolute(const Twine &current_directory,
834 SmallVectorImpl<char> &path) {
835 return make_absolute(current_directory, path, true);
836}
837
838std::error_code make_absolute(SmallVectorImpl<char> &path) {
839 return make_absolute(Twine(), path, false);
840}
841
Frederic Riss6b9396c2015-08-06 21:04:55 +0000842std::error_code create_directories(const Twine &Path, bool IgnoreExisting,
843 perms Perms) {
Rafael Espindolab6f72b22014-02-13 16:58:19 +0000844 SmallString<128> PathStorage;
845 StringRef P = Path.toStringRef(PathStorage);
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000846
Rafael Espindolab6f72b22014-02-13 16:58:19 +0000847 // Be optimistic and try to create the directory
Frederic Riss6b9396c2015-08-06 21:04:55 +0000848 std::error_code EC = create_directory(P, IgnoreExisting, Perms);
Rafael Espindolab6f72b22014-02-13 16:58:19 +0000849 // If we succeeded, or had any error other than the parent not existing, just
850 // return it.
Rafael Espindola2a826e42014-06-13 17:20:48 +0000851 if (EC != errc::no_such_file_or_directory)
Rafael Espindolab6f72b22014-02-13 16:58:19 +0000852 return EC;
Michael J. Spencerf616b212010-12-07 17:04:04 +0000853
Rafael Espindolab6f72b22014-02-13 16:58:19 +0000854 // We failed because of a no_such_file_or_directory, try to create the
855 // parent.
856 StringRef Parent = path::parent_path(P);
857 if (Parent.empty())
858 return EC;
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000859
Frederic Riss6b9396c2015-08-06 21:04:55 +0000860 if ((EC = create_directories(Parent, IgnoreExisting, Perms)))
Rafael Espindolab6f72b22014-02-13 16:58:19 +0000861 return EC;
862
Frederic Riss6b9396c2015-08-06 21:04:55 +0000863 return create_directory(P, IgnoreExisting, Perms);
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000864}
865
Justin Bognercd45f962014-06-19 19:35:39 +0000866std::error_code copy_file(const Twine &From, const Twine &To) {
867 int ReadFD, WriteFD;
868 if (std::error_code EC = openFileForRead(From, ReadFD))
869 return EC;
870 if (std::error_code EC = openFileForWrite(To, WriteFD, F_None)) {
871 close(ReadFD);
872 return EC;
873 }
874
875 const size_t BufSize = 4096;
Dylan Noblesmith42836d92014-08-26 02:03:30 +0000876 char *Buf = new char[BufSize];
Justin Bognercd45f962014-06-19 19:35:39 +0000877 int BytesRead = 0, BytesWritten = 0;
878 for (;;) {
879 BytesRead = read(ReadFD, Buf, BufSize);
880 if (BytesRead <= 0)
881 break;
882 while (BytesRead) {
883 BytesWritten = write(WriteFD, Buf, BytesRead);
884 if (BytesWritten < 0)
885 break;
886 BytesRead -= BytesWritten;
887 }
888 if (BytesWritten < 0)
889 break;
890 }
891 close(ReadFD);
892 close(WriteFD);
Dylan Noblesmith42836d92014-08-26 02:03:30 +0000893 delete[] Buf;
Justin Bognercd45f962014-06-19 19:35:39 +0000894
895 if (BytesRead < 0 || BytesWritten < 0)
896 return std::error_code(errno, std::generic_category());
897 return std::error_code();
898}
899
Michael J. Spencer730f51a2010-12-09 17:37:02 +0000900bool exists(file_status status) {
901 return status_known(status) && status.type() != file_type::file_not_found;
902}
903
904bool status_known(file_status s) {
905 return s.type() != file_type::status_error;
906}
907
908bool is_directory(file_status status) {
909 return status.type() == file_type::directory_file;
910}
911
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000912std::error_code is_directory(const Twine &path, bool &result) {
Michael J. Spencer0d771ed2011-01-11 01:21:55 +0000913 file_status st;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000914 if (std::error_code ec = status(path, st))
Michael J. Spencer0d771ed2011-01-11 01:21:55 +0000915 return ec;
916 result = is_directory(st);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000917 return std::error_code();
Michael J. Spencer0d771ed2011-01-11 01:21:55 +0000918}
919
Michael J. Spencer730f51a2010-12-09 17:37:02 +0000920bool is_regular_file(file_status status) {
921 return status.type() == file_type::regular_file;
922}
923
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000924std::error_code is_regular_file(const Twine &path, bool &result) {
Michael J. Spencer0d771ed2011-01-11 01:21:55 +0000925 file_status st;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000926 if (std::error_code ec = status(path, st))
Michael J. Spencer0d771ed2011-01-11 01:21:55 +0000927 return ec;
928 result = is_regular_file(st);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000929 return std::error_code();
Michael J. Spencer0d771ed2011-01-11 01:21:55 +0000930}
931
Michael J. Spencer730f51a2010-12-09 17:37:02 +0000932bool is_other(file_status status) {
933 return exists(status) &&
934 !is_regular_file(status) &&
Rafael Espindola20063062014-03-20 17:39:04 +0000935 !is_directory(status);
Michael J. Spencer730f51a2010-12-09 17:37:02 +0000936}
937
Juergen Ributzka84ba3422014-12-18 18:19:47 +0000938std::error_code is_other(const Twine &Path, bool &Result) {
939 file_status FileStatus;
940 if (std::error_code EC = status(Path, FileStatus))
941 return EC;
942 Result = is_other(FileStatus);
943 return std::error_code();
944}
945
Benjamin Kramer91ead3c2011-09-14 01:14:36 +0000946void directory_entry::replace_filename(const Twine &filename, file_status st) {
Rafael Espindolaf662e002015-07-15 21:24:07 +0000947 SmallString<128> path = path::parent_path(Path);
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000948 path::append(path, filename);
949 Path = path.str();
950 Status = st;
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000951}
952
Michael J. Spencer4f8a8322011-12-13 23:17:12 +0000953/// @brief Identify the magic in magic.
Logan Chienc0f691d2014-06-25 13:46:17 +0000954file_magic identify_magic(StringRef Magic) {
Rafael Espindola9b404292013-06-11 17:22:12 +0000955 if (Magic.size() < 4)
Michael J. Spencer96ebd912012-06-19 05:29:57 +0000956 return file_magic::unknown;
Rafael Espindola9b404292013-06-11 17:22:12 +0000957 switch ((unsigned char)Magic[0]) {
Rui Ueyamafc149a62013-10-15 22:45:38 +0000958 case 0x00: {
Rui Ueyama2acb0582014-09-11 21:09:57 +0000959 // COFF bigobj or short import library file
Rui Ueyamae448f9e2013-11-15 21:22:02 +0000960 if (Magic[1] == (char)0x00 && Magic[2] == (char)0xff &&
Rui Ueyama2acb0582014-09-11 21:09:57 +0000961 Magic[3] == (char)0xff) {
Rui Ueyama5c69ff52014-09-11 22:34:32 +0000962 size_t MinSize = offsetof(COFF::BigObjHeader, UUID) + sizeof(COFF::BigObjMagic);
963 if (Magic.size() < MinSize)
964 return file_magic::coff_import_library;
965
Rui Ueyama3206b792015-03-02 21:19:12 +0000966 int BigObjVersion = read16le(
Rui Ueyama5c69ff52014-09-11 22:34:32 +0000967 Magic.data() + offsetof(COFF::BigObjHeader, Version));
968 if (BigObjVersion < COFF::BigObjHeader::MinBigObjectVersion)
969 return file_magic::coff_import_library;
970
971 const char *Start = Magic.data() + offsetof(COFF::BigObjHeader, UUID);
972 if (memcmp(Start, COFF::BigObjMagic, sizeof(COFF::BigObjMagic)) != 0)
973 return file_magic::coff_import_library;
974 return file_magic::coff_object;
Rui Ueyama2acb0582014-09-11 21:09:57 +0000975 }
Rui Ueyamafc149a62013-10-15 22:45:38 +0000976 // Windows resource file
Rui Ueyama50a86e12013-10-16 03:29:49 +0000977 const char Expected[] = { 0, 0, 0, 0, '\x20', 0, 0, 0, '\xff' };
Rui Ueyamafc149a62013-10-15 22:45:38 +0000978 if (Magic.size() >= sizeof(Expected) &&
979 memcmp(Magic.data(), Expected, sizeof(Expected)) == 0)
980 return file_magic::windows_resource;
Rui Ueyama829c4392013-11-14 22:09:08 +0000981 // 0x0000 = COFF unknown machine type
982 if (Magic[1] == 0)
983 return file_magic::coff_object;
Rui Ueyamafc149a62013-10-15 22:45:38 +0000984 break;
985 }
Michael J. Spencer4f8a8322011-12-13 23:17:12 +0000986 case 0xDE: // 0x0B17C0DE = BC wraper
Rafael Espindola9b404292013-06-11 17:22:12 +0000987 if (Magic[1] == (char)0xC0 && Magic[2] == (char)0x17 &&
988 Magic[3] == (char)0x0B)
Michael J. Spencer4f8a8322011-12-13 23:17:12 +0000989 return file_magic::bitcode;
990 break;
991 case 'B':
Rafael Espindola9b404292013-06-11 17:22:12 +0000992 if (Magic[1] == 'C' && Magic[2] == (char)0xC0 && Magic[3] == (char)0xDE)
Michael J. Spencer4f8a8322011-12-13 23:17:12 +0000993 return file_magic::bitcode;
994 break;
995 case '!':
Rafael Espindola9b404292013-06-11 17:22:12 +0000996 if (Magic.size() >= 8)
Rafael Espindola69ef2af2015-07-22 18:29:39 +0000997 if (memcmp(Magic.data(), "!<arch>\n", 8) == 0 ||
998 memcmp(Magic.data(), "!<thin>\n", 8) == 0)
Michael J. Spencer4f8a8322011-12-13 23:17:12 +0000999 return file_magic::archive;
1000 break;
1001
1002 case '\177':
Rafael Espindola823de7c2013-06-11 17:25:45 +00001003 if (Magic.size() >= 18 && Magic[1] == 'E' && Magic[2] == 'L' &&
1004 Magic[3] == 'F') {
Rafael Espindola9b404292013-06-11 17:22:12 +00001005 bool Data2MSB = Magic[5] == 2;
Michael J. Spencerb8055cb2013-04-05 20:10:04 +00001006 unsigned high = Data2MSB ? 16 : 17;
1007 unsigned low = Data2MSB ? 17 : 16;
Rafael Espindola823de7c2013-06-11 17:25:45 +00001008 if (Magic[high] == 0)
Rafael Espindola9b404292013-06-11 17:22:12 +00001009 switch (Magic[low]) {
Michael J. Spencere368a622015-01-23 21:58:09 +00001010 default: return file_magic::elf;
Michael J. Spencer4f8a8322011-12-13 23:17:12 +00001011 case 1: return file_magic::elf_relocatable;
1012 case 2: return file_magic::elf_executable;
1013 case 3: return file_magic::elf_shared_object;
1014 case 4: return file_magic::elf_core;
1015 }
Michael J. Spencerbbd875b2014-11-18 01:14:25 +00001016 else
1017 // It's still some type of ELF file.
1018 return file_magic::elf;
Michael J. Spencer4f8a8322011-12-13 23:17:12 +00001019 }
1020 break;
1021
1022 case 0xCA:
Rafael Espindola9b404292013-06-11 17:22:12 +00001023 if (Magic[1] == char(0xFE) && Magic[2] == char(0xBA) &&
1024 Magic[3] == char(0xBE)) {
Michael J. Spencer4f8a8322011-12-13 23:17:12 +00001025 // This is complicated by an overlap with Java class files.
1026 // See the Mach-O section in /usr/share/file/magic for details.
Rafael Espindola9b404292013-06-11 17:22:12 +00001027 if (Magic.size() >= 8 && Magic[7] < 43)
Alexey Samsonove6388e62013-06-18 15:03:28 +00001028 return file_magic::macho_universal_binary;
Michael J. Spencer4f8a8322011-12-13 23:17:12 +00001029 }
1030 break;
1031
1032 // The two magic numbers for mach-o are:
1033 // 0xfeedface - 32-bit mach-o
1034 // 0xfeedfacf - 64-bit mach-o
1035 case 0xFE:
1036 case 0xCE:
1037 case 0xCF: {
1038 uint16_t type = 0;
Rafael Espindola9b404292013-06-11 17:22:12 +00001039 if (Magic[0] == char(0xFE) && Magic[1] == char(0xED) &&
1040 Magic[2] == char(0xFA) &&
1041 (Magic[3] == char(0xCE) || Magic[3] == char(0xCF))) {
Michael J. Spencer4f8a8322011-12-13 23:17:12 +00001042 /* Native endian */
Rafael Espindola9b404292013-06-11 17:22:12 +00001043 if (Magic.size() >= 16) type = Magic[14] << 8 | Magic[15];
1044 } else if ((Magic[0] == char(0xCE) || Magic[0] == char(0xCF)) &&
1045 Magic[1] == char(0xFA) && Magic[2] == char(0xED) &&
1046 Magic[3] == char(0xFE)) {
Michael J. Spencer4f8a8322011-12-13 23:17:12 +00001047 /* Reverse endian */
Rafael Espindola9b404292013-06-11 17:22:12 +00001048 if (Magic.size() >= 14) type = Magic[13] << 8 | Magic[12];
Michael J. Spencer4f8a8322011-12-13 23:17:12 +00001049 }
1050 switch (type) {
1051 default: break;
1052 case 1: return file_magic::macho_object;
1053 case 2: return file_magic::macho_executable;
1054 case 3: return file_magic::macho_fixed_virtual_memory_shared_lib;
1055 case 4: return file_magic::macho_core;
Rafael Espindola134cc992013-06-10 20:32:27 +00001056 case 5: return file_magic::macho_preload_executable;
Michael J. Spencer4f8a8322011-12-13 23:17:12 +00001057 case 6: return file_magic::macho_dynamically_linked_shared_lib;
1058 case 7: return file_magic::macho_dynamic_linker;
1059 case 8: return file_magic::macho_bundle;
Nick Kledzik2d2b2542014-09-17 00:53:44 +00001060 case 9: return file_magic::macho_dynamically_linked_shared_lib_stub;
Michael J. Spencer4f8a8322011-12-13 23:17:12 +00001061 case 10: return file_magic::macho_dsym_companion;
Justin Bognera7ad4b32015-02-25 22:59:20 +00001062 case 11: return file_magic::macho_kext_bundle;
Michael J. Spencer4f8a8322011-12-13 23:17:12 +00001063 }
1064 break;
1065 }
1066 case 0xF0: // PowerPC Windows
1067 case 0x83: // Alpha 32-bit
1068 case 0x84: // Alpha 64-bit
1069 case 0x66: // MPS R4000 Windows
1070 case 0x50: // mc68K
1071 case 0x4c: // 80386 Windows
Saleem Abdulrasool9b7c0af2014-03-13 07:02:35 +00001072 case 0xc4: // ARMNT Windows
Rafael Espindola9b404292013-06-11 17:22:12 +00001073 if (Magic[1] == 0x01)
Michael J. Spencer4f8a8322011-12-13 23:17:12 +00001074 return file_magic::coff_object;
1075
1076 case 0x90: // PA-RISC Windows
1077 case 0x68: // mc68K Windows
Rafael Espindola9b404292013-06-11 17:22:12 +00001078 if (Magic[1] == 0x02)
Michael J. Spencer4f8a8322011-12-13 23:17:12 +00001079 return file_magic::coff_object;
1080 break;
1081
David Majnemer50267222014-11-05 06:24:35 +00001082 case 'M': // Possible MS-DOS stub on Windows PE file
1083 if (Magic[1] == 'Z') {
Rui Ueyama3206b792015-03-02 21:19:12 +00001084 uint32_t off = read32le(Magic.data() + 0x3c);
Michael J. Spencer4f8a8322011-12-13 23:17:12 +00001085 // PE/COFF file, either EXE or DLL.
David Majnemer50267222014-11-05 06:24:35 +00001086 if (off < Magic.size() &&
1087 memcmp(Magic.data()+off, COFF::PEMagic, sizeof(COFF::PEMagic)) == 0)
Michael J. Spencer4f8a8322011-12-13 23:17:12 +00001088 return file_magic::pecoff_executable;
1089 }
1090 break;
1091
1092 case 0x64: // x86-64 Windows.
Rafael Espindola9b404292013-06-11 17:22:12 +00001093 if (Magic[1] == char(0x86))
Michael J. Spencer4f8a8322011-12-13 23:17:12 +00001094 return file_magic::coff_object;
1095 break;
1096
1097 default:
1098 break;
1099 }
1100 return file_magic::unknown;
1101}
1102
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001103std::error_code identify_magic(const Twine &Path, file_magic &Result) {
Rafael Espindolada70bfd2014-06-11 22:53:00 +00001104 int FD;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001105 if (std::error_code EC = openFileForRead(Path, FD))
Rafael Espindolada70bfd2014-06-11 22:53:00 +00001106 return EC;
Michael J. Spencer94b2ab32011-01-15 20:39:36 +00001107
Rafael Espindolada70bfd2014-06-11 22:53:00 +00001108 char Buffer[32];
1109 int Length = read(FD, Buffer, sizeof(Buffer));
Rafael Espindolaa8acef62014-06-25 14:35:59 +00001110 if (close(FD) != 0 || Length < 0)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001111 return std::error_code(errno, std::generic_category());
Rafael Espindolada70bfd2014-06-11 22:53:00 +00001112
1113 Result = identify_magic(StringRef(Buffer, Length));
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001114 return std::error_code();
Michael J. Spencer94b2ab32011-01-15 20:39:36 +00001115}
1116
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001117std::error_code directory_entry::status(file_status &result) const {
Michael J. Spencerf8dc1862011-01-05 16:39:13 +00001118 return fs::status(Path, result);
1119}
1120
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +00001121} // end namespace fs
1122} // end namespace sys
1123} // end namespace llvm
Michael J. Spencerebad2f92010-11-29 22:28:51 +00001124
1125// Include the truly platform-specific parts.
1126#if defined(LLVM_ON_UNIX)
Rafael Espindolaf1fc3822013-06-26 19:33:03 +00001127#include "Unix/Path.inc"
Michael J. Spencerebad2f92010-11-29 22:28:51 +00001128#endif
1129#if defined(LLVM_ON_WIN32)
Rafael Espindolaf1fc3822013-06-26 19:33:03 +00001130#include "Windows/Path.inc"
Michael J. Spencerebad2f92010-11-29 22:28:51 +00001131#endif
Pawel Bylica0e97e5c2015-11-02 09:49:17 +00001132
1133namespace llvm {
1134namespace sys {
1135namespace path {
1136
1137bool user_cache_directory(SmallVectorImpl<char> &Result, const Twine &Path1,
1138 const Twine &Path2, const Twine &Path3) {
1139 if (getUserCacheDir(Result)) {
1140 append(Result, Path1, Path2, Path3);
1141 return true;
1142 }
1143 return false;
1144}
1145
1146} // end namespace path
1147} // end namsspace sys
1148} // end namespace llvm