blob: 781c17c18793427188b8db888f1fde0b56c0f4e1 [file] [log] [blame]
Rafael Espindolaf1fc3822013-06-26 19:33:03 +00001//===-- Path.cpp - Implement OS Path Concept ------------------------------===//
Michael J. Spencerebad2f92010-11-29 22:28:51 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Rafael Espindolaf1fc3822013-06-26 19:33:03 +000010// This file implements the operating system Path API.
Michael J. Spencerebad2f92010-11-29 22:28:51 +000011//
12//===----------------------------------------------------------------------===//
13
Rui Ueyama5c69ff52014-09-11 22:34:32 +000014#include "llvm/Support/COFF.h"
15#include "llvm/Support/Endian.h"
Rafael Espindola2a826e42014-06-13 17:20:48 +000016#include "llvm/Support/Errc.h"
Rafael Espindola3bc8e712013-06-11 22:21:28 +000017#include "llvm/Support/Path.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"
Aaron Ballman07e76182014-02-11 03:40:14 +000020#include "llvm/Support/Process.h"
Michael J. Spencerebad2f92010-11-29 22:28:51 +000021#include <cctype>
Michael J. Spencer848f46b2010-12-28 01:49:01 +000022#include <cstdio>
23#include <cstring>
Rafael Espindola6d354812013-07-16 19:44:17 +000024#include <fcntl.h>
Rafael Espindola4526b1d2013-06-18 17:01:00 +000025
26#if !defined(_MSC_VER) && !defined(__MINGW32__)
Douglas Gregora86ddf02013-03-21 21:46:10 +000027#include <unistd.h>
Rafael Espindola4526b1d2013-06-18 17:01:00 +000028#else
29#include <io.h>
Douglas Gregora86ddf02013-03-21 21:46:10 +000030#endif
Michael J. Spencerebad2f92010-11-29 22:28:51 +000031
Rafael Espindola7a0b6402014-02-24 03:07:41 +000032using namespace llvm;
33
Michael J. Spencerebad2f92010-11-29 22:28:51 +000034namespace {
35 using llvm::StringRef;
Zhanyong Wan606bb1a2011-02-11 21:24:40 +000036 using llvm::sys::path::is_separator;
Michael J. Spencerebad2f92010-11-29 22:28:51 +000037
38#ifdef LLVM_ON_WIN32
Benjamin Kramer5e4f0a42012-02-08 13:13:47 +000039 const char *separators = "\\/";
Alp Tokercb402912014-01-24 17:20:08 +000040 const char preferred_separator = '\\';
Michael J. Spencerebad2f92010-11-29 22:28:51 +000041#else
Benjamin Kramer5e4f0a42012-02-08 13:13:47 +000042 const char separators = '/';
Alp Tokercb402912014-01-24 17:20:08 +000043 const char preferred_separator = '/';
Michael J. Spencerebad2f92010-11-29 22:28:51 +000044#endif
45
Benjamin Kramercb520cd2010-12-17 18:59:09 +000046 StringRef find_first_component(StringRef path) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +000047 // Look for this first component in the following order.
48 // * empty (in this case we return an empty string)
49 // * either C: or {//,\\}net.
50 // * {/,\}
51 // * {.,..}
52 // * {file,directory}name
53
54 if (path.empty())
55 return path;
56
Michael J. Spencerbfea3c72010-12-07 03:57:48 +000057#ifdef LLVM_ON_WIN32
Michael J. Spencerebad2f92010-11-29 22:28:51 +000058 // C:
Guy Benyei83c74e92013-02-12 21:21:59 +000059 if (path.size() >= 2 && std::isalpha(static_cast<unsigned char>(path[0])) &&
60 path[1] == ':')
Benjamin Kramerffa42ce2010-12-17 20:27:37 +000061 return path.substr(0, 2);
Michael J. Spencerbfea3c72010-12-07 03:57:48 +000062#endif
Michael J. Spencerebad2f92010-11-29 22:28:51 +000063
64 // //net
65 if ((path.size() > 2) &&
Michael J. Spencerbfea3c72010-12-07 03:57:48 +000066 is_separator(path[0]) &&
67 path[0] == path[1] &&
68 !is_separator(path[2])) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +000069 // Find the next directory separator.
Michael J. Spencerbfea3c72010-12-07 03:57:48 +000070 size_t end = path.find_first_of(separators, 2);
Benjamin Kramerffa42ce2010-12-17 20:27:37 +000071 return path.substr(0, end);
Michael J. Spencerebad2f92010-11-29 22:28:51 +000072 }
73
74 // {/,\}
Michael J. Spencerbfea3c72010-12-07 03:57:48 +000075 if (is_separator(path[0]))
Benjamin Kramerffa42ce2010-12-17 20:27:37 +000076 return path.substr(0, 1);
Michael J. Spencerebad2f92010-11-29 22:28:51 +000077
78 if (path.startswith(".."))
Benjamin Kramerffa42ce2010-12-17 20:27:37 +000079 return path.substr(0, 2);
Michael J. Spencerebad2f92010-11-29 22:28:51 +000080
81 if (path[0] == '.')
Benjamin Kramerffa42ce2010-12-17 20:27:37 +000082 return path.substr(0, 1);
Michael J. Spencerebad2f92010-11-29 22:28:51 +000083
84 // * {file,directory}name
Tareq A. Siraj73537ea2013-08-12 17:10:49 +000085 size_t end = path.find_first_of(separators);
Benjamin Kramerffa42ce2010-12-17 20:27:37 +000086 return path.substr(0, end);
Michael J. Spencerebad2f92010-11-29 22:28:51 +000087 }
Michael J. Spencer545cbdf2010-11-30 23:28:07 +000088
Benjamin Kramer292b44b2010-12-17 18:19:06 +000089 size_t filename_pos(StringRef str) {
Michael J. Spencer545cbdf2010-11-30 23:28:07 +000090 if (str.size() == 2 &&
91 is_separator(str[0]) &&
Michael J. Spencerbfea3c72010-12-07 03:57:48 +000092 str[0] == str[1])
Michael J. Spencer545cbdf2010-11-30 23:28:07 +000093 return 0;
94
95 if (str.size() > 0 && is_separator(str[str.size() - 1]))
96 return str.size() - 1;
97
98 size_t pos = str.find_last_of(separators, str.size() - 1);
99
100#ifdef LLVM_ON_WIN32
101 if (pos == StringRef::npos)
102 pos = str.find_last_of(':', str.size() - 2);
103#endif
104
105 if (pos == StringRef::npos ||
106 (pos == 1 && is_separator(str[0])))
107 return 0;
108
109 return pos + 1;
110 }
111
Benjamin Kramer292b44b2010-12-17 18:19:06 +0000112 size_t root_dir_start(StringRef str) {
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000113 // case "c:/"
114#ifdef LLVM_ON_WIN32
115 if (str.size() > 2 &&
116 str[1] == ':' &&
117 is_separator(str[2]))
118 return 2;
119#endif
120
121 // case "//"
122 if (str.size() == 2 &&
123 is_separator(str[0]) &&
124 str[0] == str[1])
125 return StringRef::npos;
126
127 // case "//net"
128 if (str.size() > 3 &&
129 is_separator(str[0]) &&
130 str[0] == str[1] &&
131 !is_separator(str[2])) {
132 return str.find_first_of(separators, 2);
133 }
134
135 // case "/"
136 if (str.size() > 0 && is_separator(str[0]))
137 return 0;
138
139 return StringRef::npos;
140 }
141
Benjamin Kramer292b44b2010-12-17 18:19:06 +0000142 size_t parent_path_end(StringRef path) {
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000143 size_t end_pos = filename_pos(path);
144
145 bool filename_was_sep = path.size() > 0 && is_separator(path[end_pos]);
146
147 // Skip separators except for root dir.
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000148 size_t root_dir_pos = root_dir_start(path.substr(0, end_pos));
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000149
150 while(end_pos > 0 &&
151 (end_pos - 1) != root_dir_pos &&
152 is_separator(path[end_pos - 1]))
153 --end_pos;
154
155 if (end_pos == 1 && root_dir_pos == 0 && filename_was_sep)
156 return StringRef::npos;
157
158 return end_pos;
159 }
Zhanyong Wan606bb1a2011-02-11 21:24:40 +0000160} // end unnamed namespace
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000161
Rafael Espindolae79a8722013-06-28 03:48:47 +0000162enum FSEntity {
163 FS_Dir,
164 FS_File,
165 FS_Name
166};
167
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000168static std::error_code createUniqueEntity(const Twine &Model, int &ResultFD,
169 SmallVectorImpl<char> &ResultPath,
170 bool MakeAbsolute, unsigned Mode,
171 FSEntity Type) {
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000172 SmallString<128> ModelStorage;
173 Model.toVector(ModelStorage);
174
175 if (MakeAbsolute) {
176 // Make model absolute by prepending a temp directory if it's not already.
177 if (!sys::path::is_absolute(Twine(ModelStorage))) {
178 SmallString<128> TDir;
Rafael Espindola016a6d52014-08-26 14:47:52 +0000179 sys::path::system_temp_directory(true, TDir);
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000180 sys::path::append(TDir, Twine(ModelStorage));
181 ModelStorage.swap(TDir);
182 }
183 }
184
185 // From here on, DO NOT modify model. It may be needed if the randomly chosen
186 // path already exists.
187 ResultPath = ModelStorage;
188 // Null terminate.
189 ResultPath.push_back(0);
190 ResultPath.pop_back();
191
192retry_random_path:
193 // Replace '%' with random chars.
194 for (unsigned i = 0, e = ModelStorage.size(); i != e; ++i) {
195 if (ModelStorage[i] == '%')
196 ResultPath[i] = "0123456789abcdef"[sys::Process::GetRandomNumber() & 15];
197 }
198
199 // Try to open + create the file.
200 switch (Type) {
201 case FS_File: {
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000202 if (std::error_code EC =
Rafael Espindola90c7f1c2014-02-24 18:20:12 +0000203 sys::fs::openFileForWrite(Twine(ResultPath.begin()), ResultFD,
204 sys::fs::F_RW | sys::fs::F_Excl, Mode)) {
Rafael Espindola2a826e42014-06-13 17:20:48 +0000205 if (EC == errc::file_exists)
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000206 goto retry_random_path;
207 return EC;
208 }
209
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000210 return std::error_code();
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000211 }
212
213 case FS_Name: {
Rafael Espindola281f23a2014-09-11 20:30:02 +0000214 std::error_code EC =
215 sys::fs::access(ResultPath.begin(), sys::fs::AccessMode::Exist);
216 if (EC == errc::no_such_file_or_directory)
217 return std::error_code();
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000218 if (EC)
219 return EC;
Rafael Espindola281f23a2014-09-11 20:30:02 +0000220 goto retry_random_path;
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000221 }
222
223 case FS_Dir: {
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000224 if (std::error_code EC =
225 sys::fs::create_directory(ResultPath.begin(), false)) {
Rafael Espindola2a826e42014-06-13 17:20:48 +0000226 if (EC == errc::file_exists)
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000227 goto retry_random_path;
228 return EC;
229 }
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000230 return std::error_code();
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000231 }
232 }
233 llvm_unreachable("Invalid Type");
234}
Rafael Espindolae79a8722013-06-28 03:48:47 +0000235
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000236namespace llvm {
237namespace sys {
238namespace path {
239
Benjamin Kramer292b44b2010-12-17 18:19:06 +0000240const_iterator begin(StringRef path) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000241 const_iterator i;
242 i.Path = path;
243 i.Component = find_first_component(path);
244 i.Position = 0;
245 return i;
246}
247
Benjamin Kramer292b44b2010-12-17 18:19:06 +0000248const_iterator end(StringRef path) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000249 const_iterator i;
250 i.Path = path;
251 i.Position = path.size();
252 return i;
253}
254
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000255const_iterator &const_iterator::operator++() {
256 assert(Position < Path.size() && "Tried to increment past end!");
257
258 // Increment Position to past the current component
259 Position += Component.size();
260
261 // Check for end.
262 if (Position == Path.size()) {
263 Component = StringRef();
264 return *this;
265 }
266
267 // Both POSIX and Windows treat paths that begin with exactly two separators
268 // specially.
269 bool was_net = Component.size() > 2 &&
270 is_separator(Component[0]) &&
271 Component[1] == Component[0] &&
272 !is_separator(Component[2]);
273
274 // Handle separators.
275 if (is_separator(Path[Position])) {
276 // Root dir.
277 if (was_net
278#ifdef LLVM_ON_WIN32
279 // c:/
280 || Component.endswith(":")
281#endif
282 ) {
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000283 Component = Path.substr(Position, 1);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000284 return *this;
285 }
286
287 // Skip extra separators.
288 while (Position != Path.size() &&
289 is_separator(Path[Position])) {
290 ++Position;
291 }
292
293 // Treat trailing '/' as a '.'.
294 if (Position == Path.size()) {
295 --Position;
296 Component = ".";
297 return *this;
298 }
299 }
300
301 // Find next component.
302 size_t end_pos = Path.find_first_of(separators, Position);
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000303 Component = Path.slice(Position, end_pos);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000304
305 return *this;
306}
307
Justin Bogner487e7642014-08-04 17:36:41 +0000308bool const_iterator::operator==(const const_iterator &RHS) const {
309 return Path.begin() == RHS.Path.begin() && Position == RHS.Position;
310}
311
312ptrdiff_t const_iterator::operator-(const const_iterator &RHS) const {
313 return Position - RHS.Position;
314}
315
316reverse_iterator rbegin(StringRef Path) {
317 reverse_iterator I;
318 I.Path = Path;
319 I.Position = Path.size();
320 return ++I;
321}
322
323reverse_iterator rend(StringRef Path) {
324 reverse_iterator I;
325 I.Path = Path;
326 I.Component = Path.substr(0, 0);
327 I.Position = 0;
328 return I;
329}
330
331reverse_iterator &reverse_iterator::operator++() {
Ben Langmuir8d116392014-03-05 19:56:30 +0000332 // If we're at the end and the previous char was a '/', return '.' unless
333 // we are the root path.
334 size_t root_dir_pos = root_dir_start(Path);
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000335 if (Position == Path.size() &&
Ben Langmuir8d116392014-03-05 19:56:30 +0000336 Path.size() > root_dir_pos + 1 &&
337 is_separator(Path[Position - 1])) {
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000338 --Position;
339 Component = ".";
340 return *this;
341 }
342
343 // Skip separators unless it's the root directory.
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000344 size_t end_pos = Position;
345
346 while(end_pos > 0 &&
347 (end_pos - 1) != root_dir_pos &&
348 is_separator(Path[end_pos - 1]))
349 --end_pos;
350
351 // Find next separator.
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000352 size_t start_pos = filename_pos(Path.substr(0, end_pos));
353 Component = Path.slice(start_pos, end_pos);
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000354 Position = start_pos;
355 return *this;
356}
357
Justin Bogner487e7642014-08-04 17:36:41 +0000358bool reverse_iterator::operator==(const reverse_iterator &RHS) const {
359 return Path.begin() == RHS.Path.begin() && Component == RHS.Component &&
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000360 Position == RHS.Position;
361}
362
Craig Topper6dc4a8bc2014-08-30 16:48:02 +0000363StringRef root_path(StringRef path) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000364 const_iterator b = begin(path),
365 pos = b,
366 e = end(path);
367 if (b != e) {
368 bool has_net = b->size() > 2 && is_separator((*b)[0]) && (*b)[1] == (*b)[0];
369 bool has_drive =
370#ifdef LLVM_ON_WIN32
371 b->endswith(":");
372#else
373 false;
374#endif
375
376 if (has_net || has_drive) {
377 if ((++pos != e) && is_separator((*pos)[0])) {
378 // {C:/,//net/}, so get the first two components.
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000379 return path.substr(0, b->size() + pos->size());
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000380 } else {
381 // just {C:,//net}, return the first component.
Michael J. Spencerf616b212010-12-07 17:04:04 +0000382 return *b;
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000383 }
384 }
385
386 // POSIX style root directory.
387 if (is_separator((*b)[0])) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000388 return *b;
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000389 }
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000390 }
391
Michael J. Spencerf616b212010-12-07 17:04:04 +0000392 return StringRef();
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000393}
394
Craig Topper6dc4a8bc2014-08-30 16:48:02 +0000395StringRef root_name(StringRef path) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000396 const_iterator b = begin(path),
397 e = end(path);
398 if (b != e) {
399 bool has_net = b->size() > 2 && is_separator((*b)[0]) && (*b)[1] == (*b)[0];
400 bool has_drive =
401#ifdef LLVM_ON_WIN32
402 b->endswith(":");
403#else
404 false;
405#endif
406
407 if (has_net || has_drive) {
408 // just {C:,//net}, return the first component.
Michael J. Spencerf616b212010-12-07 17:04:04 +0000409 return *b;
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000410 }
411 }
412
413 // No path or no name.
Michael J. Spencerf616b212010-12-07 17:04:04 +0000414 return StringRef();
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000415}
416
Craig Topper6dc4a8bc2014-08-30 16:48:02 +0000417StringRef root_directory(StringRef path) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000418 const_iterator b = begin(path),
419 pos = b,
420 e = end(path);
421 if (b != e) {
422 bool has_net = b->size() > 2 && is_separator((*b)[0]) && (*b)[1] == (*b)[0];
423 bool has_drive =
424#ifdef LLVM_ON_WIN32
425 b->endswith(":");
426#else
427 false;
428#endif
429
430 if ((has_net || has_drive) &&
431 // {C:,//net}, skip to the next component.
432 (++pos != e) && is_separator((*pos)[0])) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000433 return *pos;
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000434 }
435
436 // POSIX style root directory.
437 if (!has_net && is_separator((*b)[0])) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000438 return *b;
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000439 }
440 }
441
442 // No path or no root.
Michael J. Spencerf616b212010-12-07 17:04:04 +0000443 return StringRef();
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000444}
445
Craig Topper6dc4a8bc2014-08-30 16:48:02 +0000446StringRef relative_path(StringRef path) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000447 StringRef root = root_path(path);
Michael J. Spencere6462392012-02-29 00:06:24 +0000448 return path.substr(root.size());
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000449}
450
Michael J. Spencer1e090f02010-12-07 03:57:37 +0000451void append(SmallVectorImpl<char> &path, const Twine &a,
452 const Twine &b,
453 const Twine &c,
454 const Twine &d) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000455 SmallString<32> a_storage;
456 SmallString<32> b_storage;
457 SmallString<32> c_storage;
458 SmallString<32> d_storage;
459
460 SmallVector<StringRef, 4> components;
461 if (!a.isTriviallyEmpty()) components.push_back(a.toStringRef(a_storage));
462 if (!b.isTriviallyEmpty()) components.push_back(b.toStringRef(b_storage));
463 if (!c.isTriviallyEmpty()) components.push_back(c.toStringRef(c_storage));
464 if (!d.isTriviallyEmpty()) components.push_back(d.toStringRef(d_storage));
465
466 for (SmallVectorImpl<StringRef>::const_iterator i = components.begin(),
467 e = components.end();
468 i != e; ++i) {
469 bool path_has_sep = !path.empty() && is_separator(path[path.size() - 1]);
470 bool component_has_sep = !i->empty() && is_separator((*i)[0]);
Michael J. Spencerf616b212010-12-07 17:04:04 +0000471 bool is_root_name = has_root_name(*i);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000472
473 if (path_has_sep) {
474 // Strip separators from beginning of component.
475 size_t loc = i->find_first_not_of(separators);
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000476 StringRef c = i->substr(loc);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000477
478 // Append it.
479 path.append(c.begin(), c.end());
480 continue;
481 }
482
Michael J. Spencer95e4ac12010-12-06 04:28:23 +0000483 if (!component_has_sep && !(path.empty() || is_root_name)) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000484 // Add a separator.
Alp Tokercb402912014-01-24 17:20:08 +0000485 path.push_back(preferred_separator);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000486 }
487
488 path.append(i->begin(), i->end());
489 }
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000490}
491
Argyrios Kyrtzidisa61736f2011-02-15 17:51:19 +0000492void append(SmallVectorImpl<char> &path,
493 const_iterator begin, const_iterator end) {
494 for (; begin != end; ++begin)
495 path::append(path, *begin);
496}
497
Craig Topper6dc4a8bc2014-08-30 16:48:02 +0000498StringRef parent_path(StringRef path) {
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000499 size_t end_pos = parent_path_end(path);
500 if (end_pos == StringRef::npos)
Michael J. Spencerf616b212010-12-07 17:04:04 +0000501 return StringRef();
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000502 else
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000503 return path.substr(0, end_pos);
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000504}
505
Michael J. Spencer1e090f02010-12-07 03:57:37 +0000506void remove_filename(SmallVectorImpl<char> &path) {
Michael J. Spencer9c594092010-12-01 00:52:28 +0000507 size_t end_pos = parent_path_end(StringRef(path.begin(), path.size()));
Michael J. Spencer1e090f02010-12-07 03:57:37 +0000508 if (end_pos != StringRef::npos)
509 path.set_size(end_pos);
Michael J. Spencer9c594092010-12-01 00:52:28 +0000510}
511
Michael J. Spencerf616b212010-12-07 17:04:04 +0000512void replace_extension(SmallVectorImpl<char> &path, const Twine &extension) {
Michael J. Spencerfb3a95d2010-12-01 00:52:55 +0000513 StringRef p(path.begin(), path.size());
514 SmallString<32> ext_storage;
515 StringRef ext = extension.toStringRef(ext_storage);
516
517 // Erase existing extension.
518 size_t pos = p.find_last_of('.');
519 if (pos != StringRef::npos && pos >= filename_pos(p))
520 path.set_size(pos);
521
522 // Append '.' if needed.
523 if (ext.size() > 0 && ext[0] != '.')
524 path.push_back('.');
525
526 // Append extension.
527 path.append(ext.begin(), ext.end());
Michael J. Spencerfb3a95d2010-12-01 00:52:55 +0000528}
529
Michael J. Spencer1e090f02010-12-07 03:57:37 +0000530void native(const Twine &path, SmallVectorImpl<char> &result) {
Benjamin Kramerbd4ac9b2013-09-11 10:45:21 +0000531 assert((!path.isSingleStringRef() ||
532 path.getSingleStringRef().data() != result.data()) &&
533 "path and result are not allowed to overlap!");
Michael J. Spencer80025002010-12-01 02:48:27 +0000534 // Clear result.
Michael J. Spencer98c7a112010-12-07 01:23:19 +0000535 result.clear();
Michael J. Spencer80025002010-12-01 02:48:27 +0000536 path.toVector(result);
Benjamin Kramerbd4ac9b2013-09-11 10:45:21 +0000537 native(result);
538}
539
Rafael Espindolad649b9d2014-08-08 21:29:34 +0000540void native(SmallVectorImpl<char> &Path) {
Benjamin Kramerbd4ac9b2013-09-11 10:45:21 +0000541#ifdef LLVM_ON_WIN32
Rafael Espindola674ef1d2014-08-08 22:09:31 +0000542 std::replace(Path.begin(), Path.end(), '/', '\\');
Rafael Espindolad649b9d2014-08-08 21:29:34 +0000543#else
544 for (auto PI = Path.begin(), PE = Path.end(); PI < PE; ++PI) {
545 if (*PI == '\\') {
546 auto PN = PI + 1;
547 if (PN < PE && *PN == '\\')
548 ++PI; // increment once, the for loop will move over the escaped slash
549 else
550 *PI = '/';
551 }
552 }
Michael J. Spencer80025002010-12-01 02:48:27 +0000553#endif
Michael J. Spencer80025002010-12-01 02:48:27 +0000554}
555
Craig Topper6dc4a8bc2014-08-30 16:48:02 +0000556StringRef filename(StringRef path) {
Justin Bogner487e7642014-08-04 17:36:41 +0000557 return *rbegin(path);
Michael J. Spencer14269202010-12-01 03:18:17 +0000558}
559
Craig Topper6dc4a8bc2014-08-30 16:48:02 +0000560StringRef stem(StringRef path) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000561 StringRef fname = filename(path);
Michael J. Spencer956955e2010-12-01 03:18:33 +0000562 size_t pos = fname.find_last_of('.');
563 if (pos == StringRef::npos)
Michael J. Spencerf616b212010-12-07 17:04:04 +0000564 return fname;
Michael J. Spencer956955e2010-12-01 03:18:33 +0000565 else
566 if ((fname.size() == 1 && fname == ".") ||
567 (fname.size() == 2 && fname == ".."))
Michael J. Spencerf616b212010-12-07 17:04:04 +0000568 return fname;
Michael J. Spencer956955e2010-12-01 03:18:33 +0000569 else
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000570 return fname.substr(0, pos);
Michael J. Spencer956955e2010-12-01 03:18:33 +0000571}
572
Craig Topper6dc4a8bc2014-08-30 16:48:02 +0000573StringRef extension(StringRef path) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000574 StringRef fname = filename(path);
Michael J. Spencer87106c52010-12-01 03:37:41 +0000575 size_t pos = fname.find_last_of('.');
576 if (pos == StringRef::npos)
Michael J. Spencerf616b212010-12-07 17:04:04 +0000577 return StringRef();
Michael J. Spencer87106c52010-12-01 03:37:41 +0000578 else
579 if ((fname.size() == 1 && fname == ".") ||
580 (fname.size() == 2 && fname == ".."))
Michael J. Spencerf616b212010-12-07 17:04:04 +0000581 return StringRef();
Michael J. Spencer87106c52010-12-01 03:37:41 +0000582 else
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000583 return fname.substr(pos);
Michael J. Spencer87106c52010-12-01 03:37:41 +0000584}
585
Zhanyong Wan606bb1a2011-02-11 21:24:40 +0000586bool is_separator(char value) {
587 switch(value) {
588#ifdef LLVM_ON_WIN32
589 case '\\': // fall through
590#endif
591 case '/': return true;
592 default: return false;
593 }
594}
595
Yaron Keren15217202014-05-16 13:16:30 +0000596static const char preferred_separator_string[] = { preferred_separator, '\0' };
597
Craig Topper6dc4a8bc2014-08-30 16:48:02 +0000598StringRef get_separator() {
Yaron Keren15217202014-05-16 13:16:30 +0000599 return preferred_separator_string;
600}
601
Michael J. Spencera68282c2010-12-07 18:12:07 +0000602bool has_root_name(const Twine &path) {
Michael J. Spencer112a7692010-12-01 06:03:50 +0000603 SmallString<128> path_storage;
604 StringRef p = path.toStringRef(path_storage);
605
Michael J. Spencerf616b212010-12-07 17:04:04 +0000606 return !root_name(p).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000607}
608
Michael J. Spencera68282c2010-12-07 18:12:07 +0000609bool has_root_directory(const Twine &path) {
Michael J. Spencer112a7692010-12-01 06:03:50 +0000610 SmallString<128> path_storage;
611 StringRef p = path.toStringRef(path_storage);
612
Michael J. Spencerf616b212010-12-07 17:04:04 +0000613 return !root_directory(p).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000614}
615
Michael J. Spencera68282c2010-12-07 18:12:07 +0000616bool has_root_path(const Twine &path) {
Michael J. Spencer112a7692010-12-01 06:03:50 +0000617 SmallString<128> path_storage;
618 StringRef p = path.toStringRef(path_storage);
619
Michael J. Spencerf616b212010-12-07 17:04:04 +0000620 return !root_path(p).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000621}
622
Michael J. Spencer6d4b7e72010-12-20 13:30:28 +0000623bool has_relative_path(const Twine &path) {
624 SmallString<128> path_storage;
625 StringRef p = path.toStringRef(path_storage);
626
627 return !relative_path(p).empty();
628}
629
Michael J. Spencera68282c2010-12-07 18:12:07 +0000630bool has_filename(const Twine &path) {
Michael J. Spencer112a7692010-12-01 06:03:50 +0000631 SmallString<128> path_storage;
632 StringRef p = path.toStringRef(path_storage);
633
Michael J. Spencerf616b212010-12-07 17:04:04 +0000634 return !filename(p).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000635}
636
Michael J. Spencera68282c2010-12-07 18:12:07 +0000637bool has_parent_path(const Twine &path) {
Michael J. Spencer112a7692010-12-01 06:03:50 +0000638 SmallString<128> path_storage;
639 StringRef p = path.toStringRef(path_storage);
640
Michael J. Spencerf616b212010-12-07 17:04:04 +0000641 return !parent_path(p).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000642}
643
Michael J. Spencera68282c2010-12-07 18:12:07 +0000644bool has_stem(const Twine &path) {
Michael J. Spencer112a7692010-12-01 06:03:50 +0000645 SmallString<128> path_storage;
646 StringRef p = path.toStringRef(path_storage);
647
Michael J. Spencerf616b212010-12-07 17:04:04 +0000648 return !stem(p).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000649}
650
Michael J. Spencera68282c2010-12-07 18:12:07 +0000651bool has_extension(const Twine &path) {
Michael J. Spencer112a7692010-12-01 06:03:50 +0000652 SmallString<128> path_storage;
653 StringRef p = path.toStringRef(path_storage);
654
Michael J. Spencerf616b212010-12-07 17:04:04 +0000655 return !extension(p).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000656}
657
Michael J. Spencera68282c2010-12-07 18:12:07 +0000658bool is_absolute(const Twine &path) {
Michael J. Spencera72df5f2010-12-01 06:21:53 +0000659 SmallString<128> path_storage;
660 StringRef p = path.toStringRef(path_storage);
661
Michael J. Spencerf616b212010-12-07 17:04:04 +0000662 bool rootDir = has_root_directory(p),
Michael J. Spencera72df5f2010-12-01 06:21:53 +0000663#ifdef LLVM_ON_WIN32
Michael J. Spencerf616b212010-12-07 17:04:04 +0000664 rootName = has_root_name(p);
Michael J. Spencera72df5f2010-12-01 06:21:53 +0000665#else
Michael J. Spencerf616b212010-12-07 17:04:04 +0000666 rootName = true;
Michael J. Spencera72df5f2010-12-01 06:21:53 +0000667#endif
668
Michael J. Spencerf616b212010-12-07 17:04:04 +0000669 return rootDir && rootName;
Michael J. Spencera72df5f2010-12-01 06:21:53 +0000670}
671
Michael J. Spencera68282c2010-12-07 18:12:07 +0000672bool is_relative(const Twine &path) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000673 return !is_absolute(path);
Michael J. Spencera72df5f2010-12-01 06:21:53 +0000674}
675
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +0000676} // end namespace path
677
678namespace fs {
679
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000680std::error_code getUniqueID(const Twine Path, UniqueID &Result) {
Rafael Espindola7f822a92013-07-29 21:26:49 +0000681 file_status Status;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000682 std::error_code EC = status(Path, Status);
Rafael Espindola7f822a92013-07-29 21:26:49 +0000683 if (EC)
684 return EC;
685 Result = Status.getUniqueID();
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000686 return std::error_code();
Rafael Espindola7f822a92013-07-29 21:26:49 +0000687}
688
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000689std::error_code createUniqueFile(const Twine &Model, int &ResultFd,
690 SmallVectorImpl<char> &ResultPath,
691 unsigned Mode) {
Rafael Espindolac9d2e5b2013-07-05 21:01:08 +0000692 return createUniqueEntity(Model, ResultFd, ResultPath, false, Mode, FS_File);
693}
694
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000695std::error_code createUniqueFile(const Twine &Model,
696 SmallVectorImpl<char> &ResultPath) {
Rafael Espindolac9d2e5b2013-07-05 21:01:08 +0000697 int Dummy;
698 return createUniqueEntity(Model, Dummy, ResultPath, false, 0, FS_Name);
699}
700
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000701static std::error_code
702createTemporaryFile(const Twine &Model, int &ResultFD,
703 llvm::SmallVectorImpl<char> &ResultPath, FSEntity Type) {
Rafael Espindola325fa0f2013-07-05 19:56:49 +0000704 SmallString<128> Storage;
705 StringRef P = Model.toNullTerminatedStringRef(Storage);
706 assert(P.find_first_of(separators) == StringRef::npos &&
707 "Model must be a simple filename.");
708 // Use P.begin() so that createUniqueEntity doesn't need to recreate Storage.
709 return createUniqueEntity(P.begin(), ResultFD, ResultPath,
710 true, owner_read | owner_write, Type);
711}
712
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000713static std::error_code
Rafael Espindola325fa0f2013-07-05 19:56:49 +0000714createTemporaryFile(const Twine &Prefix, StringRef Suffix, int &ResultFD,
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000715 llvm::SmallVectorImpl<char> &ResultPath, FSEntity Type) {
Rafael Espindolad3c89042013-07-25 15:00:17 +0000716 const char *Middle = Suffix.empty() ? "-%%%%%%" : "-%%%%%%.";
717 return createTemporaryFile(Prefix + Middle + Suffix, ResultFD, ResultPath,
Rafael Espindola325fa0f2013-07-05 19:56:49 +0000718 Type);
719}
720
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000721std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
722 int &ResultFD,
723 SmallVectorImpl<char> &ResultPath) {
Rafael Espindola325fa0f2013-07-05 19:56:49 +0000724 return createTemporaryFile(Prefix, Suffix, ResultFD, ResultPath, FS_File);
725}
726
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000727std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
728 SmallVectorImpl<char> &ResultPath) {
Rafael Espindola325fa0f2013-07-05 19:56:49 +0000729 int Dummy;
730 return createTemporaryFile(Prefix, Suffix, Dummy, ResultPath, FS_Name);
731}
732
733
Rafael Espindolae79a8722013-06-28 03:48:47 +0000734// This is a mkdtemp with a different pattern. We use createUniqueEntity mostly
Rafael Espindola31a24432013-06-28 10:55:41 +0000735// for consistency. We should try using mkdtemp.
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000736std::error_code createUniqueDirectory(const Twine &Prefix,
737 SmallVectorImpl<char> &ResultPath) {
Rafael Espindolae79a8722013-06-28 03:48:47 +0000738 int Dummy;
739 return createUniqueEntity(Prefix + "-%%%%%%", Dummy, ResultPath,
740 true, 0, FS_Dir);
Rafael Espindola7ffacc42013-06-27 03:45:31 +0000741}
742
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000743std::error_code make_absolute(SmallVectorImpl<char> &path) {
Michael J. Spencer92903a32010-12-07 03:57:17 +0000744 StringRef p(path.data(), path.size());
745
Daniel Dunbarb23158c2012-02-29 00:20:37 +0000746 bool rootDirectory = path::has_root_directory(p),
747#ifdef LLVM_ON_WIN32
Daniel Dunbar39ea4582012-02-29 00:46:46 +0000748 rootName = path::has_root_name(p);
Daniel Dunbarb23158c2012-02-29 00:20:37 +0000749#else
750 rootName = true;
751#endif
Michael J. Spencer92903a32010-12-07 03:57:17 +0000752
753 // Already absolute.
754 if (rootName && rootDirectory)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000755 return std::error_code();
Michael J. Spencer92903a32010-12-07 03:57:17 +0000756
757 // All of the following conditions will need the current directory.
758 SmallString<128> current_dir;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000759 if (std::error_code ec = current_path(current_dir))
760 return ec;
Michael J. Spencer92903a32010-12-07 03:57:17 +0000761
762 // Relative path. Prepend the current directory.
763 if (!rootName && !rootDirectory) {
764 // Append path to the current directory.
Michael J. Spencer1e090f02010-12-07 03:57:37 +0000765 path::append(current_dir, p);
Michael J. Spencer92903a32010-12-07 03:57:17 +0000766 // Set path to the result.
767 path.swap(current_dir);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000768 return std::error_code();
Michael J. Spencer92903a32010-12-07 03:57:17 +0000769 }
770
771 if (!rootName && rootDirectory) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000772 StringRef cdrn = path::root_name(current_dir);
Michael J. Spencer92903a32010-12-07 03:57:17 +0000773 SmallString<128> curDirRootName(cdrn.begin(), cdrn.end());
Michael J. Spencer1e090f02010-12-07 03:57:37 +0000774 path::append(curDirRootName, p);
Michael J. Spencer92903a32010-12-07 03:57:17 +0000775 // Set path to the result.
776 path.swap(curDirRootName);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000777 return std::error_code();
Michael J. Spencer92903a32010-12-07 03:57:17 +0000778 }
779
780 if (rootName && !rootDirectory) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000781 StringRef pRootName = path::root_name(p);
782 StringRef bRootDirectory = path::root_directory(current_dir);
783 StringRef bRelativePath = path::relative_path(current_dir);
784 StringRef pRelativePath = path::relative_path(p);
Michael J. Spencer92903a32010-12-07 03:57:17 +0000785
786 SmallString<128> res;
Michael J. Spencer1e090f02010-12-07 03:57:37 +0000787 path::append(res, pRootName, bRootDirectory, bRelativePath, pRelativePath);
Michael J. Spencer92903a32010-12-07 03:57:17 +0000788 path.swap(res);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000789 return std::error_code();
Michael J. Spencer92903a32010-12-07 03:57:17 +0000790 }
791
792 llvm_unreachable("All rootName and rootDirectory combinations should have "
793 "occurred above!");
794}
795
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000796std::error_code create_directories(const Twine &Path, bool IgnoreExisting) {
Rafael Espindolab6f72b22014-02-13 16:58:19 +0000797 SmallString<128> PathStorage;
798 StringRef P = Path.toStringRef(PathStorage);
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000799
Rafael Espindolab6f72b22014-02-13 16:58:19 +0000800 // Be optimistic and try to create the directory
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000801 std::error_code EC = create_directory(P, IgnoreExisting);
Rafael Espindolab6f72b22014-02-13 16:58:19 +0000802 // If we succeeded, or had any error other than the parent not existing, just
803 // return it.
Rafael Espindola2a826e42014-06-13 17:20:48 +0000804 if (EC != errc::no_such_file_or_directory)
Rafael Espindolab6f72b22014-02-13 16:58:19 +0000805 return EC;
Michael J. Spencerf616b212010-12-07 17:04:04 +0000806
Rafael Espindolab6f72b22014-02-13 16:58:19 +0000807 // We failed because of a no_such_file_or_directory, try to create the
808 // parent.
809 StringRef Parent = path::parent_path(P);
810 if (Parent.empty())
811 return EC;
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000812
Rafael Espindolab6f72b22014-02-13 16:58:19 +0000813 if ((EC = create_directories(Parent)))
814 return EC;
815
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000816 return create_directory(P, IgnoreExisting);
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000817}
818
Justin Bognercd45f962014-06-19 19:35:39 +0000819std::error_code copy_file(const Twine &From, const Twine &To) {
820 int ReadFD, WriteFD;
821 if (std::error_code EC = openFileForRead(From, ReadFD))
822 return EC;
823 if (std::error_code EC = openFileForWrite(To, WriteFD, F_None)) {
824 close(ReadFD);
825 return EC;
826 }
827
828 const size_t BufSize = 4096;
Dylan Noblesmith42836d92014-08-26 02:03:30 +0000829 char *Buf = new char[BufSize];
Justin Bognercd45f962014-06-19 19:35:39 +0000830 int BytesRead = 0, BytesWritten = 0;
831 for (;;) {
832 BytesRead = read(ReadFD, Buf, BufSize);
833 if (BytesRead <= 0)
834 break;
835 while (BytesRead) {
836 BytesWritten = write(WriteFD, Buf, BytesRead);
837 if (BytesWritten < 0)
838 break;
839 BytesRead -= BytesWritten;
840 }
841 if (BytesWritten < 0)
842 break;
843 }
844 close(ReadFD);
845 close(WriteFD);
Dylan Noblesmith42836d92014-08-26 02:03:30 +0000846 delete[] Buf;
Justin Bognercd45f962014-06-19 19:35:39 +0000847
848 if (BytesRead < 0 || BytesWritten < 0)
849 return std::error_code(errno, std::generic_category());
850 return std::error_code();
851}
852
Michael J. Spencer730f51a2010-12-09 17:37:02 +0000853bool exists(file_status status) {
854 return status_known(status) && status.type() != file_type::file_not_found;
855}
856
857bool status_known(file_status s) {
858 return s.type() != file_type::status_error;
859}
860
861bool is_directory(file_status status) {
862 return status.type() == file_type::directory_file;
863}
864
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000865std::error_code is_directory(const Twine &path, bool &result) {
Michael J. Spencer0d771ed2011-01-11 01:21:55 +0000866 file_status st;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000867 if (std::error_code ec = status(path, st))
Michael J. Spencer0d771ed2011-01-11 01:21:55 +0000868 return ec;
869 result = is_directory(st);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000870 return std::error_code();
Michael J. Spencer0d771ed2011-01-11 01:21:55 +0000871}
872
Michael J. Spencer730f51a2010-12-09 17:37:02 +0000873bool is_regular_file(file_status status) {
874 return status.type() == file_type::regular_file;
875}
876
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000877std::error_code is_regular_file(const Twine &path, bool &result) {
Michael J. Spencer0d771ed2011-01-11 01:21:55 +0000878 file_status st;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000879 if (std::error_code ec = status(path, st))
Michael J. Spencer0d771ed2011-01-11 01:21:55 +0000880 return ec;
881 result = is_regular_file(st);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000882 return std::error_code();
Michael J. Spencer0d771ed2011-01-11 01:21:55 +0000883}
884
Michael J. Spencer730f51a2010-12-09 17:37:02 +0000885bool is_other(file_status status) {
886 return exists(status) &&
887 !is_regular_file(status) &&
Rafael Espindola20063062014-03-20 17:39:04 +0000888 !is_directory(status);
Michael J. Spencer730f51a2010-12-09 17:37:02 +0000889}
890
Benjamin Kramer91ead3c2011-09-14 01:14:36 +0000891void directory_entry::replace_filename(const Twine &filename, file_status st) {
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000892 SmallString<128> path(Path.begin(), Path.end());
893 path::remove_filename(path);
894 path::append(path, filename);
895 Path = path.str();
896 Status = st;
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000897}
898
Michael J. Spencer4f8a8322011-12-13 23:17:12 +0000899/// @brief Identify the magic in magic.
Logan Chienc0f691d2014-06-25 13:46:17 +0000900file_magic identify_magic(StringRef Magic) {
Rafael Espindola9b404292013-06-11 17:22:12 +0000901 if (Magic.size() < 4)
Michael J. Spencer96ebd912012-06-19 05:29:57 +0000902 return file_magic::unknown;
Rafael Espindola9b404292013-06-11 17:22:12 +0000903 switch ((unsigned char)Magic[0]) {
Rui Ueyamafc149a62013-10-15 22:45:38 +0000904 case 0x00: {
Rui Ueyama2acb0582014-09-11 21:09:57 +0000905 // COFF bigobj or short import library file
Rui Ueyamae448f9e2013-11-15 21:22:02 +0000906 if (Magic[1] == (char)0x00 && Magic[2] == (char)0xff &&
Rui Ueyama2acb0582014-09-11 21:09:57 +0000907 Magic[3] == (char)0xff) {
Rui Ueyama5c69ff52014-09-11 22:34:32 +0000908 size_t MinSize = offsetof(COFF::BigObjHeader, UUID) + sizeof(COFF::BigObjMagic);
909 if (Magic.size() < MinSize)
910 return file_magic::coff_import_library;
911
912 int BigObjVersion = *reinterpret_cast<const support::ulittle16_t*>(
913 Magic.data() + offsetof(COFF::BigObjHeader, Version));
914 if (BigObjVersion < COFF::BigObjHeader::MinBigObjectVersion)
915 return file_magic::coff_import_library;
916
917 const char *Start = Magic.data() + offsetof(COFF::BigObjHeader, UUID);
918 if (memcmp(Start, COFF::BigObjMagic, sizeof(COFF::BigObjMagic)) != 0)
919 return file_magic::coff_import_library;
920 return file_magic::coff_object;
Rui Ueyama2acb0582014-09-11 21:09:57 +0000921 }
Rui Ueyamafc149a62013-10-15 22:45:38 +0000922 // Windows resource file
Rui Ueyama50a86e12013-10-16 03:29:49 +0000923 const char Expected[] = { 0, 0, 0, 0, '\x20', 0, 0, 0, '\xff' };
Rui Ueyamafc149a62013-10-15 22:45:38 +0000924 if (Magic.size() >= sizeof(Expected) &&
925 memcmp(Magic.data(), Expected, sizeof(Expected)) == 0)
926 return file_magic::windows_resource;
Rui Ueyama829c4392013-11-14 22:09:08 +0000927 // 0x0000 = COFF unknown machine type
928 if (Magic[1] == 0)
929 return file_magic::coff_object;
Rui Ueyamafc149a62013-10-15 22:45:38 +0000930 break;
931 }
Michael J. Spencer4f8a8322011-12-13 23:17:12 +0000932 case 0xDE: // 0x0B17C0DE = BC wraper
Rafael Espindola9b404292013-06-11 17:22:12 +0000933 if (Magic[1] == (char)0xC0 && Magic[2] == (char)0x17 &&
934 Magic[3] == (char)0x0B)
Michael J. Spencer4f8a8322011-12-13 23:17:12 +0000935 return file_magic::bitcode;
936 break;
937 case 'B':
Rafael Espindola9b404292013-06-11 17:22:12 +0000938 if (Magic[1] == 'C' && Magic[2] == (char)0xC0 && Magic[3] == (char)0xDE)
Michael J. Spencer4f8a8322011-12-13 23:17:12 +0000939 return file_magic::bitcode;
940 break;
941 case '!':
Rafael Espindola9b404292013-06-11 17:22:12 +0000942 if (Magic.size() >= 8)
943 if (memcmp(Magic.data(),"!<arch>\n",8) == 0)
Michael J. Spencer4f8a8322011-12-13 23:17:12 +0000944 return file_magic::archive;
945 break;
946
947 case '\177':
Rafael Espindola823de7c2013-06-11 17:25:45 +0000948 if (Magic.size() >= 18 && Magic[1] == 'E' && Magic[2] == 'L' &&
949 Magic[3] == 'F') {
Rafael Espindola9b404292013-06-11 17:22:12 +0000950 bool Data2MSB = Magic[5] == 2;
Michael J. Spencerb8055cb2013-04-05 20:10:04 +0000951 unsigned high = Data2MSB ? 16 : 17;
952 unsigned low = Data2MSB ? 17 : 16;
Rafael Espindola823de7c2013-06-11 17:25:45 +0000953 if (Magic[high] == 0)
Rafael Espindola9b404292013-06-11 17:22:12 +0000954 switch (Magic[low]) {
Michael J. Spencer4f8a8322011-12-13 23:17:12 +0000955 default: break;
956 case 1: return file_magic::elf_relocatable;
957 case 2: return file_magic::elf_executable;
958 case 3: return file_magic::elf_shared_object;
959 case 4: return file_magic::elf_core;
960 }
961 }
962 break;
963
964 case 0xCA:
Rafael Espindola9b404292013-06-11 17:22:12 +0000965 if (Magic[1] == char(0xFE) && Magic[2] == char(0xBA) &&
966 Magic[3] == char(0xBE)) {
Michael J. Spencer4f8a8322011-12-13 23:17:12 +0000967 // This is complicated by an overlap with Java class files.
968 // See the Mach-O section in /usr/share/file/magic for details.
Rafael Espindola9b404292013-06-11 17:22:12 +0000969 if (Magic.size() >= 8 && Magic[7] < 43)
Alexey Samsonove6388e62013-06-18 15:03:28 +0000970 return file_magic::macho_universal_binary;
Michael J. Spencer4f8a8322011-12-13 23:17:12 +0000971 }
972 break;
973
974 // The two magic numbers for mach-o are:
975 // 0xfeedface - 32-bit mach-o
976 // 0xfeedfacf - 64-bit mach-o
977 case 0xFE:
978 case 0xCE:
979 case 0xCF: {
980 uint16_t type = 0;
Rafael Espindola9b404292013-06-11 17:22:12 +0000981 if (Magic[0] == char(0xFE) && Magic[1] == char(0xED) &&
982 Magic[2] == char(0xFA) &&
983 (Magic[3] == char(0xCE) || Magic[3] == char(0xCF))) {
Michael J. Spencer4f8a8322011-12-13 23:17:12 +0000984 /* Native endian */
Rafael Espindola9b404292013-06-11 17:22:12 +0000985 if (Magic.size() >= 16) type = Magic[14] << 8 | Magic[15];
986 } else if ((Magic[0] == char(0xCE) || Magic[0] == char(0xCF)) &&
987 Magic[1] == char(0xFA) && Magic[2] == char(0xED) &&
988 Magic[3] == char(0xFE)) {
Michael J. Spencer4f8a8322011-12-13 23:17:12 +0000989 /* Reverse endian */
Rafael Espindola9b404292013-06-11 17:22:12 +0000990 if (Magic.size() >= 14) type = Magic[13] << 8 | Magic[12];
Michael J. Spencer4f8a8322011-12-13 23:17:12 +0000991 }
992 switch (type) {
993 default: break;
994 case 1: return file_magic::macho_object;
995 case 2: return file_magic::macho_executable;
996 case 3: return file_magic::macho_fixed_virtual_memory_shared_lib;
997 case 4: return file_magic::macho_core;
Rafael Espindola134cc992013-06-10 20:32:27 +0000998 case 5: return file_magic::macho_preload_executable;
Michael J. Spencer4f8a8322011-12-13 23:17:12 +0000999 case 6: return file_magic::macho_dynamically_linked_shared_lib;
1000 case 7: return file_magic::macho_dynamic_linker;
1001 case 8: return file_magic::macho_bundle;
1002 case 9: return file_magic::macho_dynamic_linker;
1003 case 10: return file_magic::macho_dsym_companion;
1004 }
1005 break;
1006 }
1007 case 0xF0: // PowerPC Windows
1008 case 0x83: // Alpha 32-bit
1009 case 0x84: // Alpha 64-bit
1010 case 0x66: // MPS R4000 Windows
1011 case 0x50: // mc68K
1012 case 0x4c: // 80386 Windows
Saleem Abdulrasool9b7c0af2014-03-13 07:02:35 +00001013 case 0xc4: // ARMNT Windows
Rafael Espindola9b404292013-06-11 17:22:12 +00001014 if (Magic[1] == 0x01)
Michael J. Spencer4f8a8322011-12-13 23:17:12 +00001015 return file_magic::coff_object;
1016
1017 case 0x90: // PA-RISC Windows
1018 case 0x68: // mc68K Windows
Rafael Espindola9b404292013-06-11 17:22:12 +00001019 if (Magic[1] == 0x02)
Michael J. Spencer4f8a8322011-12-13 23:17:12 +00001020 return file_magic::coff_object;
1021 break;
1022
1023 case 0x4d: // Possible MS-DOS stub on Windows PE file
Rafael Espindola9b404292013-06-11 17:22:12 +00001024 if (Magic[1] == 0x5a) {
Michael J. Spencer4f8a8322011-12-13 23:17:12 +00001025 uint32_t off =
Rafael Espindola9b404292013-06-11 17:22:12 +00001026 *reinterpret_cast<const support::ulittle32_t*>(Magic.data() + 0x3c);
Michael J. Spencer4f8a8322011-12-13 23:17:12 +00001027 // PE/COFF file, either EXE or DLL.
Rafael Espindola9b404292013-06-11 17:22:12 +00001028 if (off < Magic.size() && memcmp(Magic.data() + off, "PE\0\0",4) == 0)
Michael J. Spencer4f8a8322011-12-13 23:17:12 +00001029 return file_magic::pecoff_executable;
1030 }
1031 break;
1032
1033 case 0x64: // x86-64 Windows.
Rafael Espindola9b404292013-06-11 17:22:12 +00001034 if (Magic[1] == char(0x86))
Michael J. Spencer4f8a8322011-12-13 23:17:12 +00001035 return file_magic::coff_object;
1036 break;
1037
1038 default:
1039 break;
1040 }
1041 return file_magic::unknown;
1042}
1043
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001044std::error_code identify_magic(const Twine &Path, file_magic &Result) {
Rafael Espindolada70bfd2014-06-11 22:53:00 +00001045 int FD;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001046 if (std::error_code EC = openFileForRead(Path, FD))
Rafael Espindolada70bfd2014-06-11 22:53:00 +00001047 return EC;
Michael J. Spencer94b2ab32011-01-15 20:39:36 +00001048
Rafael Espindolada70bfd2014-06-11 22:53:00 +00001049 char Buffer[32];
1050 int Length = read(FD, Buffer, sizeof(Buffer));
Rafael Espindolaa8acef62014-06-25 14:35:59 +00001051 if (close(FD) != 0 || Length < 0)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001052 return std::error_code(errno, std::generic_category());
Rafael Espindolada70bfd2014-06-11 22:53:00 +00001053
1054 Result = identify_magic(StringRef(Buffer, Length));
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001055 return std::error_code();
Michael J. Spencer94b2ab32011-01-15 20:39:36 +00001056}
1057
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001058std::error_code directory_entry::status(file_status &result) const {
Michael J. Spencerf8dc1862011-01-05 16:39:13 +00001059 return fs::status(Path, result);
1060}
1061
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +00001062} // end namespace fs
1063} // end namespace sys
1064} // end namespace llvm
Michael J. Spencerebad2f92010-11-29 22:28:51 +00001065
1066// Include the truly platform-specific parts.
1067#if defined(LLVM_ON_UNIX)
Rafael Espindolaf1fc3822013-06-26 19:33:03 +00001068#include "Unix/Path.inc"
Michael J. Spencerebad2f92010-11-29 22:28:51 +00001069#endif
1070#if defined(LLVM_ON_WIN32)
Rafael Espindolaf1fc3822013-06-26 19:33:03 +00001071#include "Windows/Path.inc"
Michael J. Spencerebad2f92010-11-29 22:28:51 +00001072#endif