blob: c3a6aa48a971eb4bc1808bc3254f8dafe1cb3f01 [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"
Kevin Enderby87c85b72016-01-26 23:43:37 +000015#include "llvm/Support/MachO.h"
Rui Ueyama5c69ff52014-09-11 22:34:32 +000016#include "llvm/Support/Endian.h"
Rafael Espindola2a826e42014-06-13 17:20:48 +000017#include "llvm/Support/Errc.h"
Michael J. Spencerebad2f92010-11-29 22:28:51 +000018#include "llvm/Support/ErrorHandling.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/Support/FileSystem.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000020#include "llvm/Support/Path.h"
Aaron Ballman07e76182014-02-11 03:40:14 +000021#include "llvm/Support/Process.h"
Michael J. Spencerebad2f92010-11-29 22:28:51 +000022#include <cctype>
Michael J. Spencer848f46b2010-12-28 01:49:01 +000023#include <cstring>
Rafael Espindola4526b1d2013-06-18 17:01:00 +000024
25#if !defined(_MSC_VER) && !defined(__MINGW32__)
Douglas Gregora86ddf02013-03-21 21:46:10 +000026#include <unistd.h>
Rafael Espindola4526b1d2013-06-18 17:01:00 +000027#else
28#include <io.h>
Douglas Gregora86ddf02013-03-21 21:46:10 +000029#endif
Michael J. Spencerebad2f92010-11-29 22:28:51 +000030
Rafael Espindola7a0b6402014-02-24 03:07:41 +000031using namespace llvm;
Rui Ueyama3206b792015-03-02 21:19:12 +000032using namespace llvm::support::endian;
Rafael Espindola7a0b6402014-02-24 03:07:41 +000033
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 // * {/,\}
Michael J. Spencerebad2f92010-11-29 22:28:51 +000051 // * {file,directory}name
52
53 if (path.empty())
54 return path;
55
Michael J. Spencerbfea3c72010-12-07 03:57:48 +000056#ifdef LLVM_ON_WIN32
Michael J. Spencerebad2f92010-11-29 22:28:51 +000057 // C:
Guy Benyei83c74e92013-02-12 21:21:59 +000058 if (path.size() >= 2 && std::isalpha(static_cast<unsigned char>(path[0])) &&
59 path[1] == ':')
Benjamin Kramerffa42ce2010-12-17 20:27:37 +000060 return path.substr(0, 2);
Michael J. Spencerbfea3c72010-12-07 03:57:48 +000061#endif
Michael J. Spencerebad2f92010-11-29 22:28:51 +000062
63 // //net
64 if ((path.size() > 2) &&
Michael J. Spencerbfea3c72010-12-07 03:57:48 +000065 is_separator(path[0]) &&
66 path[0] == path[1] &&
67 !is_separator(path[2])) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +000068 // Find the next directory separator.
Michael J. Spencerbfea3c72010-12-07 03:57:48 +000069 size_t end = path.find_first_of(separators, 2);
Benjamin Kramerffa42ce2010-12-17 20:27:37 +000070 return path.substr(0, end);
Michael J. Spencerebad2f92010-11-29 22:28:51 +000071 }
72
73 // {/,\}
Michael J. Spencerbfea3c72010-12-07 03:57:48 +000074 if (is_separator(path[0]))
Benjamin Kramerffa42ce2010-12-17 20:27:37 +000075 return path.substr(0, 1);
Michael J. Spencerebad2f92010-11-29 22:28:51 +000076
Michael J. Spencerebad2f92010-11-29 22:28:51 +000077 // * {file,directory}name
Tareq A. Siraj73537ea2013-08-12 17:10:49 +000078 size_t end = path.find_first_of(separators);
Benjamin Kramerffa42ce2010-12-17 20:27:37 +000079 return path.substr(0, end);
Michael J. Spencerebad2f92010-11-29 22:28:51 +000080 }
Michael J. Spencer545cbdf2010-11-30 23:28:07 +000081
Benjamin Kramer292b44b2010-12-17 18:19:06 +000082 size_t filename_pos(StringRef str) {
Michael J. Spencer545cbdf2010-11-30 23:28:07 +000083 if (str.size() == 2 &&
84 is_separator(str[0]) &&
Michael J. Spencerbfea3c72010-12-07 03:57:48 +000085 str[0] == str[1])
Michael J. Spencer545cbdf2010-11-30 23:28:07 +000086 return 0;
87
88 if (str.size() > 0 && is_separator(str[str.size() - 1]))
89 return str.size() - 1;
90
91 size_t pos = str.find_last_of(separators, str.size() - 1);
92
93#ifdef LLVM_ON_WIN32
Zachary Turner36f807c2015-02-12 00:05:49 +000094 if (pos == StringRef::npos)
95 pos = str.find_last_of(':', str.size() - 2);
Michael J. Spencer545cbdf2010-11-30 23:28:07 +000096#endif
97
98 if (pos == StringRef::npos ||
99 (pos == 1 && is_separator(str[0])))
100 return 0;
101
102 return pos + 1;
103 }
104
Benjamin Kramer292b44b2010-12-17 18:19:06 +0000105 size_t root_dir_start(StringRef str) {
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000106 // case "c:/"
107#ifdef LLVM_ON_WIN32
108 if (str.size() > 2 &&
109 str[1] == ':' &&
110 is_separator(str[2]))
111 return 2;
112#endif
113
114 // case "//"
115 if (str.size() == 2 &&
116 is_separator(str[0]) &&
117 str[0] == str[1])
118 return StringRef::npos;
119
120 // case "//net"
121 if (str.size() > 3 &&
122 is_separator(str[0]) &&
123 str[0] == str[1] &&
124 !is_separator(str[2])) {
125 return str.find_first_of(separators, 2);
126 }
127
128 // case "/"
129 if (str.size() > 0 && is_separator(str[0]))
130 return 0;
131
132 return StringRef::npos;
133 }
134
Benjamin Kramer292b44b2010-12-17 18:19:06 +0000135 size_t parent_path_end(StringRef path) {
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000136 size_t end_pos = filename_pos(path);
137
138 bool filename_was_sep = path.size() > 0 && is_separator(path[end_pos]);
139
140 // Skip separators except for root dir.
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000141 size_t root_dir_pos = root_dir_start(path.substr(0, end_pos));
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000142
143 while(end_pos > 0 &&
144 (end_pos - 1) != root_dir_pos &&
145 is_separator(path[end_pos - 1]))
146 --end_pos;
147
148 if (end_pos == 1 && root_dir_pos == 0 && filename_was_sep)
149 return StringRef::npos;
150
151 return end_pos;
152 }
Zhanyong Wan606bb1a2011-02-11 21:24:40 +0000153} // end unnamed namespace
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000154
Rafael Espindolae79a8722013-06-28 03:48:47 +0000155enum FSEntity {
156 FS_Dir,
157 FS_File,
158 FS_Name
159};
160
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000161static std::error_code createUniqueEntity(const Twine &Model, int &ResultFD,
162 SmallVectorImpl<char> &ResultPath,
163 bool MakeAbsolute, unsigned Mode,
164 FSEntity Type) {
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000165 SmallString<128> ModelStorage;
166 Model.toVector(ModelStorage);
167
168 if (MakeAbsolute) {
169 // Make model absolute by prepending a temp directory if it's not already.
170 if (!sys::path::is_absolute(Twine(ModelStorage))) {
171 SmallString<128> TDir;
Rafael Espindola016a6d52014-08-26 14:47:52 +0000172 sys::path::system_temp_directory(true, TDir);
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000173 sys::path::append(TDir, Twine(ModelStorage));
174 ModelStorage.swap(TDir);
175 }
176 }
177
178 // From here on, DO NOT modify model. It may be needed if the randomly chosen
179 // path already exists.
180 ResultPath = ModelStorage;
181 // Null terminate.
182 ResultPath.push_back(0);
183 ResultPath.pop_back();
184
185retry_random_path:
186 // Replace '%' with random chars.
187 for (unsigned i = 0, e = ModelStorage.size(); i != e; ++i) {
188 if (ModelStorage[i] == '%')
189 ResultPath[i] = "0123456789abcdef"[sys::Process::GetRandomNumber() & 15];
190 }
191
192 // Try to open + create the file.
193 switch (Type) {
194 case FS_File: {
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000195 if (std::error_code EC =
Rafael Espindola90c7f1c2014-02-24 18:20:12 +0000196 sys::fs::openFileForWrite(Twine(ResultPath.begin()), ResultFD,
197 sys::fs::F_RW | sys::fs::F_Excl, Mode)) {
Rafael Espindola2a826e42014-06-13 17:20:48 +0000198 if (EC == errc::file_exists)
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000199 goto retry_random_path;
200 return EC;
201 }
202
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000203 return std::error_code();
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000204 }
205
206 case FS_Name: {
Rafael Espindola281f23a2014-09-11 20:30:02 +0000207 std::error_code EC =
208 sys::fs::access(ResultPath.begin(), sys::fs::AccessMode::Exist);
209 if (EC == errc::no_such_file_or_directory)
210 return std::error_code();
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000211 if (EC)
212 return EC;
Rafael Espindola281f23a2014-09-11 20:30:02 +0000213 goto retry_random_path;
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000214 }
215
216 case FS_Dir: {
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000217 if (std::error_code EC =
218 sys::fs::create_directory(ResultPath.begin(), false)) {
Rafael Espindola2a826e42014-06-13 17:20:48 +0000219 if (EC == errc::file_exists)
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000220 goto retry_random_path;
221 return EC;
222 }
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000223 return std::error_code();
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000224 }
225 }
226 llvm_unreachable("Invalid Type");
227}
Rafael Espindolae79a8722013-06-28 03:48:47 +0000228
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000229namespace llvm {
230namespace sys {
231namespace path {
232
Benjamin Kramer292b44b2010-12-17 18:19:06 +0000233const_iterator begin(StringRef path) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000234 const_iterator i;
235 i.Path = path;
236 i.Component = find_first_component(path);
237 i.Position = 0;
238 return i;
239}
240
Benjamin Kramer292b44b2010-12-17 18:19:06 +0000241const_iterator end(StringRef path) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000242 const_iterator i;
243 i.Path = path;
244 i.Position = path.size();
245 return i;
246}
247
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000248const_iterator &const_iterator::operator++() {
249 assert(Position < Path.size() && "Tried to increment past end!");
250
251 // Increment Position to past the current component
252 Position += Component.size();
253
254 // Check for end.
255 if (Position == Path.size()) {
256 Component = StringRef();
257 return *this;
258 }
259
260 // Both POSIX and Windows treat paths that begin with exactly two separators
261 // specially.
262 bool was_net = Component.size() > 2 &&
263 is_separator(Component[0]) &&
264 Component[1] == Component[0] &&
265 !is_separator(Component[2]);
266
267 // Handle separators.
268 if (is_separator(Path[Position])) {
269 // Root dir.
270 if (was_net
271#ifdef LLVM_ON_WIN32
272 // c:/
273 || Component.endswith(":")
274#endif
275 ) {
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000276 Component = Path.substr(Position, 1);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000277 return *this;
278 }
279
280 // Skip extra separators.
281 while (Position != Path.size() &&
282 is_separator(Path[Position])) {
283 ++Position;
284 }
285
286 // Treat trailing '/' as a '.'.
287 if (Position == Path.size()) {
288 --Position;
289 Component = ".";
290 return *this;
291 }
292 }
293
294 // Find next component.
295 size_t end_pos = Path.find_first_of(separators, Position);
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000296 Component = Path.slice(Position, end_pos);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000297
298 return *this;
299}
300
Justin Bogner487e7642014-08-04 17:36:41 +0000301bool const_iterator::operator==(const const_iterator &RHS) const {
302 return Path.begin() == RHS.Path.begin() && Position == RHS.Position;
303}
304
305ptrdiff_t const_iterator::operator-(const const_iterator &RHS) const {
306 return Position - RHS.Position;
307}
308
309reverse_iterator rbegin(StringRef Path) {
310 reverse_iterator I;
311 I.Path = Path;
312 I.Position = Path.size();
313 return ++I;
314}
315
316reverse_iterator rend(StringRef Path) {
317 reverse_iterator I;
318 I.Path = Path;
319 I.Component = Path.substr(0, 0);
320 I.Position = 0;
321 return I;
322}
323
324reverse_iterator &reverse_iterator::operator++() {
Ben Langmuir8d116392014-03-05 19:56:30 +0000325 // If we're at the end and the previous char was a '/', return '.' unless
326 // we are the root path.
327 size_t root_dir_pos = root_dir_start(Path);
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000328 if (Position == Path.size() &&
Ben Langmuir8d116392014-03-05 19:56:30 +0000329 Path.size() > root_dir_pos + 1 &&
330 is_separator(Path[Position - 1])) {
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000331 --Position;
332 Component = ".";
333 return *this;
334 }
335
336 // Skip separators unless it's the root directory.
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000337 size_t end_pos = Position;
338
339 while(end_pos > 0 &&
340 (end_pos - 1) != root_dir_pos &&
341 is_separator(Path[end_pos - 1]))
342 --end_pos;
343
344 // Find next separator.
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000345 size_t start_pos = filename_pos(Path.substr(0, end_pos));
346 Component = Path.slice(start_pos, end_pos);
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000347 Position = start_pos;
348 return *this;
349}
350
Justin Bogner487e7642014-08-04 17:36:41 +0000351bool reverse_iterator::operator==(const reverse_iterator &RHS) const {
352 return Path.begin() == RHS.Path.begin() && Component == RHS.Component &&
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000353 Position == RHS.Position;
354}
355
Filipe Cabecinhas78949382016-04-29 16:48:07 +0000356ptrdiff_t reverse_iterator::operator-(const reverse_iterator &RHS) const {
357 return Position - RHS.Position;
358}
359
Craig Topper6dc4a8bc2014-08-30 16:48:02 +0000360StringRef root_path(StringRef path) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000361 const_iterator b = begin(path),
362 pos = b,
363 e = end(path);
364 if (b != e) {
365 bool has_net = b->size() > 2 && is_separator((*b)[0]) && (*b)[1] == (*b)[0];
366 bool has_drive =
367#ifdef LLVM_ON_WIN32
368 b->endswith(":");
369#else
370 false;
371#endif
372
373 if (has_net || has_drive) {
374 if ((++pos != e) && is_separator((*pos)[0])) {
375 // {C:/,//net/}, so get the first two components.
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000376 return path.substr(0, b->size() + pos->size());
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000377 } else {
378 // just {C:,//net}, return the first component.
Michael J. Spencerf616b212010-12-07 17:04:04 +0000379 return *b;
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000380 }
381 }
382
383 // POSIX style root directory.
384 if (is_separator((*b)[0])) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000385 return *b;
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000386 }
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000387 }
388
Michael J. Spencerf616b212010-12-07 17:04:04 +0000389 return StringRef();
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000390}
391
Craig Topper6dc4a8bc2014-08-30 16:48:02 +0000392StringRef root_name(StringRef path) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000393 const_iterator b = begin(path),
394 e = end(path);
395 if (b != e) {
396 bool has_net = b->size() > 2 && is_separator((*b)[0]) && (*b)[1] == (*b)[0];
397 bool has_drive =
398#ifdef LLVM_ON_WIN32
399 b->endswith(":");
400#else
401 false;
402#endif
403
404 if (has_net || has_drive) {
405 // just {C:,//net}, return the first component.
Michael J. Spencerf616b212010-12-07 17:04:04 +0000406 return *b;
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000407 }
408 }
409
410 // No path or no name.
Michael J. Spencerf616b212010-12-07 17:04:04 +0000411 return StringRef();
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000412}
413
Craig Topper6dc4a8bc2014-08-30 16:48:02 +0000414StringRef root_directory(StringRef path) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000415 const_iterator b = begin(path),
416 pos = b,
417 e = end(path);
418 if (b != e) {
419 bool has_net = b->size() > 2 && is_separator((*b)[0]) && (*b)[1] == (*b)[0];
420 bool has_drive =
421#ifdef LLVM_ON_WIN32
422 b->endswith(":");
423#else
424 false;
425#endif
426
427 if ((has_net || has_drive) &&
428 // {C:,//net}, skip to the next component.
429 (++pos != e) && is_separator((*pos)[0])) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000430 return *pos;
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000431 }
432
433 // POSIX style root directory.
434 if (!has_net && is_separator((*b)[0])) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000435 return *b;
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000436 }
437 }
438
439 // No path or no root.
Michael J. Spencerf616b212010-12-07 17:04:04 +0000440 return StringRef();
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000441}
442
Craig Topper6dc4a8bc2014-08-30 16:48:02 +0000443StringRef relative_path(StringRef path) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000444 StringRef root = root_path(path);
Michael J. Spencere6462392012-02-29 00:06:24 +0000445 return path.substr(root.size());
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000446}
447
Michael J. Spencer1e090f02010-12-07 03:57:37 +0000448void append(SmallVectorImpl<char> &path, const Twine &a,
449 const Twine &b,
450 const Twine &c,
451 const Twine &d) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000452 SmallString<32> a_storage;
453 SmallString<32> b_storage;
454 SmallString<32> c_storage;
455 SmallString<32> d_storage;
456
457 SmallVector<StringRef, 4> components;
458 if (!a.isTriviallyEmpty()) components.push_back(a.toStringRef(a_storage));
459 if (!b.isTriviallyEmpty()) components.push_back(b.toStringRef(b_storage));
460 if (!c.isTriviallyEmpty()) components.push_back(c.toStringRef(c_storage));
461 if (!d.isTriviallyEmpty()) components.push_back(d.toStringRef(d_storage));
462
Pawel Bylica64d08ff2015-10-22 08:12:15 +0000463 for (auto &component : components) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000464 bool path_has_sep = !path.empty() && is_separator(path[path.size() - 1]);
Pawel Bylica64d08ff2015-10-22 08:12:15 +0000465 bool component_has_sep = !component.empty() && is_separator(component[0]);
466 bool is_root_name = has_root_name(component);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000467
468 if (path_has_sep) {
469 // Strip separators from beginning of component.
Pawel Bylica64d08ff2015-10-22 08:12:15 +0000470 size_t loc = component.find_first_not_of(separators);
471 StringRef c = component.substr(loc);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000472
473 // Append it.
474 path.append(c.begin(), c.end());
475 continue;
476 }
477
Michael J. Spencer95e4ac12010-12-06 04:28:23 +0000478 if (!component_has_sep && !(path.empty() || is_root_name)) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000479 // Add a separator.
Alp Tokercb402912014-01-24 17:20:08 +0000480 path.push_back(preferred_separator);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000481 }
482
Pawel Bylica64d08ff2015-10-22 08:12:15 +0000483 path.append(component.begin(), component.end());
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000484 }
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000485}
486
Argyrios Kyrtzidisa61736f2011-02-15 17:51:19 +0000487void append(SmallVectorImpl<char> &path,
488 const_iterator begin, const_iterator end) {
489 for (; begin != end; ++begin)
490 path::append(path, *begin);
491}
492
Craig Topper6dc4a8bc2014-08-30 16:48:02 +0000493StringRef parent_path(StringRef path) {
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000494 size_t end_pos = parent_path_end(path);
495 if (end_pos == StringRef::npos)
Michael J. Spencerf616b212010-12-07 17:04:04 +0000496 return StringRef();
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000497 else
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000498 return path.substr(0, end_pos);
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000499}
500
Michael J. Spencer1e090f02010-12-07 03:57:37 +0000501void remove_filename(SmallVectorImpl<char> &path) {
Michael J. Spencer9c594092010-12-01 00:52:28 +0000502 size_t end_pos = parent_path_end(StringRef(path.begin(), path.size()));
Michael J. Spencer1e090f02010-12-07 03:57:37 +0000503 if (end_pos != StringRef::npos)
504 path.set_size(end_pos);
Michael J. Spencer9c594092010-12-01 00:52:28 +0000505}
506
Michael J. Spencerf616b212010-12-07 17:04:04 +0000507void replace_extension(SmallVectorImpl<char> &path, const Twine &extension) {
Michael J. Spencerfb3a95d2010-12-01 00:52:55 +0000508 StringRef p(path.begin(), path.size());
509 SmallString<32> ext_storage;
510 StringRef ext = extension.toStringRef(ext_storage);
511
512 // Erase existing extension.
513 size_t pos = p.find_last_of('.');
514 if (pos != StringRef::npos && pos >= filename_pos(p))
515 path.set_size(pos);
516
517 // Append '.' if needed.
518 if (ext.size() > 0 && ext[0] != '.')
519 path.push_back('.');
520
521 // Append extension.
522 path.append(ext.begin(), ext.end());
Michael J. Spencerfb3a95d2010-12-01 00:52:55 +0000523}
524
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000525void replace_path_prefix(SmallVectorImpl<char> &Path,
526 const StringRef &OldPrefix,
527 const StringRef &NewPrefix) {
528 if (OldPrefix.empty() && NewPrefix.empty())
529 return;
530
531 StringRef OrigPath(Path.begin(), Path.size());
532 if (!OrigPath.startswith(OldPrefix))
533 return;
534
535 // If prefixes have the same size we can simply copy the new one over.
536 if (OldPrefix.size() == NewPrefix.size()) {
537 std::copy(NewPrefix.begin(), NewPrefix.end(), Path.begin());
538 return;
539 }
540
541 StringRef RelPath = OrigPath.substr(OldPrefix.size());
542 SmallString<256> NewPath;
543 path::append(NewPath, NewPrefix);
544 path::append(NewPath, RelPath);
545 Path.swap(NewPath);
546}
547
Michael J. Spencer1e090f02010-12-07 03:57:37 +0000548void native(const Twine &path, SmallVectorImpl<char> &result) {
Benjamin Kramerbd4ac9b2013-09-11 10:45:21 +0000549 assert((!path.isSingleStringRef() ||
550 path.getSingleStringRef().data() != result.data()) &&
551 "path and result are not allowed to overlap!");
Michael J. Spencer80025002010-12-01 02:48:27 +0000552 // Clear result.
Michael J. Spencer98c7a112010-12-07 01:23:19 +0000553 result.clear();
Michael J. Spencer80025002010-12-01 02:48:27 +0000554 path.toVector(result);
Benjamin Kramerbd4ac9b2013-09-11 10:45:21 +0000555 native(result);
556}
557
Rafael Espindolad649b9d2014-08-08 21:29:34 +0000558void native(SmallVectorImpl<char> &Path) {
Benjamin Kramerbd4ac9b2013-09-11 10:45:21 +0000559#ifdef LLVM_ON_WIN32
Rafael Espindola674ef1d2014-08-08 22:09:31 +0000560 std::replace(Path.begin(), Path.end(), '/', '\\');
Rafael Espindolad649b9d2014-08-08 21:29:34 +0000561#else
562 for (auto PI = Path.begin(), PE = Path.end(); PI < PE; ++PI) {
563 if (*PI == '\\') {
564 auto PN = PI + 1;
565 if (PN < PE && *PN == '\\')
566 ++PI; // increment once, the for loop will move over the escaped slash
567 else
568 *PI = '/';
569 }
570 }
Michael J. Spencer80025002010-12-01 02:48:27 +0000571#endif
Michael J. Spencer80025002010-12-01 02:48:27 +0000572}
573
Craig Topper6dc4a8bc2014-08-30 16:48:02 +0000574StringRef filename(StringRef path) {
Justin Bogner487e7642014-08-04 17:36:41 +0000575 return *rbegin(path);
Michael J. Spencer14269202010-12-01 03:18:17 +0000576}
577
Craig Topper6dc4a8bc2014-08-30 16:48:02 +0000578StringRef stem(StringRef path) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000579 StringRef fname = filename(path);
Michael J. Spencer956955e2010-12-01 03:18:33 +0000580 size_t pos = fname.find_last_of('.');
581 if (pos == StringRef::npos)
Michael J. Spencerf616b212010-12-07 17:04:04 +0000582 return fname;
Michael J. Spencer956955e2010-12-01 03:18:33 +0000583 else
584 if ((fname.size() == 1 && fname == ".") ||
585 (fname.size() == 2 && fname == ".."))
Michael J. Spencerf616b212010-12-07 17:04:04 +0000586 return fname;
Michael J. Spencer956955e2010-12-01 03:18:33 +0000587 else
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000588 return fname.substr(0, pos);
Michael J. Spencer956955e2010-12-01 03:18:33 +0000589}
590
Craig Topper6dc4a8bc2014-08-30 16:48:02 +0000591StringRef extension(StringRef path) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000592 StringRef fname = filename(path);
Michael J. Spencer87106c52010-12-01 03:37:41 +0000593 size_t pos = fname.find_last_of('.');
594 if (pos == StringRef::npos)
Michael J. Spencerf616b212010-12-07 17:04:04 +0000595 return StringRef();
Michael J. Spencer87106c52010-12-01 03:37:41 +0000596 else
597 if ((fname.size() == 1 && fname == ".") ||
598 (fname.size() == 2 && fname == ".."))
Michael J. Spencerf616b212010-12-07 17:04:04 +0000599 return StringRef();
Michael J. Spencer87106c52010-12-01 03:37:41 +0000600 else
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000601 return fname.substr(pos);
Michael J. Spencer87106c52010-12-01 03:37:41 +0000602}
603
Zhanyong Wan606bb1a2011-02-11 21:24:40 +0000604bool is_separator(char value) {
605 switch(value) {
606#ifdef LLVM_ON_WIN32
607 case '\\': // fall through
608#endif
609 case '/': return true;
610 default: return false;
611 }
612}
613
Yaron Keren15217202014-05-16 13:16:30 +0000614static const char preferred_separator_string[] = { preferred_separator, '\0' };
615
Craig Topper6dc4a8bc2014-08-30 16:48:02 +0000616StringRef get_separator() {
Yaron Keren15217202014-05-16 13:16:30 +0000617 return preferred_separator_string;
618}
619
Michael J. Spencera68282c2010-12-07 18:12:07 +0000620bool has_root_name(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 !root_name(p).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000625}
626
Michael J. Spencera68282c2010-12-07 18:12:07 +0000627bool has_root_directory(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 !root_directory(p).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000632}
633
Michael J. Spencera68282c2010-12-07 18:12:07 +0000634bool has_root_path(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 !root_path(p).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000639}
640
Michael J. Spencer6d4b7e72010-12-20 13:30:28 +0000641bool has_relative_path(const Twine &path) {
642 SmallString<128> path_storage;
643 StringRef p = path.toStringRef(path_storage);
644
645 return !relative_path(p).empty();
646}
647
Michael J. Spencera68282c2010-12-07 18:12:07 +0000648bool has_filename(const Twine &path) {
Michael J. Spencer112a7692010-12-01 06:03:50 +0000649 SmallString<128> path_storage;
650 StringRef p = path.toStringRef(path_storage);
651
Michael J. Spencerf616b212010-12-07 17:04:04 +0000652 return !filename(p).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000653}
654
Michael J. Spencera68282c2010-12-07 18:12:07 +0000655bool has_parent_path(const Twine &path) {
Michael J. Spencer112a7692010-12-01 06:03:50 +0000656 SmallString<128> path_storage;
657 StringRef p = path.toStringRef(path_storage);
658
Michael J. Spencerf616b212010-12-07 17:04:04 +0000659 return !parent_path(p).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000660}
661
Michael J. Spencera68282c2010-12-07 18:12:07 +0000662bool has_stem(const Twine &path) {
Michael J. Spencer112a7692010-12-01 06:03:50 +0000663 SmallString<128> path_storage;
664 StringRef p = path.toStringRef(path_storage);
665
Michael J. Spencerf616b212010-12-07 17:04:04 +0000666 return !stem(p).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000667}
668
Michael J. Spencera68282c2010-12-07 18:12:07 +0000669bool has_extension(const Twine &path) {
Michael J. Spencer112a7692010-12-01 06:03:50 +0000670 SmallString<128> path_storage;
671 StringRef p = path.toStringRef(path_storage);
672
Michael J. Spencerf616b212010-12-07 17:04:04 +0000673 return !extension(p).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000674}
675
Michael J. Spencera68282c2010-12-07 18:12:07 +0000676bool is_absolute(const Twine &path) {
Michael J. Spencera72df5f2010-12-01 06:21:53 +0000677 SmallString<128> path_storage;
678 StringRef p = path.toStringRef(path_storage);
679
Michael J. Spencerf616b212010-12-07 17:04:04 +0000680 bool rootDir = has_root_directory(p),
Michael J. Spencera72df5f2010-12-01 06:21:53 +0000681#ifdef LLVM_ON_WIN32
Michael J. Spencerf616b212010-12-07 17:04:04 +0000682 rootName = has_root_name(p);
Michael J. Spencera72df5f2010-12-01 06:21:53 +0000683#else
Michael J. Spencerf616b212010-12-07 17:04:04 +0000684 rootName = true;
Michael J. Spencera72df5f2010-12-01 06:21:53 +0000685#endif
686
Michael J. Spencerf616b212010-12-07 17:04:04 +0000687 return rootDir && rootName;
Michael J. Spencera72df5f2010-12-01 06:21:53 +0000688}
689
Douglas Katzmana26be4a2015-09-02 21:02:10 +0000690bool is_relative(const Twine &path) { return !is_absolute(path); }
691
692StringRef remove_leading_dotslash(StringRef Path) {
693 // Remove leading "./" (or ".//" or "././" etc.)
694 while (Path.size() > 2 && Path[0] == '.' && is_separator(Path[1])) {
695 Path = Path.substr(2);
696 while (Path.size() > 0 && is_separator(Path[0]))
697 Path = Path.substr(1);
698 }
699 return Path;
Michael J. Spencera72df5f2010-12-01 06:21:53 +0000700}
701
Mike Aizatsky662b4fd2015-11-09 18:56:31 +0000702static SmallString<256> remove_dots(StringRef path, bool remove_dot_dot) {
703 SmallVector<StringRef, 16> components;
704
705 // Skip the root path, then look for traversal in the components.
706 StringRef rel = path::relative_path(path);
707 for (StringRef C : llvm::make_range(path::begin(rel), path::end(rel))) {
708 if (C == ".")
709 continue;
Benjamin Kramer937dd7a2016-10-17 13:28:21 +0000710 // Leading ".." will remain in the path unless it's at the root.
711 if (remove_dot_dot && C == "..") {
712 if (!components.empty() && components.back() != "..") {
713 components.pop_back();
714 continue;
715 }
716 if (path::is_absolute(path))
717 continue;
Mike Aizatsky662b4fd2015-11-09 18:56:31 +0000718 }
719 components.push_back(C);
720 }
721
722 SmallString<256> buffer = path::root_path(path);
723 for (StringRef C : components)
724 path::append(buffer, C);
725 return buffer;
726}
727
728bool remove_dots(SmallVectorImpl<char> &path, bool remove_dot_dot) {
729 StringRef p(path.data(), path.size());
730
731 SmallString<256> result = remove_dots(p, remove_dot_dot);
732 if (result == path)
733 return false;
734
735 path.swap(result);
736 return true;
737}
738
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +0000739} // end namespace path
740
741namespace fs {
742
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000743std::error_code getUniqueID(const Twine Path, UniqueID &Result) {
Rafael Espindola7f822a92013-07-29 21:26:49 +0000744 file_status Status;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000745 std::error_code EC = status(Path, Status);
Rafael Espindola7f822a92013-07-29 21:26:49 +0000746 if (EC)
747 return EC;
748 Result = Status.getUniqueID();
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000749 return std::error_code();
Rafael Espindola7f822a92013-07-29 21:26:49 +0000750}
751
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000752std::error_code createUniqueFile(const Twine &Model, int &ResultFd,
753 SmallVectorImpl<char> &ResultPath,
754 unsigned Mode) {
Rafael Espindolac9d2e5b2013-07-05 21:01:08 +0000755 return createUniqueEntity(Model, ResultFd, ResultPath, false, Mode, FS_File);
756}
757
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000758std::error_code createUniqueFile(const Twine &Model,
759 SmallVectorImpl<char> &ResultPath) {
Rafael Espindolac9d2e5b2013-07-05 21:01:08 +0000760 int Dummy;
761 return createUniqueEntity(Model, Dummy, ResultPath, false, 0, FS_Name);
762}
763
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000764static std::error_code
765createTemporaryFile(const Twine &Model, int &ResultFD,
766 llvm::SmallVectorImpl<char> &ResultPath, FSEntity Type) {
Rafael Espindola325fa0f2013-07-05 19:56:49 +0000767 SmallString<128> Storage;
768 StringRef P = Model.toNullTerminatedStringRef(Storage);
769 assert(P.find_first_of(separators) == StringRef::npos &&
770 "Model must be a simple filename.");
771 // Use P.begin() so that createUniqueEntity doesn't need to recreate Storage.
772 return createUniqueEntity(P.begin(), ResultFD, ResultPath,
773 true, owner_read | owner_write, Type);
774}
775
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000776static std::error_code
Rafael Espindola325fa0f2013-07-05 19:56:49 +0000777createTemporaryFile(const Twine &Prefix, StringRef Suffix, int &ResultFD,
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000778 llvm::SmallVectorImpl<char> &ResultPath, FSEntity Type) {
Rafael Espindolad3c89042013-07-25 15:00:17 +0000779 const char *Middle = Suffix.empty() ? "-%%%%%%" : "-%%%%%%.";
780 return createTemporaryFile(Prefix + Middle + Suffix, ResultFD, ResultPath,
Rafael Espindola325fa0f2013-07-05 19:56:49 +0000781 Type);
782}
783
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000784std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
785 int &ResultFD,
786 SmallVectorImpl<char> &ResultPath) {
Rafael Espindola325fa0f2013-07-05 19:56:49 +0000787 return createTemporaryFile(Prefix, Suffix, ResultFD, ResultPath, FS_File);
788}
789
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000790std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
791 SmallVectorImpl<char> &ResultPath) {
Rafael Espindola325fa0f2013-07-05 19:56:49 +0000792 int Dummy;
793 return createTemporaryFile(Prefix, Suffix, Dummy, ResultPath, FS_Name);
794}
795
796
Rafael Espindolae79a8722013-06-28 03:48:47 +0000797// This is a mkdtemp with a different pattern. We use createUniqueEntity mostly
Rafael Espindola31a24432013-06-28 10:55:41 +0000798// for consistency. We should try using mkdtemp.
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000799std::error_code createUniqueDirectory(const Twine &Prefix,
800 SmallVectorImpl<char> &ResultPath) {
Rafael Espindolae79a8722013-06-28 03:48:47 +0000801 int Dummy;
802 return createUniqueEntity(Prefix + "-%%%%%%", Dummy, ResultPath,
803 true, 0, FS_Dir);
Rafael Espindola7ffacc42013-06-27 03:45:31 +0000804}
805
Benjamin Kramerae1d5992015-10-05 13:02:43 +0000806static std::error_code make_absolute(const Twine &current_directory,
807 SmallVectorImpl<char> &path,
808 bool use_current_directory) {
Michael J. Spencer92903a32010-12-07 03:57:17 +0000809 StringRef p(path.data(), path.size());
810
Daniel Dunbarb23158c2012-02-29 00:20:37 +0000811 bool rootDirectory = path::has_root_directory(p),
812#ifdef LLVM_ON_WIN32
Daniel Dunbar39ea4582012-02-29 00:46:46 +0000813 rootName = path::has_root_name(p);
Daniel Dunbarb23158c2012-02-29 00:20:37 +0000814#else
815 rootName = true;
816#endif
Michael J. Spencer92903a32010-12-07 03:57:17 +0000817
818 // Already absolute.
819 if (rootName && rootDirectory)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000820 return std::error_code();
Michael J. Spencer92903a32010-12-07 03:57:17 +0000821
822 // All of the following conditions will need the current directory.
823 SmallString<128> current_dir;
Benjamin Kramerae1d5992015-10-05 13:02:43 +0000824 if (use_current_directory)
825 current_directory.toVector(current_dir);
826 else if (std::error_code ec = current_path(current_dir))
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000827 return ec;
Michael J. Spencer92903a32010-12-07 03:57:17 +0000828
829 // Relative path. Prepend the current directory.
830 if (!rootName && !rootDirectory) {
831 // Append path to the current directory.
Michael J. Spencer1e090f02010-12-07 03:57:37 +0000832 path::append(current_dir, p);
Michael J. Spencer92903a32010-12-07 03:57:17 +0000833 // Set path to the result.
834 path.swap(current_dir);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000835 return std::error_code();
Michael J. Spencer92903a32010-12-07 03:57:17 +0000836 }
837
838 if (!rootName && rootDirectory) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000839 StringRef cdrn = path::root_name(current_dir);
Michael J. Spencer92903a32010-12-07 03:57:17 +0000840 SmallString<128> curDirRootName(cdrn.begin(), cdrn.end());
Michael J. Spencer1e090f02010-12-07 03:57:37 +0000841 path::append(curDirRootName, p);
Michael J. Spencer92903a32010-12-07 03:57:17 +0000842 // Set path to the result.
843 path.swap(curDirRootName);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000844 return std::error_code();
Michael J. Spencer92903a32010-12-07 03:57:17 +0000845 }
846
847 if (rootName && !rootDirectory) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000848 StringRef pRootName = path::root_name(p);
849 StringRef bRootDirectory = path::root_directory(current_dir);
850 StringRef bRelativePath = path::relative_path(current_dir);
851 StringRef pRelativePath = path::relative_path(p);
Michael J. Spencer92903a32010-12-07 03:57:17 +0000852
853 SmallString<128> res;
Michael J. Spencer1e090f02010-12-07 03:57:37 +0000854 path::append(res, pRootName, bRootDirectory, bRelativePath, pRelativePath);
Michael J. Spencer92903a32010-12-07 03:57:17 +0000855 path.swap(res);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000856 return std::error_code();
Michael J. Spencer92903a32010-12-07 03:57:17 +0000857 }
858
859 llvm_unreachable("All rootName and rootDirectory combinations should have "
860 "occurred above!");
861}
862
Benjamin Kramerae1d5992015-10-05 13:02:43 +0000863std::error_code make_absolute(const Twine &current_directory,
864 SmallVectorImpl<char> &path) {
865 return make_absolute(current_directory, path, true);
866}
867
868std::error_code make_absolute(SmallVectorImpl<char> &path) {
869 return make_absolute(Twine(), path, false);
870}
871
Frederic Riss6b9396c2015-08-06 21:04:55 +0000872std::error_code create_directories(const Twine &Path, bool IgnoreExisting,
873 perms Perms) {
Rafael Espindolab6f72b22014-02-13 16:58:19 +0000874 SmallString<128> PathStorage;
875 StringRef P = Path.toStringRef(PathStorage);
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000876
Rafael Espindolab6f72b22014-02-13 16:58:19 +0000877 // Be optimistic and try to create the directory
Frederic Riss6b9396c2015-08-06 21:04:55 +0000878 std::error_code EC = create_directory(P, IgnoreExisting, Perms);
Rafael Espindolab6f72b22014-02-13 16:58:19 +0000879 // If we succeeded, or had any error other than the parent not existing, just
880 // return it.
Rafael Espindola2a826e42014-06-13 17:20:48 +0000881 if (EC != errc::no_such_file_or_directory)
Rafael Espindolab6f72b22014-02-13 16:58:19 +0000882 return EC;
Michael J. Spencerf616b212010-12-07 17:04:04 +0000883
Rafael Espindolab6f72b22014-02-13 16:58:19 +0000884 // We failed because of a no_such_file_or_directory, try to create the
885 // parent.
886 StringRef Parent = path::parent_path(P);
887 if (Parent.empty())
888 return EC;
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000889
Frederic Riss6b9396c2015-08-06 21:04:55 +0000890 if ((EC = create_directories(Parent, IgnoreExisting, Perms)))
Rafael Espindolab6f72b22014-02-13 16:58:19 +0000891 return EC;
892
Frederic Riss6b9396c2015-08-06 21:04:55 +0000893 return create_directory(P, IgnoreExisting, Perms);
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000894}
895
Justin Bognercd45f962014-06-19 19:35:39 +0000896std::error_code copy_file(const Twine &From, const Twine &To) {
897 int ReadFD, WriteFD;
898 if (std::error_code EC = openFileForRead(From, ReadFD))
899 return EC;
900 if (std::error_code EC = openFileForWrite(To, WriteFD, F_None)) {
901 close(ReadFD);
902 return EC;
903 }
904
905 const size_t BufSize = 4096;
Dylan Noblesmith42836d92014-08-26 02:03:30 +0000906 char *Buf = new char[BufSize];
Justin Bognercd45f962014-06-19 19:35:39 +0000907 int BytesRead = 0, BytesWritten = 0;
908 for (;;) {
909 BytesRead = read(ReadFD, Buf, BufSize);
910 if (BytesRead <= 0)
911 break;
912 while (BytesRead) {
913 BytesWritten = write(WriteFD, Buf, BytesRead);
914 if (BytesWritten < 0)
915 break;
916 BytesRead -= BytesWritten;
917 }
918 if (BytesWritten < 0)
919 break;
920 }
921 close(ReadFD);
922 close(WriteFD);
Dylan Noblesmith42836d92014-08-26 02:03:30 +0000923 delete[] Buf;
Justin Bognercd45f962014-06-19 19:35:39 +0000924
925 if (BytesRead < 0 || BytesWritten < 0)
926 return std::error_code(errno, std::generic_category());
927 return std::error_code();
928}
929
Michael J. Spencer730f51a2010-12-09 17:37:02 +0000930bool exists(file_status status) {
931 return status_known(status) && status.type() != file_type::file_not_found;
932}
933
934bool status_known(file_status s) {
935 return s.type() != file_type::status_error;
936}
937
938bool is_directory(file_status status) {
939 return status.type() == file_type::directory_file;
940}
941
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000942std::error_code is_directory(const Twine &path, bool &result) {
Michael J. Spencer0d771ed2011-01-11 01:21:55 +0000943 file_status st;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000944 if (std::error_code ec = status(path, st))
Michael J. Spencer0d771ed2011-01-11 01:21:55 +0000945 return ec;
946 result = is_directory(st);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000947 return std::error_code();
Michael J. Spencer0d771ed2011-01-11 01:21:55 +0000948}
949
Michael J. Spencer730f51a2010-12-09 17:37:02 +0000950bool is_regular_file(file_status status) {
951 return status.type() == file_type::regular_file;
952}
953
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000954std::error_code is_regular_file(const Twine &path, bool &result) {
Michael J. Spencer0d771ed2011-01-11 01:21:55 +0000955 file_status st;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000956 if (std::error_code ec = status(path, st))
Michael J. Spencer0d771ed2011-01-11 01:21:55 +0000957 return ec;
958 result = is_regular_file(st);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000959 return std::error_code();
Michael J. Spencer0d771ed2011-01-11 01:21:55 +0000960}
961
Michael J. Spencer730f51a2010-12-09 17:37:02 +0000962bool is_other(file_status status) {
963 return exists(status) &&
964 !is_regular_file(status) &&
Rafael Espindola20063062014-03-20 17:39:04 +0000965 !is_directory(status);
Michael J. Spencer730f51a2010-12-09 17:37:02 +0000966}
967
Juergen Ributzka84ba3422014-12-18 18:19:47 +0000968std::error_code is_other(const Twine &Path, bool &Result) {
969 file_status FileStatus;
970 if (std::error_code EC = status(Path, FileStatus))
971 return EC;
972 Result = is_other(FileStatus);
973 return std::error_code();
974}
975
Benjamin Kramer91ead3c2011-09-14 01:14:36 +0000976void directory_entry::replace_filename(const Twine &filename, file_status st) {
Rafael Espindolaf662e002015-07-15 21:24:07 +0000977 SmallString<128> path = path::parent_path(Path);
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000978 path::append(path, filename);
979 Path = path.str();
980 Status = st;
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000981}
982
Rui Ueyama6b77ad32016-11-15 01:57:05 +0000983template <size_t N>
984static bool startswith(StringRef Magic, const char (&S)[N]) {
985 return Magic.startswith(StringRef(S, N - 1));
986}
987
Michael J. Spencer4f8a8322011-12-13 23:17:12 +0000988/// @brief Identify the magic in magic.
Logan Chienc0f691d2014-06-25 13:46:17 +0000989file_magic identify_magic(StringRef Magic) {
Rafael Espindola9b404292013-06-11 17:22:12 +0000990 if (Magic.size() < 4)
Michael J. Spencer96ebd912012-06-19 05:29:57 +0000991 return file_magic::unknown;
Rafael Espindola9b404292013-06-11 17:22:12 +0000992 switch ((unsigned char)Magic[0]) {
Rui Ueyamafc149a62013-10-15 22:45:38 +0000993 case 0x00: {
Rui Ueyama2d021662016-11-15 00:54:54 +0000994 // COFF bigobj, CL.exe's LTO object file, or short import library file
Rui Ueyama6b77ad32016-11-15 01:57:05 +0000995 if (startswith(Magic, "\0\0\xFF\xFF")) {
Rui Ueyama5c69ff52014-09-11 22:34:32 +0000996 size_t MinSize = offsetof(COFF::BigObjHeader, UUID) + sizeof(COFF::BigObjMagic);
997 if (Magic.size() < MinSize)
998 return file_magic::coff_import_library;
999
Rui Ueyama5c69ff52014-09-11 22:34:32 +00001000 const char *Start = Magic.data() + offsetof(COFF::BigObjHeader, UUID);
Rui Ueyama2d021662016-11-15 00:54:54 +00001001 if (memcmp(Start, COFF::BigObjMagic, sizeof(COFF::BigObjMagic)) == 0)
1002 return file_magic::coff_object;
1003 if (memcmp(Start, COFF::ClGlObjMagic, sizeof(COFF::BigObjMagic)) == 0)
1004 return file_magic::coff_cl_gl_object;
1005 return file_magic::coff_import_library;
Rui Ueyama2acb0582014-09-11 21:09:57 +00001006 }
Rui Ueyamafc149a62013-10-15 22:45:38 +00001007 // Windows resource file
Rui Ueyama6b77ad32016-11-15 01:57:05 +00001008 if (startswith(Magic, "\0\0\0\0\x20\0\0\0\xFF"))
Rui Ueyamafc149a62013-10-15 22:45:38 +00001009 return file_magic::windows_resource;
Rui Ueyama829c4392013-11-14 22:09:08 +00001010 // 0x0000 = COFF unknown machine type
1011 if (Magic[1] == 0)
1012 return file_magic::coff_object;
Rui Ueyamafc149a62013-10-15 22:45:38 +00001013 break;
1014 }
Michael J. Spencer4f8a8322011-12-13 23:17:12 +00001015 case 0xDE: // 0x0B17C0DE = BC wraper
Rui Ueyama6b77ad32016-11-15 01:57:05 +00001016 if (startswith(Magic, "\xDE\xC0\x17\x0B"))
Michael J. Spencer4f8a8322011-12-13 23:17:12 +00001017 return file_magic::bitcode;
1018 break;
1019 case 'B':
Rui Ueyama6b77ad32016-11-15 01:57:05 +00001020 if (startswith(Magic, "BC\xC0\xDE"))
Michael J. Spencer4f8a8322011-12-13 23:17:12 +00001021 return file_magic::bitcode;
1022 break;
1023 case '!':
Rui Ueyama6b77ad32016-11-15 01:57:05 +00001024 if (startswith(Magic, "!<arch>\n") || startswith(Magic, "!<thin>\n"))
1025 return file_magic::archive;
Michael J. Spencer4f8a8322011-12-13 23:17:12 +00001026 break;
1027
1028 case '\177':
Rui Ueyama6b77ad32016-11-15 01:57:05 +00001029 if (startswith(Magic, "\177ELF") && Magic.size() >= 18) {
Rafael Espindola9b404292013-06-11 17:22:12 +00001030 bool Data2MSB = Magic[5] == 2;
Michael J. Spencerb8055cb2013-04-05 20:10:04 +00001031 unsigned high = Data2MSB ? 16 : 17;
1032 unsigned low = Data2MSB ? 17 : 16;
Rui Ueyama6b77ad32016-11-15 01:57:05 +00001033 if (Magic[high] == 0) {
Rafael Espindola9b404292013-06-11 17:22:12 +00001034 switch (Magic[low]) {
Michael J. Spencere368a622015-01-23 21:58:09 +00001035 default: return file_magic::elf;
Michael J. Spencer4f8a8322011-12-13 23:17:12 +00001036 case 1: return file_magic::elf_relocatable;
1037 case 2: return file_magic::elf_executable;
1038 case 3: return file_magic::elf_shared_object;
1039 case 4: return file_magic::elf_core;
1040 }
Rui Ueyama6b77ad32016-11-15 01:57:05 +00001041 }
1042 // It's still some type of ELF file.
1043 return file_magic::elf;
Michael J. Spencer4f8a8322011-12-13 23:17:12 +00001044 }
1045 break;
1046
1047 case 0xCA:
Rui Ueyama6b77ad32016-11-15 01:57:05 +00001048 if (startswith(Magic, "\xCA\xFE\xBA\xBE") ||
1049 startswith(Magic, "\xCA\xFE\xBA\xBF")) {
Michael J. Spencer4f8a8322011-12-13 23:17:12 +00001050 // This is complicated by an overlap with Java class files.
1051 // See the Mach-O section in /usr/share/file/magic for details.
Rafael Espindola9b404292013-06-11 17:22:12 +00001052 if (Magic.size() >= 8 && Magic[7] < 43)
Alexey Samsonove6388e62013-06-18 15:03:28 +00001053 return file_magic::macho_universal_binary;
Michael J. Spencer4f8a8322011-12-13 23:17:12 +00001054 }
1055 break;
1056
1057 // The two magic numbers for mach-o are:
1058 // 0xfeedface - 32-bit mach-o
1059 // 0xfeedfacf - 64-bit mach-o
1060 case 0xFE:
1061 case 0xCE:
1062 case 0xCF: {
1063 uint16_t type = 0;
Rui Ueyama6b77ad32016-11-15 01:57:05 +00001064 if (startswith(Magic, "\xFE\xED\xFA\xCE") ||
1065 startswith(Magic, "\xFE\xED\xFA\xCF")) {
Michael J. Spencer4f8a8322011-12-13 23:17:12 +00001066 /* Native endian */
Kevin Enderby87c85b72016-01-26 23:43:37 +00001067 size_t MinSize;
1068 if (Magic[3] == char(0xCE))
1069 MinSize = sizeof(MachO::mach_header);
1070 else
1071 MinSize = sizeof(MachO::mach_header_64);
1072 if (Magic.size() >= MinSize)
1073 type = Magic[12] << 24 | Magic[13] << 12 | Magic[14] << 8 | Magic[15];
Rui Ueyama6b77ad32016-11-15 01:57:05 +00001074 } else if (startswith(Magic, "\xCE\xFA\xED\xFE") ||
1075 startswith(Magic, "\xCF\xFA\xED\xFE")) {
Michael J. Spencer4f8a8322011-12-13 23:17:12 +00001076 /* Reverse endian */
Kevin Enderby87c85b72016-01-26 23:43:37 +00001077 size_t MinSize;
1078 if (Magic[0] == char(0xCE))
1079 MinSize = sizeof(MachO::mach_header);
1080 else
1081 MinSize = sizeof(MachO::mach_header_64);
1082 if (Magic.size() >= MinSize)
1083 type = Magic[15] << 24 | Magic[14] << 12 |Magic[13] << 8 | Magic[12];
Michael J. Spencer4f8a8322011-12-13 23:17:12 +00001084 }
1085 switch (type) {
1086 default: break;
1087 case 1: return file_magic::macho_object;
1088 case 2: return file_magic::macho_executable;
1089 case 3: return file_magic::macho_fixed_virtual_memory_shared_lib;
1090 case 4: return file_magic::macho_core;
Rafael Espindola134cc992013-06-10 20:32:27 +00001091 case 5: return file_magic::macho_preload_executable;
Michael J. Spencer4f8a8322011-12-13 23:17:12 +00001092 case 6: return file_magic::macho_dynamically_linked_shared_lib;
1093 case 7: return file_magic::macho_dynamic_linker;
1094 case 8: return file_magic::macho_bundle;
Nick Kledzik2d2b2542014-09-17 00:53:44 +00001095 case 9: return file_magic::macho_dynamically_linked_shared_lib_stub;
Michael J. Spencer4f8a8322011-12-13 23:17:12 +00001096 case 10: return file_magic::macho_dsym_companion;
Justin Bognera7ad4b32015-02-25 22:59:20 +00001097 case 11: return file_magic::macho_kext_bundle;
Michael J. Spencer4f8a8322011-12-13 23:17:12 +00001098 }
1099 break;
1100 }
1101 case 0xF0: // PowerPC Windows
1102 case 0x83: // Alpha 32-bit
1103 case 0x84: // Alpha 64-bit
1104 case 0x66: // MPS R4000 Windows
1105 case 0x50: // mc68K
1106 case 0x4c: // 80386 Windows
Saleem Abdulrasool9b7c0af2014-03-13 07:02:35 +00001107 case 0xc4: // ARMNT Windows
Rafael Espindola9b404292013-06-11 17:22:12 +00001108 if (Magic[1] == 0x01)
Michael J. Spencer4f8a8322011-12-13 23:17:12 +00001109 return file_magic::coff_object;
1110
1111 case 0x90: // PA-RISC Windows
1112 case 0x68: // mc68K Windows
Rafael Espindola9b404292013-06-11 17:22:12 +00001113 if (Magic[1] == 0x02)
Michael J. Spencer4f8a8322011-12-13 23:17:12 +00001114 return file_magic::coff_object;
1115 break;
1116
David Majnemer50267222014-11-05 06:24:35 +00001117 case 'M': // Possible MS-DOS stub on Windows PE file
Rui Ueyama6b77ad32016-11-15 01:57:05 +00001118 if (startswith(Magic, "MZ")) {
Rui Ueyama3206b792015-03-02 21:19:12 +00001119 uint32_t off = read32le(Magic.data() + 0x3c);
Michael J. Spencer4f8a8322011-12-13 23:17:12 +00001120 // PE/COFF file, either EXE or DLL.
David Majnemer50267222014-11-05 06:24:35 +00001121 if (off < Magic.size() &&
1122 memcmp(Magic.data()+off, COFF::PEMagic, sizeof(COFF::PEMagic)) == 0)
Michael J. Spencer4f8a8322011-12-13 23:17:12 +00001123 return file_magic::pecoff_executable;
1124 }
1125 break;
1126
1127 case 0x64: // x86-64 Windows.
Rafael Espindola9b404292013-06-11 17:22:12 +00001128 if (Magic[1] == char(0x86))
Michael J. Spencer4f8a8322011-12-13 23:17:12 +00001129 return file_magic::coff_object;
1130 break;
1131
1132 default:
1133 break;
1134 }
1135 return file_magic::unknown;
1136}
1137
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001138std::error_code identify_magic(const Twine &Path, file_magic &Result) {
Rafael Espindolada70bfd2014-06-11 22:53:00 +00001139 int FD;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001140 if (std::error_code EC = openFileForRead(Path, FD))
Rafael Espindolada70bfd2014-06-11 22:53:00 +00001141 return EC;
Michael J. Spencer94b2ab32011-01-15 20:39:36 +00001142
Rafael Espindolada70bfd2014-06-11 22:53:00 +00001143 char Buffer[32];
1144 int Length = read(FD, Buffer, sizeof(Buffer));
Rafael Espindolaa8acef62014-06-25 14:35:59 +00001145 if (close(FD) != 0 || Length < 0)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001146 return std::error_code(errno, std::generic_category());
Rafael Espindolada70bfd2014-06-11 22:53:00 +00001147
1148 Result = identify_magic(StringRef(Buffer, Length));
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001149 return std::error_code();
Michael J. Spencer94b2ab32011-01-15 20:39:36 +00001150}
1151
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001152std::error_code directory_entry::status(file_status &result) const {
Michael J. Spencerf8dc1862011-01-05 16:39:13 +00001153 return fs::status(Path, result);
1154}
1155
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +00001156} // end namespace fs
1157} // end namespace sys
1158} // end namespace llvm
Michael J. Spencerebad2f92010-11-29 22:28:51 +00001159
1160// Include the truly platform-specific parts.
1161#if defined(LLVM_ON_UNIX)
Rafael Espindolaf1fc3822013-06-26 19:33:03 +00001162#include "Unix/Path.inc"
Michael J. Spencerebad2f92010-11-29 22:28:51 +00001163#endif
1164#if defined(LLVM_ON_WIN32)
Rafael Espindolaf1fc3822013-06-26 19:33:03 +00001165#include "Windows/Path.inc"
Michael J. Spencerebad2f92010-11-29 22:28:51 +00001166#endif
Pawel Bylica0e97e5c2015-11-02 09:49:17 +00001167
1168namespace llvm {
1169namespace sys {
1170namespace path {
1171
1172bool user_cache_directory(SmallVectorImpl<char> &Result, const Twine &Path1,
1173 const Twine &Path2, const Twine &Path3) {
1174 if (getUserCacheDir(Result)) {
1175 append(Result, Path1, Path2, Path3);
1176 return true;
1177 }
1178 return false;
1179}
1180
1181} // end namespace path
1182} // end namsspace sys
1183} // end namespace llvm