blob: 259000b4e47c14737a0650dda79aece507a0b313 [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
Rafael Espindola2a826e42014-06-13 17:20:48 +000014#include "llvm/Support/Errc.h"
Rafael Espindola3bc8e712013-06-11 22:21:28 +000015#include "llvm/Support/Path.h"
Michael J. Spencer4f8a8322011-12-13 23:17:12 +000016#include "llvm/Support/Endian.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"
Aaron Ballman07e76182014-02-11 03:40:14 +000019#include "llvm/Support/Process.h"
Michael J. Spencerebad2f92010-11-29 22:28:51 +000020#include <cctype>
Michael J. Spencer848f46b2010-12-28 01:49:01 +000021#include <cstdio>
22#include <cstring>
Rafael Espindola6d354812013-07-16 19:44:17 +000023#include <fcntl.h>
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;
32
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 // * {/,\}
50 // * {.,..}
51 // * {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
77 if (path.startswith(".."))
Benjamin Kramerffa42ce2010-12-17 20:27:37 +000078 return path.substr(0, 2);
Michael J. Spencerebad2f92010-11-29 22:28:51 +000079
80 if (path[0] == '.')
Benjamin Kramerffa42ce2010-12-17 20:27:37 +000081 return path.substr(0, 1);
Michael J. Spencerebad2f92010-11-29 22:28:51 +000082
83 // * {file,directory}name
Tareq A. Siraj73537ea2013-08-12 17:10:49 +000084 size_t end = path.find_first_of(separators);
Benjamin Kramerffa42ce2010-12-17 20:27:37 +000085 return path.substr(0, end);
Michael J. Spencerebad2f92010-11-29 22:28:51 +000086 }
Michael J. Spencer545cbdf2010-11-30 23:28:07 +000087
Benjamin Kramer292b44b2010-12-17 18:19:06 +000088 size_t filename_pos(StringRef str) {
Michael J. Spencer545cbdf2010-11-30 23:28:07 +000089 if (str.size() == 2 &&
90 is_separator(str[0]) &&
Michael J. Spencerbfea3c72010-12-07 03:57:48 +000091 str[0] == str[1])
Michael J. Spencer545cbdf2010-11-30 23:28:07 +000092 return 0;
93
94 if (str.size() > 0 && is_separator(str[str.size() - 1]))
95 return str.size() - 1;
96
97 size_t pos = str.find_last_of(separators, str.size() - 1);
98
99#ifdef LLVM_ON_WIN32
100 if (pos == StringRef::npos)
101 pos = str.find_last_of(':', str.size() - 2);
102#endif
103
104 if (pos == StringRef::npos ||
105 (pos == 1 && is_separator(str[0])))
106 return 0;
107
108 return pos + 1;
109 }
110
Benjamin Kramer292b44b2010-12-17 18:19:06 +0000111 size_t root_dir_start(StringRef str) {
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000112 // case "c:/"
113#ifdef LLVM_ON_WIN32
114 if (str.size() > 2 &&
115 str[1] == ':' &&
116 is_separator(str[2]))
117 return 2;
118#endif
119
120 // case "//"
121 if (str.size() == 2 &&
122 is_separator(str[0]) &&
123 str[0] == str[1])
124 return StringRef::npos;
125
126 // case "//net"
127 if (str.size() > 3 &&
128 is_separator(str[0]) &&
129 str[0] == str[1] &&
130 !is_separator(str[2])) {
131 return str.find_first_of(separators, 2);
132 }
133
134 // case "/"
135 if (str.size() > 0 && is_separator(str[0]))
136 return 0;
137
138 return StringRef::npos;
139 }
140
Benjamin Kramer292b44b2010-12-17 18:19:06 +0000141 size_t parent_path_end(StringRef path) {
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000142 size_t end_pos = filename_pos(path);
143
144 bool filename_was_sep = path.size() > 0 && is_separator(path[end_pos]);
145
146 // Skip separators except for root dir.
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000147 size_t root_dir_pos = root_dir_start(path.substr(0, end_pos));
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000148
149 while(end_pos > 0 &&
150 (end_pos - 1) != root_dir_pos &&
151 is_separator(path[end_pos - 1]))
152 --end_pos;
153
154 if (end_pos == 1 && root_dir_pos == 0 && filename_was_sep)
155 return StringRef::npos;
156
157 return end_pos;
158 }
Zhanyong Wan606bb1a2011-02-11 21:24:40 +0000159} // end unnamed namespace
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000160
Rafael Espindolae79a8722013-06-28 03:48:47 +0000161enum FSEntity {
162 FS_Dir,
163 FS_File,
164 FS_Name
165};
166
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000167static std::error_code createUniqueEntity(const Twine &Model, int &ResultFD,
168 SmallVectorImpl<char> &ResultPath,
169 bool MakeAbsolute, unsigned Mode,
170 FSEntity Type) {
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000171 SmallString<128> ModelStorage;
172 Model.toVector(ModelStorage);
173
174 if (MakeAbsolute) {
175 // Make model absolute by prepending a temp directory if it's not already.
176 if (!sys::path::is_absolute(Twine(ModelStorage))) {
177 SmallString<128> TDir;
Rafael Espindola016a6d52014-08-26 14:47:52 +0000178 sys::path::system_temp_directory(true, TDir);
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000179 sys::path::append(TDir, Twine(ModelStorage));
180 ModelStorage.swap(TDir);
181 }
182 }
183
184 // From here on, DO NOT modify model. It may be needed if the randomly chosen
185 // path already exists.
186 ResultPath = ModelStorage;
187 // Null terminate.
188 ResultPath.push_back(0);
189 ResultPath.pop_back();
190
191retry_random_path:
192 // Replace '%' with random chars.
193 for (unsigned i = 0, e = ModelStorage.size(); i != e; ++i) {
194 if (ModelStorage[i] == '%')
195 ResultPath[i] = "0123456789abcdef"[sys::Process::GetRandomNumber() & 15];
196 }
197
198 // Try to open + create the file.
199 switch (Type) {
200 case FS_File: {
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000201 if (std::error_code EC =
Rafael Espindola90c7f1c2014-02-24 18:20:12 +0000202 sys::fs::openFileForWrite(Twine(ResultPath.begin()), ResultFD,
203 sys::fs::F_RW | sys::fs::F_Excl, Mode)) {
Rafael Espindola2a826e42014-06-13 17:20:48 +0000204 if (EC == errc::file_exists)
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000205 goto retry_random_path;
206 return EC;
207 }
208
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000209 return std::error_code();
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000210 }
211
212 case FS_Name: {
213 bool Exists;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000214 std::error_code EC = sys::fs::exists(ResultPath.begin(), Exists);
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000215 if (EC)
216 return EC;
217 if (Exists)
218 goto retry_random_path;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000219 return std::error_code();
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000220 }
221
222 case FS_Dir: {
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000223 if (std::error_code EC =
224 sys::fs::create_directory(ResultPath.begin(), false)) {
Rafael Espindola2a826e42014-06-13 17:20:48 +0000225 if (EC == errc::file_exists)
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000226 goto retry_random_path;
227 return EC;
228 }
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000229 return std::error_code();
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000230 }
231 }
232 llvm_unreachable("Invalid Type");
233}
Rafael Espindolae79a8722013-06-28 03:48:47 +0000234
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000235namespace llvm {
236namespace sys {
237namespace path {
238
Benjamin Kramer292b44b2010-12-17 18:19:06 +0000239const_iterator begin(StringRef path) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000240 const_iterator i;
241 i.Path = path;
242 i.Component = find_first_component(path);
243 i.Position = 0;
244 return i;
245}
246
Benjamin Kramer292b44b2010-12-17 18:19:06 +0000247const_iterator end(StringRef path) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000248 const_iterator i;
249 i.Path = path;
250 i.Position = path.size();
251 return i;
252}
253
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000254const_iterator &const_iterator::operator++() {
255 assert(Position < Path.size() && "Tried to increment past end!");
256
257 // Increment Position to past the current component
258 Position += Component.size();
259
260 // Check for end.
261 if (Position == Path.size()) {
262 Component = StringRef();
263 return *this;
264 }
265
266 // Both POSIX and Windows treat paths that begin with exactly two separators
267 // specially.
268 bool was_net = Component.size() > 2 &&
269 is_separator(Component[0]) &&
270 Component[1] == Component[0] &&
271 !is_separator(Component[2]);
272
273 // Handle separators.
274 if (is_separator(Path[Position])) {
275 // Root dir.
276 if (was_net
277#ifdef LLVM_ON_WIN32
278 // c:/
279 || Component.endswith(":")
280#endif
281 ) {
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000282 Component = Path.substr(Position, 1);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000283 return *this;
284 }
285
286 // Skip extra separators.
287 while (Position != Path.size() &&
288 is_separator(Path[Position])) {
289 ++Position;
290 }
291
292 // Treat trailing '/' as a '.'.
293 if (Position == Path.size()) {
294 --Position;
295 Component = ".";
296 return *this;
297 }
298 }
299
300 // Find next component.
301 size_t end_pos = Path.find_first_of(separators, Position);
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000302 Component = Path.slice(Position, end_pos);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000303
304 return *this;
305}
306
Justin Bogner487e7642014-08-04 17:36:41 +0000307bool const_iterator::operator==(const const_iterator &RHS) const {
308 return Path.begin() == RHS.Path.begin() && Position == RHS.Position;
309}
310
311ptrdiff_t const_iterator::operator-(const const_iterator &RHS) const {
312 return Position - RHS.Position;
313}
314
315reverse_iterator rbegin(StringRef Path) {
316 reverse_iterator I;
317 I.Path = Path;
318 I.Position = Path.size();
319 return ++I;
320}
321
322reverse_iterator rend(StringRef Path) {
323 reverse_iterator I;
324 I.Path = Path;
325 I.Component = Path.substr(0, 0);
326 I.Position = 0;
327 return I;
328}
329
330reverse_iterator &reverse_iterator::operator++() {
Ben Langmuir8d116392014-03-05 19:56:30 +0000331 // If we're at the end and the previous char was a '/', return '.' unless
332 // we are the root path.
333 size_t root_dir_pos = root_dir_start(Path);
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000334 if (Position == Path.size() &&
Ben Langmuir8d116392014-03-05 19:56:30 +0000335 Path.size() > root_dir_pos + 1 &&
336 is_separator(Path[Position - 1])) {
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000337 --Position;
338 Component = ".";
339 return *this;
340 }
341
342 // Skip separators unless it's the root directory.
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000343 size_t end_pos = Position;
344
345 while(end_pos > 0 &&
346 (end_pos - 1) != root_dir_pos &&
347 is_separator(Path[end_pos - 1]))
348 --end_pos;
349
350 // Find next separator.
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000351 size_t start_pos = filename_pos(Path.substr(0, end_pos));
352 Component = Path.slice(start_pos, end_pos);
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000353 Position = start_pos;
354 return *this;
355}
356
Justin Bogner487e7642014-08-04 17:36:41 +0000357bool reverse_iterator::operator==(const reverse_iterator &RHS) const {
358 return Path.begin() == RHS.Path.begin() && Component == RHS.Component &&
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000359 Position == RHS.Position;
360}
361
Benjamin Kramer292b44b2010-12-17 18:19:06 +0000362const StringRef root_path(StringRef path) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000363 const_iterator b = begin(path),
364 pos = b,
365 e = end(path);
366 if (b != e) {
367 bool has_net = b->size() > 2 && is_separator((*b)[0]) && (*b)[1] == (*b)[0];
368 bool has_drive =
369#ifdef LLVM_ON_WIN32
370 b->endswith(":");
371#else
372 false;
373#endif
374
375 if (has_net || has_drive) {
376 if ((++pos != e) && is_separator((*pos)[0])) {
377 // {C:/,//net/}, so get the first two components.
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000378 return path.substr(0, b->size() + pos->size());
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000379 } else {
380 // just {C:,//net}, return the first component.
Michael J. Spencerf616b212010-12-07 17:04:04 +0000381 return *b;
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000382 }
383 }
384
385 // POSIX style root directory.
386 if (is_separator((*b)[0])) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000387 return *b;
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000388 }
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000389 }
390
Michael J. Spencerf616b212010-12-07 17:04:04 +0000391 return StringRef();
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000392}
393
Benjamin Kramer292b44b2010-12-17 18:19:06 +0000394const StringRef root_name(StringRef path) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000395 const_iterator b = begin(path),
396 e = end(path);
397 if (b != e) {
398 bool has_net = b->size() > 2 && is_separator((*b)[0]) && (*b)[1] == (*b)[0];
399 bool has_drive =
400#ifdef LLVM_ON_WIN32
401 b->endswith(":");
402#else
403 false;
404#endif
405
406 if (has_net || has_drive) {
407 // just {C:,//net}, return the first component.
Michael J. Spencerf616b212010-12-07 17:04:04 +0000408 return *b;
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000409 }
410 }
411
412 // No path or no name.
Michael J. Spencerf616b212010-12-07 17:04:04 +0000413 return StringRef();
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000414}
415
Benjamin Kramer292b44b2010-12-17 18:19:06 +0000416const StringRef root_directory(StringRef path) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000417 const_iterator b = begin(path),
418 pos = b,
419 e = end(path);
420 if (b != e) {
421 bool has_net = b->size() > 2 && is_separator((*b)[0]) && (*b)[1] == (*b)[0];
422 bool has_drive =
423#ifdef LLVM_ON_WIN32
424 b->endswith(":");
425#else
426 false;
427#endif
428
429 if ((has_net || has_drive) &&
430 // {C:,//net}, skip to the next component.
431 (++pos != e) && is_separator((*pos)[0])) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000432 return *pos;
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000433 }
434
435 // POSIX style root directory.
436 if (!has_net && is_separator((*b)[0])) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000437 return *b;
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000438 }
439 }
440
441 // No path or no root.
Michael J. Spencerf616b212010-12-07 17:04:04 +0000442 return StringRef();
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000443}
444
Benjamin Kramer292b44b2010-12-17 18:19:06 +0000445const StringRef relative_path(StringRef path) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000446 StringRef root = root_path(path);
Michael J. Spencere6462392012-02-29 00:06:24 +0000447 return path.substr(root.size());
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000448}
449
Michael J. Spencer1e090f02010-12-07 03:57:37 +0000450void append(SmallVectorImpl<char> &path, const Twine &a,
451 const Twine &b,
452 const Twine &c,
453 const Twine &d) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000454 SmallString<32> a_storage;
455 SmallString<32> b_storage;
456 SmallString<32> c_storage;
457 SmallString<32> d_storage;
458
459 SmallVector<StringRef, 4> components;
460 if (!a.isTriviallyEmpty()) components.push_back(a.toStringRef(a_storage));
461 if (!b.isTriviallyEmpty()) components.push_back(b.toStringRef(b_storage));
462 if (!c.isTriviallyEmpty()) components.push_back(c.toStringRef(c_storage));
463 if (!d.isTriviallyEmpty()) components.push_back(d.toStringRef(d_storage));
464
465 for (SmallVectorImpl<StringRef>::const_iterator i = components.begin(),
466 e = components.end();
467 i != e; ++i) {
468 bool path_has_sep = !path.empty() && is_separator(path[path.size() - 1]);
469 bool component_has_sep = !i->empty() && is_separator((*i)[0]);
Michael J. Spencerf616b212010-12-07 17:04:04 +0000470 bool is_root_name = has_root_name(*i);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000471
472 if (path_has_sep) {
473 // Strip separators from beginning of component.
474 size_t loc = i->find_first_not_of(separators);
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000475 StringRef c = i->substr(loc);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000476
477 // Append it.
478 path.append(c.begin(), c.end());
479 continue;
480 }
481
Michael J. Spencer95e4ac12010-12-06 04:28:23 +0000482 if (!component_has_sep && !(path.empty() || is_root_name)) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000483 // Add a separator.
Alp Tokercb402912014-01-24 17:20:08 +0000484 path.push_back(preferred_separator);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000485 }
486
487 path.append(i->begin(), i->end());
488 }
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000489}
490
Argyrios Kyrtzidisa61736f2011-02-15 17:51:19 +0000491void append(SmallVectorImpl<char> &path,
492 const_iterator begin, const_iterator end) {
493 for (; begin != end; ++begin)
494 path::append(path, *begin);
495}
496
Benjamin Kramer292b44b2010-12-17 18:19:06 +0000497const StringRef parent_path(StringRef path) {
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000498 size_t end_pos = parent_path_end(path);
499 if (end_pos == StringRef::npos)
Michael J. Spencerf616b212010-12-07 17:04:04 +0000500 return StringRef();
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000501 else
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000502 return path.substr(0, end_pos);
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000503}
504
Michael J. Spencer1e090f02010-12-07 03:57:37 +0000505void remove_filename(SmallVectorImpl<char> &path) {
Michael J. Spencer9c594092010-12-01 00:52:28 +0000506 size_t end_pos = parent_path_end(StringRef(path.begin(), path.size()));
Michael J. Spencer1e090f02010-12-07 03:57:37 +0000507 if (end_pos != StringRef::npos)
508 path.set_size(end_pos);
Michael J. Spencer9c594092010-12-01 00:52:28 +0000509}
510
Michael J. Spencerf616b212010-12-07 17:04:04 +0000511void replace_extension(SmallVectorImpl<char> &path, const Twine &extension) {
Michael J. Spencerfb3a95d2010-12-01 00:52:55 +0000512 StringRef p(path.begin(), path.size());
513 SmallString<32> ext_storage;
514 StringRef ext = extension.toStringRef(ext_storage);
515
516 // Erase existing extension.
517 size_t pos = p.find_last_of('.');
518 if (pos != StringRef::npos && pos >= filename_pos(p))
519 path.set_size(pos);
520
521 // Append '.' if needed.
522 if (ext.size() > 0 && ext[0] != '.')
523 path.push_back('.');
524
525 // Append extension.
526 path.append(ext.begin(), ext.end());
Michael J. Spencerfb3a95d2010-12-01 00:52:55 +0000527}
528
Michael J. Spencer1e090f02010-12-07 03:57:37 +0000529void native(const Twine &path, SmallVectorImpl<char> &result) {
Benjamin Kramerbd4ac9b2013-09-11 10:45:21 +0000530 assert((!path.isSingleStringRef() ||
531 path.getSingleStringRef().data() != result.data()) &&
532 "path and result are not allowed to overlap!");
Michael J. Spencer80025002010-12-01 02:48:27 +0000533 // Clear result.
Michael J. Spencer98c7a112010-12-07 01:23:19 +0000534 result.clear();
Michael J. Spencer80025002010-12-01 02:48:27 +0000535 path.toVector(result);
Benjamin Kramerbd4ac9b2013-09-11 10:45:21 +0000536 native(result);
537}
538
Rafael Espindolad649b9d2014-08-08 21:29:34 +0000539void native(SmallVectorImpl<char> &Path) {
Benjamin Kramerbd4ac9b2013-09-11 10:45:21 +0000540#ifdef LLVM_ON_WIN32
Rafael Espindola674ef1d2014-08-08 22:09:31 +0000541 std::replace(Path.begin(), Path.end(), '/', '\\');
Rafael Espindolad649b9d2014-08-08 21:29:34 +0000542#else
543 for (auto PI = Path.begin(), PE = Path.end(); PI < PE; ++PI) {
544 if (*PI == '\\') {
545 auto PN = PI + 1;
546 if (PN < PE && *PN == '\\')
547 ++PI; // increment once, the for loop will move over the escaped slash
548 else
549 *PI = '/';
550 }
551 }
Michael J. Spencer80025002010-12-01 02:48:27 +0000552#endif
Michael J. Spencer80025002010-12-01 02:48:27 +0000553}
554
Benjamin Kramer292b44b2010-12-17 18:19:06 +0000555const StringRef filename(StringRef path) {
Justin Bogner487e7642014-08-04 17:36:41 +0000556 return *rbegin(path);
Michael J. Spencer14269202010-12-01 03:18:17 +0000557}
558
Benjamin Kramer292b44b2010-12-17 18:19:06 +0000559const StringRef stem(StringRef path) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000560 StringRef fname = filename(path);
Michael J. Spencer956955e2010-12-01 03:18:33 +0000561 size_t pos = fname.find_last_of('.');
562 if (pos == StringRef::npos)
Michael J. Spencerf616b212010-12-07 17:04:04 +0000563 return fname;
Michael J. Spencer956955e2010-12-01 03:18:33 +0000564 else
565 if ((fname.size() == 1 && fname == ".") ||
566 (fname.size() == 2 && fname == ".."))
Michael J. Spencerf616b212010-12-07 17:04:04 +0000567 return fname;
Michael J. Spencer956955e2010-12-01 03:18:33 +0000568 else
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000569 return fname.substr(0, pos);
Michael J. Spencer956955e2010-12-01 03:18:33 +0000570}
571
Benjamin Kramer292b44b2010-12-17 18:19:06 +0000572const StringRef extension(StringRef path) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000573 StringRef fname = filename(path);
Michael J. Spencer87106c52010-12-01 03:37:41 +0000574 size_t pos = fname.find_last_of('.');
575 if (pos == StringRef::npos)
Michael J. Spencerf616b212010-12-07 17:04:04 +0000576 return StringRef();
Michael J. Spencer87106c52010-12-01 03:37:41 +0000577 else
578 if ((fname.size() == 1 && fname == ".") ||
579 (fname.size() == 2 && fname == ".."))
Michael J. Spencerf616b212010-12-07 17:04:04 +0000580 return StringRef();
Michael J. Spencer87106c52010-12-01 03:37:41 +0000581 else
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000582 return fname.substr(pos);
Michael J. Spencer87106c52010-12-01 03:37:41 +0000583}
584
Zhanyong Wan606bb1a2011-02-11 21:24:40 +0000585bool is_separator(char value) {
586 switch(value) {
587#ifdef LLVM_ON_WIN32
588 case '\\': // fall through
589#endif
590 case '/': return true;
591 default: return false;
592 }
593}
594
Yaron Keren15217202014-05-16 13:16:30 +0000595static const char preferred_separator_string[] = { preferred_separator, '\0' };
596
597const StringRef get_separator() {
598 return preferred_separator_string;
599}
600
Michael J. Spencera68282c2010-12-07 18:12:07 +0000601bool has_root_name(const Twine &path) {
Michael J. Spencer112a7692010-12-01 06:03:50 +0000602 SmallString<128> path_storage;
603 StringRef p = path.toStringRef(path_storage);
604
Michael J. Spencerf616b212010-12-07 17:04:04 +0000605 return !root_name(p).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000606}
607
Michael J. Spencera68282c2010-12-07 18:12:07 +0000608bool has_root_directory(const Twine &path) {
Michael J. Spencer112a7692010-12-01 06:03:50 +0000609 SmallString<128> path_storage;
610 StringRef p = path.toStringRef(path_storage);
611
Michael J. Spencerf616b212010-12-07 17:04:04 +0000612 return !root_directory(p).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000613}
614
Michael J. Spencera68282c2010-12-07 18:12:07 +0000615bool has_root_path(const Twine &path) {
Michael J. Spencer112a7692010-12-01 06:03:50 +0000616 SmallString<128> path_storage;
617 StringRef p = path.toStringRef(path_storage);
618
Michael J. Spencerf616b212010-12-07 17:04:04 +0000619 return !root_path(p).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000620}
621
Michael J. Spencer6d4b7e72010-12-20 13:30:28 +0000622bool has_relative_path(const Twine &path) {
623 SmallString<128> path_storage;
624 StringRef p = path.toStringRef(path_storage);
625
626 return !relative_path(p).empty();
627}
628
Michael J. Spencera68282c2010-12-07 18:12:07 +0000629bool has_filename(const Twine &path) {
Michael J. Spencer112a7692010-12-01 06:03:50 +0000630 SmallString<128> path_storage;
631 StringRef p = path.toStringRef(path_storage);
632
Michael J. Spencerf616b212010-12-07 17:04:04 +0000633 return !filename(p).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000634}
635
Michael J. Spencera68282c2010-12-07 18:12:07 +0000636bool has_parent_path(const Twine &path) {
Michael J. Spencer112a7692010-12-01 06:03:50 +0000637 SmallString<128> path_storage;
638 StringRef p = path.toStringRef(path_storage);
639
Michael J. Spencerf616b212010-12-07 17:04:04 +0000640 return !parent_path(p).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000641}
642
Michael J. Spencera68282c2010-12-07 18:12:07 +0000643bool has_stem(const Twine &path) {
Michael J. Spencer112a7692010-12-01 06:03:50 +0000644 SmallString<128> path_storage;
645 StringRef p = path.toStringRef(path_storage);
646
Michael J. Spencerf616b212010-12-07 17:04:04 +0000647 return !stem(p).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000648}
649
Michael J. Spencera68282c2010-12-07 18:12:07 +0000650bool has_extension(const Twine &path) {
Michael J. Spencer112a7692010-12-01 06:03:50 +0000651 SmallString<128> path_storage;
652 StringRef p = path.toStringRef(path_storage);
653
Michael J. Spencerf616b212010-12-07 17:04:04 +0000654 return !extension(p).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000655}
656
Michael J. Spencera68282c2010-12-07 18:12:07 +0000657bool is_absolute(const Twine &path) {
Michael J. Spencera72df5f2010-12-01 06:21:53 +0000658 SmallString<128> path_storage;
659 StringRef p = path.toStringRef(path_storage);
660
Michael J. Spencerf616b212010-12-07 17:04:04 +0000661 bool rootDir = has_root_directory(p),
Michael J. Spencera72df5f2010-12-01 06:21:53 +0000662#ifdef LLVM_ON_WIN32
Michael J. Spencerf616b212010-12-07 17:04:04 +0000663 rootName = has_root_name(p);
Michael J. Spencera72df5f2010-12-01 06:21:53 +0000664#else
Michael J. Spencerf616b212010-12-07 17:04:04 +0000665 rootName = true;
Michael J. Spencera72df5f2010-12-01 06:21:53 +0000666#endif
667
Michael J. Spencerf616b212010-12-07 17:04:04 +0000668 return rootDir && rootName;
Michael J. Spencera72df5f2010-12-01 06:21:53 +0000669}
670
Michael J. Spencera68282c2010-12-07 18:12:07 +0000671bool is_relative(const Twine &path) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000672 return !is_absolute(path);
Michael J. Spencera72df5f2010-12-01 06:21:53 +0000673}
674
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +0000675} // end namespace path
676
677namespace fs {
678
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000679std::error_code getUniqueID(const Twine Path, UniqueID &Result) {
Rafael Espindola7f822a92013-07-29 21:26:49 +0000680 file_status Status;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000681 std::error_code EC = status(Path, Status);
Rafael Espindola7f822a92013-07-29 21:26:49 +0000682 if (EC)
683 return EC;
684 Result = Status.getUniqueID();
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000685 return std::error_code();
Rafael Espindola7f822a92013-07-29 21:26:49 +0000686}
687
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000688std::error_code createUniqueFile(const Twine &Model, int &ResultFd,
689 SmallVectorImpl<char> &ResultPath,
690 unsigned Mode) {
Rafael Espindolac9d2e5b2013-07-05 21:01:08 +0000691 return createUniqueEntity(Model, ResultFd, ResultPath, false, Mode, FS_File);
692}
693
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000694std::error_code createUniqueFile(const Twine &Model,
695 SmallVectorImpl<char> &ResultPath) {
Rafael Espindolac9d2e5b2013-07-05 21:01:08 +0000696 int Dummy;
697 return createUniqueEntity(Model, Dummy, ResultPath, false, 0, FS_Name);
698}
699
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000700static std::error_code
701createTemporaryFile(const Twine &Model, int &ResultFD,
702 llvm::SmallVectorImpl<char> &ResultPath, FSEntity Type) {
Rafael Espindola325fa0f2013-07-05 19:56:49 +0000703 SmallString<128> Storage;
704 StringRef P = Model.toNullTerminatedStringRef(Storage);
705 assert(P.find_first_of(separators) == StringRef::npos &&
706 "Model must be a simple filename.");
707 // Use P.begin() so that createUniqueEntity doesn't need to recreate Storage.
708 return createUniqueEntity(P.begin(), ResultFD, ResultPath,
709 true, owner_read | owner_write, Type);
710}
711
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000712static std::error_code
Rafael Espindola325fa0f2013-07-05 19:56:49 +0000713createTemporaryFile(const Twine &Prefix, StringRef Suffix, int &ResultFD,
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000714 llvm::SmallVectorImpl<char> &ResultPath, FSEntity Type) {
Rafael Espindolad3c89042013-07-25 15:00:17 +0000715 const char *Middle = Suffix.empty() ? "-%%%%%%" : "-%%%%%%.";
716 return createTemporaryFile(Prefix + Middle + Suffix, ResultFD, ResultPath,
Rafael Espindola325fa0f2013-07-05 19:56:49 +0000717 Type);
718}
719
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000720std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
721 int &ResultFD,
722 SmallVectorImpl<char> &ResultPath) {
Rafael Espindola325fa0f2013-07-05 19:56:49 +0000723 return createTemporaryFile(Prefix, Suffix, ResultFD, ResultPath, FS_File);
724}
725
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000726std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
727 SmallVectorImpl<char> &ResultPath) {
Rafael Espindola325fa0f2013-07-05 19:56:49 +0000728 int Dummy;
729 return createTemporaryFile(Prefix, Suffix, Dummy, ResultPath, FS_Name);
730}
731
732
Rafael Espindolae79a8722013-06-28 03:48:47 +0000733// This is a mkdtemp with a different pattern. We use createUniqueEntity mostly
Rafael Espindola31a24432013-06-28 10:55:41 +0000734// for consistency. We should try using mkdtemp.
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000735std::error_code createUniqueDirectory(const Twine &Prefix,
736 SmallVectorImpl<char> &ResultPath) {
Rafael Espindolae79a8722013-06-28 03:48:47 +0000737 int Dummy;
738 return createUniqueEntity(Prefix + "-%%%%%%", Dummy, ResultPath,
739 true, 0, FS_Dir);
Rafael Espindola7ffacc42013-06-27 03:45:31 +0000740}
741
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000742std::error_code make_absolute(SmallVectorImpl<char> &path) {
Michael J. Spencer92903a32010-12-07 03:57:17 +0000743 StringRef p(path.data(), path.size());
744
Daniel Dunbarb23158c2012-02-29 00:20:37 +0000745 bool rootDirectory = path::has_root_directory(p),
746#ifdef LLVM_ON_WIN32
Daniel Dunbar39ea4582012-02-29 00:46:46 +0000747 rootName = path::has_root_name(p);
Daniel Dunbarb23158c2012-02-29 00:20:37 +0000748#else
749 rootName = true;
750#endif
Michael J. Spencer92903a32010-12-07 03:57:17 +0000751
752 // Already absolute.
753 if (rootName && rootDirectory)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000754 return std::error_code();
Michael J. Spencer92903a32010-12-07 03:57:17 +0000755
756 // All of the following conditions will need the current directory.
757 SmallString<128> current_dir;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000758 if (std::error_code ec = current_path(current_dir))
759 return ec;
Michael J. Spencer92903a32010-12-07 03:57:17 +0000760
761 // Relative path. Prepend the current directory.
762 if (!rootName && !rootDirectory) {
763 // Append path to the current directory.
Michael J. Spencer1e090f02010-12-07 03:57:37 +0000764 path::append(current_dir, p);
Michael J. Spencer92903a32010-12-07 03:57:17 +0000765 // Set path to the result.
766 path.swap(current_dir);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000767 return std::error_code();
Michael J. Spencer92903a32010-12-07 03:57:17 +0000768 }
769
770 if (!rootName && rootDirectory) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000771 StringRef cdrn = path::root_name(current_dir);
Michael J. Spencer92903a32010-12-07 03:57:17 +0000772 SmallString<128> curDirRootName(cdrn.begin(), cdrn.end());
Michael J. Spencer1e090f02010-12-07 03:57:37 +0000773 path::append(curDirRootName, p);
Michael J. Spencer92903a32010-12-07 03:57:17 +0000774 // Set path to the result.
775 path.swap(curDirRootName);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000776 return std::error_code();
Michael J. Spencer92903a32010-12-07 03:57:17 +0000777 }
778
779 if (rootName && !rootDirectory) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000780 StringRef pRootName = path::root_name(p);
781 StringRef bRootDirectory = path::root_directory(current_dir);
782 StringRef bRelativePath = path::relative_path(current_dir);
783 StringRef pRelativePath = path::relative_path(p);
Michael J. Spencer92903a32010-12-07 03:57:17 +0000784
785 SmallString<128> res;
Michael J. Spencer1e090f02010-12-07 03:57:37 +0000786 path::append(res, pRootName, bRootDirectory, bRelativePath, pRelativePath);
Michael J. Spencer92903a32010-12-07 03:57:17 +0000787 path.swap(res);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000788 return std::error_code();
Michael J. Spencer92903a32010-12-07 03:57:17 +0000789 }
790
791 llvm_unreachable("All rootName and rootDirectory combinations should have "
792 "occurred above!");
793}
794
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000795std::error_code create_directories(const Twine &Path, bool IgnoreExisting) {
Rafael Espindolab6f72b22014-02-13 16:58:19 +0000796 SmallString<128> PathStorage;
797 StringRef P = Path.toStringRef(PathStorage);
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000798
Rafael Espindolab6f72b22014-02-13 16:58:19 +0000799 // Be optimistic and try to create the directory
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000800 std::error_code EC = create_directory(P, IgnoreExisting);
Rafael Espindolab6f72b22014-02-13 16:58:19 +0000801 // If we succeeded, or had any error other than the parent not existing, just
802 // return it.
Rafael Espindola2a826e42014-06-13 17:20:48 +0000803 if (EC != errc::no_such_file_or_directory)
Rafael Espindolab6f72b22014-02-13 16:58:19 +0000804 return EC;
Michael J. Spencerf616b212010-12-07 17:04:04 +0000805
Rafael Espindolab6f72b22014-02-13 16:58:19 +0000806 // We failed because of a no_such_file_or_directory, try to create the
807 // parent.
808 StringRef Parent = path::parent_path(P);
809 if (Parent.empty())
810 return EC;
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000811
Rafael Espindolab6f72b22014-02-13 16:58:19 +0000812 if ((EC = create_directories(Parent)))
813 return EC;
814
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000815 return create_directory(P, IgnoreExisting);
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000816}
817
Justin Bognercd45f962014-06-19 19:35:39 +0000818std::error_code copy_file(const Twine &From, const Twine &To) {
819 int ReadFD, WriteFD;
820 if (std::error_code EC = openFileForRead(From, ReadFD))
821 return EC;
822 if (std::error_code EC = openFileForWrite(To, WriteFD, F_None)) {
823 close(ReadFD);
824 return EC;
825 }
826
827 const size_t BufSize = 4096;
Dylan Noblesmith42836d92014-08-26 02:03:30 +0000828 char *Buf = new char[BufSize];
Justin Bognercd45f962014-06-19 19:35:39 +0000829 int BytesRead = 0, BytesWritten = 0;
830 for (;;) {
831 BytesRead = read(ReadFD, Buf, BufSize);
832 if (BytesRead <= 0)
833 break;
834 while (BytesRead) {
835 BytesWritten = write(WriteFD, Buf, BytesRead);
836 if (BytesWritten < 0)
837 break;
838 BytesRead -= BytesWritten;
839 }
840 if (BytesWritten < 0)
841 break;
842 }
843 close(ReadFD);
844 close(WriteFD);
Dylan Noblesmith42836d92014-08-26 02:03:30 +0000845 delete[] Buf;
Justin Bognercd45f962014-06-19 19:35:39 +0000846
847 if (BytesRead < 0 || BytesWritten < 0)
848 return std::error_code(errno, std::generic_category());
849 return std::error_code();
850}
851
Michael J. Spencer730f51a2010-12-09 17:37:02 +0000852bool exists(file_status status) {
853 return status_known(status) && status.type() != file_type::file_not_found;
854}
855
856bool status_known(file_status s) {
857 return s.type() != file_type::status_error;
858}
859
860bool is_directory(file_status status) {
861 return status.type() == file_type::directory_file;
862}
863
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000864std::error_code is_directory(const Twine &path, bool &result) {
Michael J. Spencer0d771ed2011-01-11 01:21:55 +0000865 file_status st;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000866 if (std::error_code ec = status(path, st))
Michael J. Spencer0d771ed2011-01-11 01:21:55 +0000867 return ec;
868 result = is_directory(st);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000869 return std::error_code();
Michael J. Spencer0d771ed2011-01-11 01:21:55 +0000870}
871
Michael J. Spencer730f51a2010-12-09 17:37:02 +0000872bool is_regular_file(file_status status) {
873 return status.type() == file_type::regular_file;
874}
875
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000876std::error_code is_regular_file(const Twine &path, bool &result) {
Michael J. Spencer0d771ed2011-01-11 01:21:55 +0000877 file_status st;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000878 if (std::error_code ec = status(path, st))
Michael J. Spencer0d771ed2011-01-11 01:21:55 +0000879 return ec;
880 result = is_regular_file(st);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000881 return std::error_code();
Michael J. Spencer0d771ed2011-01-11 01:21:55 +0000882}
883
Michael J. Spencer730f51a2010-12-09 17:37:02 +0000884bool is_other(file_status status) {
885 return exists(status) &&
886 !is_regular_file(status) &&
Rafael Espindola20063062014-03-20 17:39:04 +0000887 !is_directory(status);
Michael J. Spencer730f51a2010-12-09 17:37:02 +0000888}
889
Benjamin Kramer91ead3c2011-09-14 01:14:36 +0000890void directory_entry::replace_filename(const Twine &filename, file_status st) {
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000891 SmallString<128> path(Path.begin(), Path.end());
892 path::remove_filename(path);
893 path::append(path, filename);
894 Path = path.str();
895 Status = st;
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000896}
897
Michael J. Spencer4f8a8322011-12-13 23:17:12 +0000898/// @brief Identify the magic in magic.
Logan Chienc0f691d2014-06-25 13:46:17 +0000899file_magic identify_magic(StringRef Magic) {
Rafael Espindola9b404292013-06-11 17:22:12 +0000900 if (Magic.size() < 4)
Michael J. Spencer96ebd912012-06-19 05:29:57 +0000901 return file_magic::unknown;
Rafael Espindola9b404292013-06-11 17:22:12 +0000902 switch ((unsigned char)Magic[0]) {
Rui Ueyamafc149a62013-10-15 22:45:38 +0000903 case 0x00: {
Rui Ueyamae448f9e2013-11-15 21:22:02 +0000904 // COFF short import library file
905 if (Magic[1] == (char)0x00 && Magic[2] == (char)0xff &&
906 Magic[3] == (char)0xff)
907 return file_magic::coff_import_library;
Rui Ueyamafc149a62013-10-15 22:45:38 +0000908 // Windows resource file
Rui Ueyama50a86e12013-10-16 03:29:49 +0000909 const char Expected[] = { 0, 0, 0, 0, '\x20', 0, 0, 0, '\xff' };
Rui Ueyamafc149a62013-10-15 22:45:38 +0000910 if (Magic.size() >= sizeof(Expected) &&
911 memcmp(Magic.data(), Expected, sizeof(Expected)) == 0)
912 return file_magic::windows_resource;
Rui Ueyama829c4392013-11-14 22:09:08 +0000913 // 0x0000 = COFF unknown machine type
914 if (Magic[1] == 0)
915 return file_magic::coff_object;
Rui Ueyamafc149a62013-10-15 22:45:38 +0000916 break;
917 }
Michael J. Spencer4f8a8322011-12-13 23:17:12 +0000918 case 0xDE: // 0x0B17C0DE = BC wraper
Rafael Espindola9b404292013-06-11 17:22:12 +0000919 if (Magic[1] == (char)0xC0 && Magic[2] == (char)0x17 &&
920 Magic[3] == (char)0x0B)
Michael J. Spencer4f8a8322011-12-13 23:17:12 +0000921 return file_magic::bitcode;
922 break;
923 case 'B':
Rafael Espindola9b404292013-06-11 17:22:12 +0000924 if (Magic[1] == 'C' && Magic[2] == (char)0xC0 && Magic[3] == (char)0xDE)
Michael J. Spencer4f8a8322011-12-13 23:17:12 +0000925 return file_magic::bitcode;
926 break;
927 case '!':
Rafael Espindola9b404292013-06-11 17:22:12 +0000928 if (Magic.size() >= 8)
929 if (memcmp(Magic.data(),"!<arch>\n",8) == 0)
Michael J. Spencer4f8a8322011-12-13 23:17:12 +0000930 return file_magic::archive;
931 break;
932
933 case '\177':
Rafael Espindola823de7c2013-06-11 17:25:45 +0000934 if (Magic.size() >= 18 && Magic[1] == 'E' && Magic[2] == 'L' &&
935 Magic[3] == 'F') {
Rafael Espindola9b404292013-06-11 17:22:12 +0000936 bool Data2MSB = Magic[5] == 2;
Michael J. Spencerb8055cb2013-04-05 20:10:04 +0000937 unsigned high = Data2MSB ? 16 : 17;
938 unsigned low = Data2MSB ? 17 : 16;
Rafael Espindola823de7c2013-06-11 17:25:45 +0000939 if (Magic[high] == 0)
Rafael Espindola9b404292013-06-11 17:22:12 +0000940 switch (Magic[low]) {
Michael J. Spencer4f8a8322011-12-13 23:17:12 +0000941 default: break;
942 case 1: return file_magic::elf_relocatable;
943 case 2: return file_magic::elf_executable;
944 case 3: return file_magic::elf_shared_object;
945 case 4: return file_magic::elf_core;
946 }
947 }
948 break;
949
950 case 0xCA:
Rafael Espindola9b404292013-06-11 17:22:12 +0000951 if (Magic[1] == char(0xFE) && Magic[2] == char(0xBA) &&
952 Magic[3] == char(0xBE)) {
Michael J. Spencer4f8a8322011-12-13 23:17:12 +0000953 // This is complicated by an overlap with Java class files.
954 // See the Mach-O section in /usr/share/file/magic for details.
Rafael Espindola9b404292013-06-11 17:22:12 +0000955 if (Magic.size() >= 8 && Magic[7] < 43)
Alexey Samsonove6388e62013-06-18 15:03:28 +0000956 return file_magic::macho_universal_binary;
Michael J. Spencer4f8a8322011-12-13 23:17:12 +0000957 }
958 break;
959
960 // The two magic numbers for mach-o are:
961 // 0xfeedface - 32-bit mach-o
962 // 0xfeedfacf - 64-bit mach-o
963 case 0xFE:
964 case 0xCE:
965 case 0xCF: {
966 uint16_t type = 0;
Rafael Espindola9b404292013-06-11 17:22:12 +0000967 if (Magic[0] == char(0xFE) && Magic[1] == char(0xED) &&
968 Magic[2] == char(0xFA) &&
969 (Magic[3] == char(0xCE) || Magic[3] == char(0xCF))) {
Michael J. Spencer4f8a8322011-12-13 23:17:12 +0000970 /* Native endian */
Rafael Espindola9b404292013-06-11 17:22:12 +0000971 if (Magic.size() >= 16) type = Magic[14] << 8 | Magic[15];
972 } else if ((Magic[0] == char(0xCE) || Magic[0] == char(0xCF)) &&
973 Magic[1] == char(0xFA) && Magic[2] == char(0xED) &&
974 Magic[3] == char(0xFE)) {
Michael J. Spencer4f8a8322011-12-13 23:17:12 +0000975 /* Reverse endian */
Rafael Espindola9b404292013-06-11 17:22:12 +0000976 if (Magic.size() >= 14) type = Magic[13] << 8 | Magic[12];
Michael J. Spencer4f8a8322011-12-13 23:17:12 +0000977 }
978 switch (type) {
979 default: break;
980 case 1: return file_magic::macho_object;
981 case 2: return file_magic::macho_executable;
982 case 3: return file_magic::macho_fixed_virtual_memory_shared_lib;
983 case 4: return file_magic::macho_core;
Rafael Espindola134cc992013-06-10 20:32:27 +0000984 case 5: return file_magic::macho_preload_executable;
Michael J. Spencer4f8a8322011-12-13 23:17:12 +0000985 case 6: return file_magic::macho_dynamically_linked_shared_lib;
986 case 7: return file_magic::macho_dynamic_linker;
987 case 8: return file_magic::macho_bundle;
988 case 9: return file_magic::macho_dynamic_linker;
989 case 10: return file_magic::macho_dsym_companion;
990 }
991 break;
992 }
993 case 0xF0: // PowerPC Windows
994 case 0x83: // Alpha 32-bit
995 case 0x84: // Alpha 64-bit
996 case 0x66: // MPS R4000 Windows
997 case 0x50: // mc68K
998 case 0x4c: // 80386 Windows
Saleem Abdulrasool9b7c0af2014-03-13 07:02:35 +0000999 case 0xc4: // ARMNT Windows
Rafael Espindola9b404292013-06-11 17:22:12 +00001000 if (Magic[1] == 0x01)
Michael J. Spencer4f8a8322011-12-13 23:17:12 +00001001 return file_magic::coff_object;
1002
1003 case 0x90: // PA-RISC Windows
1004 case 0x68: // mc68K Windows
Rafael Espindola9b404292013-06-11 17:22:12 +00001005 if (Magic[1] == 0x02)
Michael J. Spencer4f8a8322011-12-13 23:17:12 +00001006 return file_magic::coff_object;
1007 break;
1008
1009 case 0x4d: // Possible MS-DOS stub on Windows PE file
Rafael Espindola9b404292013-06-11 17:22:12 +00001010 if (Magic[1] == 0x5a) {
Michael J. Spencer4f8a8322011-12-13 23:17:12 +00001011 uint32_t off =
Rafael Espindola9b404292013-06-11 17:22:12 +00001012 *reinterpret_cast<const support::ulittle32_t*>(Magic.data() + 0x3c);
Michael J. Spencer4f8a8322011-12-13 23:17:12 +00001013 // PE/COFF file, either EXE or DLL.
Rafael Espindola9b404292013-06-11 17:22:12 +00001014 if (off < Magic.size() && memcmp(Magic.data() + off, "PE\0\0",4) == 0)
Michael J. Spencer4f8a8322011-12-13 23:17:12 +00001015 return file_magic::pecoff_executable;
1016 }
1017 break;
1018
1019 case 0x64: // x86-64 Windows.
Rafael Espindola9b404292013-06-11 17:22:12 +00001020 if (Magic[1] == char(0x86))
Michael J. Spencer4f8a8322011-12-13 23:17:12 +00001021 return file_magic::coff_object;
1022 break;
1023
1024 default:
1025 break;
1026 }
1027 return file_magic::unknown;
1028}
1029
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001030std::error_code identify_magic(const Twine &Path, file_magic &Result) {
Rafael Espindolada70bfd2014-06-11 22:53:00 +00001031 int FD;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001032 if (std::error_code EC = openFileForRead(Path, FD))
Rafael Espindolada70bfd2014-06-11 22:53:00 +00001033 return EC;
Michael J. Spencer94b2ab32011-01-15 20:39:36 +00001034
Rafael Espindolada70bfd2014-06-11 22:53:00 +00001035 char Buffer[32];
1036 int Length = read(FD, Buffer, sizeof(Buffer));
Rafael Espindolaa8acef62014-06-25 14:35:59 +00001037 if (close(FD) != 0 || Length < 0)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001038 return std::error_code(errno, std::generic_category());
Rafael Espindolada70bfd2014-06-11 22:53:00 +00001039
1040 Result = identify_magic(StringRef(Buffer, Length));
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001041 return std::error_code();
Michael J. Spencer94b2ab32011-01-15 20:39:36 +00001042}
1043
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001044std::error_code directory_entry::status(file_status &result) const {
Michael J. Spencerf8dc1862011-01-05 16:39:13 +00001045 return fs::status(Path, result);
1046}
1047
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +00001048} // end namespace fs
1049} // end namespace sys
1050} // end namespace llvm
Michael J. Spencerebad2f92010-11-29 22:28:51 +00001051
1052// Include the truly platform-specific parts.
1053#if defined(LLVM_ON_UNIX)
Rafael Espindolaf1fc3822013-06-26 19:33:03 +00001054#include "Unix/Path.inc"
Michael J. Spencerebad2f92010-11-29 22:28:51 +00001055#endif
1056#if defined(LLVM_ON_WIN32)
Rafael Espindolaf1fc3822013-06-26 19:33:03 +00001057#include "Windows/Path.inc"
Michael J. Spencerebad2f92010-11-29 22:28:51 +00001058#endif