blob: 535394c5b3ba1136b3845b736941233d4b1d8373 [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
167// Implemented in Unix/Path.inc and Windows/Path.inc.
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000168static std::error_code TempDir(SmallVectorImpl<char> &result);
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000169
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000170static std::error_code createUniqueEntity(const Twine &Model, int &ResultFD,
171 SmallVectorImpl<char> &ResultPath,
172 bool MakeAbsolute, unsigned Mode,
173 FSEntity Type) {
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000174 SmallString<128> ModelStorage;
175 Model.toVector(ModelStorage);
176
177 if (MakeAbsolute) {
178 // Make model absolute by prepending a temp directory if it's not already.
179 if (!sys::path::is_absolute(Twine(ModelStorage))) {
180 SmallString<128> TDir;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000181 if (std::error_code EC = TempDir(TDir))
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000182 return EC;
183 sys::path::append(TDir, Twine(ModelStorage));
184 ModelStorage.swap(TDir);
185 }
186 }
187
188 // From here on, DO NOT modify model. It may be needed if the randomly chosen
189 // path already exists.
190 ResultPath = ModelStorage;
191 // Null terminate.
192 ResultPath.push_back(0);
193 ResultPath.pop_back();
194
195retry_random_path:
196 // Replace '%' with random chars.
197 for (unsigned i = 0, e = ModelStorage.size(); i != e; ++i) {
198 if (ModelStorage[i] == '%')
199 ResultPath[i] = "0123456789abcdef"[sys::Process::GetRandomNumber() & 15];
200 }
201
202 // Try to open + create the file.
203 switch (Type) {
204 case FS_File: {
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000205 if (std::error_code EC =
Rafael Espindola90c7f1c2014-02-24 18:20:12 +0000206 sys::fs::openFileForWrite(Twine(ResultPath.begin()), ResultFD,
207 sys::fs::F_RW | sys::fs::F_Excl, Mode)) {
Rafael Espindola2a826e42014-06-13 17:20:48 +0000208 if (EC == errc::file_exists)
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000209 goto retry_random_path;
210 return EC;
211 }
212
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000213 return std::error_code();
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000214 }
215
216 case FS_Name: {
217 bool Exists;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000218 std::error_code EC = sys::fs::exists(ResultPath.begin(), Exists);
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000219 if (EC)
220 return EC;
221 if (Exists)
222 goto retry_random_path;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000223 return std::error_code();
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000224 }
225
226 case FS_Dir: {
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000227 if (std::error_code EC =
228 sys::fs::create_directory(ResultPath.begin(), false)) {
Rafael Espindola2a826e42014-06-13 17:20:48 +0000229 if (EC == errc::file_exists)
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000230 goto retry_random_path;
231 return EC;
232 }
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000233 return std::error_code();
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000234 }
235 }
236 llvm_unreachable("Invalid Type");
237}
Rafael Espindolae79a8722013-06-28 03:48:47 +0000238
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000239namespace llvm {
240namespace sys {
241namespace path {
242
Benjamin Kramer292b44b2010-12-17 18:19:06 +0000243const_iterator begin(StringRef path) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000244 const_iterator i;
245 i.Path = path;
246 i.Component = find_first_component(path);
247 i.Position = 0;
248 return i;
249}
250
Benjamin Kramer292b44b2010-12-17 18:19:06 +0000251const_iterator end(StringRef path) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000252 const_iterator i;
253 i.Path = path;
254 i.Position = path.size();
255 return i;
256}
257
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000258const_iterator &const_iterator::operator++() {
259 assert(Position < Path.size() && "Tried to increment past end!");
260
261 // Increment Position to past the current component
262 Position += Component.size();
263
264 // Check for end.
265 if (Position == Path.size()) {
266 Component = StringRef();
267 return *this;
268 }
269
270 // Both POSIX and Windows treat paths that begin with exactly two separators
271 // specially.
272 bool was_net = Component.size() > 2 &&
273 is_separator(Component[0]) &&
274 Component[1] == Component[0] &&
275 !is_separator(Component[2]);
276
277 // Handle separators.
278 if (is_separator(Path[Position])) {
279 // Root dir.
280 if (was_net
281#ifdef LLVM_ON_WIN32
282 // c:/
283 || Component.endswith(":")
284#endif
285 ) {
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000286 Component = Path.substr(Position, 1);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000287 return *this;
288 }
289
290 // Skip extra separators.
291 while (Position != Path.size() &&
292 is_separator(Path[Position])) {
293 ++Position;
294 }
295
296 // Treat trailing '/' as a '.'.
297 if (Position == Path.size()) {
298 --Position;
299 Component = ".";
300 return *this;
301 }
302 }
303
304 // Find next component.
305 size_t end_pos = Path.find_first_of(separators, Position);
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000306 Component = Path.slice(Position, end_pos);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000307
308 return *this;
309}
310
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000311const_iterator &const_iterator::operator--() {
Ben Langmuir8d116392014-03-05 19:56:30 +0000312 // If we're at the end and the previous char was a '/', return '.' unless
313 // we are the root path.
314 size_t root_dir_pos = root_dir_start(Path);
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000315 if (Position == Path.size() &&
Ben Langmuir8d116392014-03-05 19:56:30 +0000316 Path.size() > root_dir_pos + 1 &&
317 is_separator(Path[Position - 1])) {
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000318 --Position;
319 Component = ".";
320 return *this;
321 }
322
323 // Skip separators unless it's the root directory.
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000324 size_t end_pos = Position;
325
326 while(end_pos > 0 &&
327 (end_pos - 1) != root_dir_pos &&
328 is_separator(Path[end_pos - 1]))
329 --end_pos;
330
331 // Find next separator.
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000332 size_t start_pos = filename_pos(Path.substr(0, end_pos));
333 Component = Path.slice(start_pos, end_pos);
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000334 Position = start_pos;
335 return *this;
336}
337
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000338bool const_iterator::operator==(const const_iterator &RHS) const {
339 return Path.begin() == RHS.Path.begin() &&
340 Position == RHS.Position;
341}
342
343bool const_iterator::operator!=(const const_iterator &RHS) const {
344 return !(*this == RHS);
345}
346
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000347ptrdiff_t const_iterator::operator-(const const_iterator &RHS) const {
348 return Position - RHS.Position;
349}
350
Benjamin Kramer292b44b2010-12-17 18:19:06 +0000351const StringRef root_path(StringRef path) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000352 const_iterator b = begin(path),
353 pos = b,
354 e = end(path);
355 if (b != e) {
356 bool has_net = b->size() > 2 && is_separator((*b)[0]) && (*b)[1] == (*b)[0];
357 bool has_drive =
358#ifdef LLVM_ON_WIN32
359 b->endswith(":");
360#else
361 false;
362#endif
363
364 if (has_net || has_drive) {
365 if ((++pos != e) && is_separator((*pos)[0])) {
366 // {C:/,//net/}, so get the first two components.
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000367 return path.substr(0, b->size() + pos->size());
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000368 } else {
369 // just {C:,//net}, return the first component.
Michael J. Spencerf616b212010-12-07 17:04:04 +0000370 return *b;
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000371 }
372 }
373
374 // POSIX style root directory.
375 if (is_separator((*b)[0])) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000376 return *b;
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000377 }
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000378 }
379
Michael J. Spencerf616b212010-12-07 17:04:04 +0000380 return StringRef();
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000381}
382
Benjamin Kramer292b44b2010-12-17 18:19:06 +0000383const StringRef root_name(StringRef path) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000384 const_iterator b = begin(path),
385 e = end(path);
386 if (b != e) {
387 bool has_net = b->size() > 2 && is_separator((*b)[0]) && (*b)[1] == (*b)[0];
388 bool has_drive =
389#ifdef LLVM_ON_WIN32
390 b->endswith(":");
391#else
392 false;
393#endif
394
395 if (has_net || has_drive) {
396 // just {C:,//net}, return the first component.
Michael J. Spencerf616b212010-12-07 17:04:04 +0000397 return *b;
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000398 }
399 }
400
401 // No path or no name.
Michael J. Spencerf616b212010-12-07 17:04:04 +0000402 return StringRef();
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000403}
404
Benjamin Kramer292b44b2010-12-17 18:19:06 +0000405const StringRef root_directory(StringRef path) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000406 const_iterator b = begin(path),
407 pos = b,
408 e = end(path);
409 if (b != e) {
410 bool has_net = b->size() > 2 && is_separator((*b)[0]) && (*b)[1] == (*b)[0];
411 bool has_drive =
412#ifdef LLVM_ON_WIN32
413 b->endswith(":");
414#else
415 false;
416#endif
417
418 if ((has_net || has_drive) &&
419 // {C:,//net}, skip to the next component.
420 (++pos != e) && is_separator((*pos)[0])) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000421 return *pos;
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000422 }
423
424 // POSIX style root directory.
425 if (!has_net && is_separator((*b)[0])) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000426 return *b;
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000427 }
428 }
429
430 // No path or no root.
Michael J. Spencerf616b212010-12-07 17:04:04 +0000431 return StringRef();
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000432}
433
Benjamin Kramer292b44b2010-12-17 18:19:06 +0000434const StringRef relative_path(StringRef path) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000435 StringRef root = root_path(path);
Michael J. Spencere6462392012-02-29 00:06:24 +0000436 return path.substr(root.size());
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000437}
438
Michael J. Spencer1e090f02010-12-07 03:57:37 +0000439void append(SmallVectorImpl<char> &path, const Twine &a,
440 const Twine &b,
441 const Twine &c,
442 const Twine &d) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000443 SmallString<32> a_storage;
444 SmallString<32> b_storage;
445 SmallString<32> c_storage;
446 SmallString<32> d_storage;
447
448 SmallVector<StringRef, 4> components;
449 if (!a.isTriviallyEmpty()) components.push_back(a.toStringRef(a_storage));
450 if (!b.isTriviallyEmpty()) components.push_back(b.toStringRef(b_storage));
451 if (!c.isTriviallyEmpty()) components.push_back(c.toStringRef(c_storage));
452 if (!d.isTriviallyEmpty()) components.push_back(d.toStringRef(d_storage));
453
454 for (SmallVectorImpl<StringRef>::const_iterator i = components.begin(),
455 e = components.end();
456 i != e; ++i) {
457 bool path_has_sep = !path.empty() && is_separator(path[path.size() - 1]);
458 bool component_has_sep = !i->empty() && is_separator((*i)[0]);
Michael J. Spencerf616b212010-12-07 17:04:04 +0000459 bool is_root_name = has_root_name(*i);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000460
461 if (path_has_sep) {
462 // Strip separators from beginning of component.
463 size_t loc = i->find_first_not_of(separators);
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000464 StringRef c = i->substr(loc);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000465
466 // Append it.
467 path.append(c.begin(), c.end());
468 continue;
469 }
470
Michael J. Spencer95e4ac12010-12-06 04:28:23 +0000471 if (!component_has_sep && !(path.empty() || is_root_name)) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000472 // Add a separator.
Alp Tokercb402912014-01-24 17:20:08 +0000473 path.push_back(preferred_separator);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000474 }
475
476 path.append(i->begin(), i->end());
477 }
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000478}
479
Argyrios Kyrtzidisa61736f2011-02-15 17:51:19 +0000480void append(SmallVectorImpl<char> &path,
481 const_iterator begin, const_iterator end) {
482 for (; begin != end; ++begin)
483 path::append(path, *begin);
484}
485
Benjamin Kramer292b44b2010-12-17 18:19:06 +0000486const StringRef parent_path(StringRef path) {
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000487 size_t end_pos = parent_path_end(path);
488 if (end_pos == StringRef::npos)
Michael J. Spencerf616b212010-12-07 17:04:04 +0000489 return StringRef();
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000490 else
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000491 return path.substr(0, end_pos);
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000492}
493
Michael J. Spencer1e090f02010-12-07 03:57:37 +0000494void remove_filename(SmallVectorImpl<char> &path) {
Michael J. Spencer9c594092010-12-01 00:52:28 +0000495 size_t end_pos = parent_path_end(StringRef(path.begin(), path.size()));
Michael J. Spencer1e090f02010-12-07 03:57:37 +0000496 if (end_pos != StringRef::npos)
497 path.set_size(end_pos);
Michael J. Spencer9c594092010-12-01 00:52:28 +0000498}
499
Michael J. Spencerf616b212010-12-07 17:04:04 +0000500void replace_extension(SmallVectorImpl<char> &path, const Twine &extension) {
Michael J. Spencerfb3a95d2010-12-01 00:52:55 +0000501 StringRef p(path.begin(), path.size());
502 SmallString<32> ext_storage;
503 StringRef ext = extension.toStringRef(ext_storage);
504
505 // Erase existing extension.
506 size_t pos = p.find_last_of('.');
507 if (pos != StringRef::npos && pos >= filename_pos(p))
508 path.set_size(pos);
509
510 // Append '.' if needed.
511 if (ext.size() > 0 && ext[0] != '.')
512 path.push_back('.');
513
514 // Append extension.
515 path.append(ext.begin(), ext.end());
Michael J. Spencerfb3a95d2010-12-01 00:52:55 +0000516}
517
Michael J. Spencer1e090f02010-12-07 03:57:37 +0000518void native(const Twine &path, SmallVectorImpl<char> &result) {
Benjamin Kramerbd4ac9b2013-09-11 10:45:21 +0000519 assert((!path.isSingleStringRef() ||
520 path.getSingleStringRef().data() != result.data()) &&
521 "path and result are not allowed to overlap!");
Michael J. Spencer80025002010-12-01 02:48:27 +0000522 // Clear result.
Michael J. Spencer98c7a112010-12-07 01:23:19 +0000523 result.clear();
Michael J. Spencer80025002010-12-01 02:48:27 +0000524 path.toVector(result);
Benjamin Kramerbd4ac9b2013-09-11 10:45:21 +0000525 native(result);
526}
527
528void native(SmallVectorImpl<char> &path) {
529#ifdef LLVM_ON_WIN32
530 std::replace(path.begin(), path.end(), '/', '\\');
Michael J. Spencer80025002010-12-01 02:48:27 +0000531#endif
Michael J. Spencer80025002010-12-01 02:48:27 +0000532}
533
Benjamin Kramer292b44b2010-12-17 18:19:06 +0000534const StringRef filename(StringRef path) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000535 return *(--end(path));
Michael J. Spencer14269202010-12-01 03:18:17 +0000536}
537
Benjamin Kramer292b44b2010-12-17 18:19:06 +0000538const StringRef stem(StringRef path) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000539 StringRef fname = filename(path);
Michael J. Spencer956955e2010-12-01 03:18:33 +0000540 size_t pos = fname.find_last_of('.');
541 if (pos == StringRef::npos)
Michael J. Spencerf616b212010-12-07 17:04:04 +0000542 return fname;
Michael J. Spencer956955e2010-12-01 03:18:33 +0000543 else
544 if ((fname.size() == 1 && fname == ".") ||
545 (fname.size() == 2 && fname == ".."))
Michael J. Spencerf616b212010-12-07 17:04:04 +0000546 return fname;
Michael J. Spencer956955e2010-12-01 03:18:33 +0000547 else
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000548 return fname.substr(0, pos);
Michael J. Spencer956955e2010-12-01 03:18:33 +0000549}
550
Benjamin Kramer292b44b2010-12-17 18:19:06 +0000551const StringRef extension(StringRef path) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000552 StringRef fname = filename(path);
Michael J. Spencer87106c52010-12-01 03:37:41 +0000553 size_t pos = fname.find_last_of('.');
554 if (pos == StringRef::npos)
Michael J. Spencerf616b212010-12-07 17:04:04 +0000555 return StringRef();
Michael J. Spencer87106c52010-12-01 03:37:41 +0000556 else
557 if ((fname.size() == 1 && fname == ".") ||
558 (fname.size() == 2 && fname == ".."))
Michael J. Spencerf616b212010-12-07 17:04:04 +0000559 return StringRef();
Michael J. Spencer87106c52010-12-01 03:37:41 +0000560 else
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000561 return fname.substr(pos);
Michael J. Spencer87106c52010-12-01 03:37:41 +0000562}
563
Zhanyong Wan606bb1a2011-02-11 21:24:40 +0000564bool is_separator(char value) {
565 switch(value) {
566#ifdef LLVM_ON_WIN32
567 case '\\': // fall through
568#endif
569 case '/': return true;
570 default: return false;
571 }
572}
573
Yaron Keren15217202014-05-16 13:16:30 +0000574static const char preferred_separator_string[] = { preferred_separator, '\0' };
575
576const StringRef get_separator() {
577 return preferred_separator_string;
578}
579
Douglas Gregor123dc702011-09-14 20:27:01 +0000580void system_temp_directory(bool erasedOnReboot, SmallVectorImpl<char> &result) {
581 result.clear();
Michael J. Spencer7dfbeda2011-12-13 23:16:15 +0000582
David Fang6860c812014-02-12 21:02:12 +0000583#if defined(_CS_DARWIN_USER_TEMP_DIR) && defined(_CS_DARWIN_USER_CACHE_DIR)
Douglas Gregora86ddf02013-03-21 21:46:10 +0000584 // On Darwin, use DARWIN_USER_TEMP_DIR or DARWIN_USER_CACHE_DIR.
David Fang6860c812014-02-12 21:02:12 +0000585 // macros defined in <unistd.h> on darwin >= 9
Douglas Gregora86ddf02013-03-21 21:46:10 +0000586 int ConfName = erasedOnReboot? _CS_DARWIN_USER_TEMP_DIR
587 : _CS_DARWIN_USER_CACHE_DIR;
Craig Topperc10719f2014-04-07 04:17:22 +0000588 size_t ConfLen = confstr(ConfName, nullptr, 0);
Douglas Gregora86ddf02013-03-21 21:46:10 +0000589 if (ConfLen > 0) {
590 do {
591 result.resize(ConfLen);
592 ConfLen = confstr(ConfName, result.data(), result.size());
593 } while (ConfLen > 0 && ConfLen != result.size());
594
595 if (ConfLen > 0) {
596 assert(result.back() == 0);
597 result.pop_back();
598 return;
599 }
600
601 result.clear();
602 }
603#endif
604
Douglas Gregor123dc702011-09-14 20:27:01 +0000605 // Check whether the temporary directory is specified by an environment
606 // variable.
607 const char *EnvironmentVariable;
608#ifdef LLVM_ON_WIN32
609 EnvironmentVariable = "TEMP";
610#else
611 EnvironmentVariable = "TMPDIR";
612#endif
613 if (char *RequestedDir = getenv(EnvironmentVariable)) {
614 result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
615 return;
616 }
Michael J. Spencer7dfbeda2011-12-13 23:16:15 +0000617
Douglas Gregor123dc702011-09-14 20:27:01 +0000618 // Fall back to a system default.
619 const char *DefaultResult;
620#ifdef LLVM_ON_WIN32
621 (void)erasedOnReboot;
Douglas Gregor8b744542011-09-14 23:21:47 +0000622 DefaultResult = "C:\\TEMP";
Douglas Gregor123dc702011-09-14 20:27:01 +0000623#else
624 if (erasedOnReboot)
625 DefaultResult = "/tmp";
626 else
627 DefaultResult = "/var/tmp";
628#endif
629 result.append(DefaultResult, DefaultResult + strlen(DefaultResult));
630}
Michael J. Spencer7dfbeda2011-12-13 23:16:15 +0000631
Michael J. Spencera68282c2010-12-07 18:12:07 +0000632bool has_root_name(const Twine &path) {
Michael J. Spencer112a7692010-12-01 06:03:50 +0000633 SmallString<128> path_storage;
634 StringRef p = path.toStringRef(path_storage);
635
Michael J. Spencerf616b212010-12-07 17:04:04 +0000636 return !root_name(p).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000637}
638
Michael J. Spencera68282c2010-12-07 18:12:07 +0000639bool has_root_directory(const Twine &path) {
Michael J. Spencer112a7692010-12-01 06:03:50 +0000640 SmallString<128> path_storage;
641 StringRef p = path.toStringRef(path_storage);
642
Michael J. Spencerf616b212010-12-07 17:04:04 +0000643 return !root_directory(p).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000644}
645
Michael J. Spencera68282c2010-12-07 18:12:07 +0000646bool has_root_path(const Twine &path) {
Michael J. Spencer112a7692010-12-01 06:03:50 +0000647 SmallString<128> path_storage;
648 StringRef p = path.toStringRef(path_storage);
649
Michael J. Spencerf616b212010-12-07 17:04:04 +0000650 return !root_path(p).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000651}
652
Michael J. Spencer6d4b7e72010-12-20 13:30:28 +0000653bool has_relative_path(const Twine &path) {
654 SmallString<128> path_storage;
655 StringRef p = path.toStringRef(path_storage);
656
657 return !relative_path(p).empty();
658}
659
Michael J. Spencera68282c2010-12-07 18:12:07 +0000660bool has_filename(const Twine &path) {
Michael J. Spencer112a7692010-12-01 06:03:50 +0000661 SmallString<128> path_storage;
662 StringRef p = path.toStringRef(path_storage);
663
Michael J. Spencerf616b212010-12-07 17:04:04 +0000664 return !filename(p).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000665}
666
Michael J. Spencera68282c2010-12-07 18:12:07 +0000667bool has_parent_path(const Twine &path) {
Michael J. Spencer112a7692010-12-01 06:03:50 +0000668 SmallString<128> path_storage;
669 StringRef p = path.toStringRef(path_storage);
670
Michael J. Spencerf616b212010-12-07 17:04:04 +0000671 return !parent_path(p).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000672}
673
Michael J. Spencera68282c2010-12-07 18:12:07 +0000674bool has_stem(const Twine &path) {
Michael J. Spencer112a7692010-12-01 06:03:50 +0000675 SmallString<128> path_storage;
676 StringRef p = path.toStringRef(path_storage);
677
Michael J. Spencerf616b212010-12-07 17:04:04 +0000678 return !stem(p).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000679}
680
Michael J. Spencera68282c2010-12-07 18:12:07 +0000681bool has_extension(const Twine &path) {
Michael J. Spencer112a7692010-12-01 06:03:50 +0000682 SmallString<128> path_storage;
683 StringRef p = path.toStringRef(path_storage);
684
Michael J. Spencerf616b212010-12-07 17:04:04 +0000685 return !extension(p).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000686}
687
Michael J. Spencera68282c2010-12-07 18:12:07 +0000688bool is_absolute(const Twine &path) {
Michael J. Spencera72df5f2010-12-01 06:21:53 +0000689 SmallString<128> path_storage;
690 StringRef p = path.toStringRef(path_storage);
691
Michael J. Spencerf616b212010-12-07 17:04:04 +0000692 bool rootDir = has_root_directory(p),
Michael J. Spencera72df5f2010-12-01 06:21:53 +0000693#ifdef LLVM_ON_WIN32
Michael J. Spencerf616b212010-12-07 17:04:04 +0000694 rootName = has_root_name(p);
Michael J. Spencera72df5f2010-12-01 06:21:53 +0000695#else
Michael J. Spencerf616b212010-12-07 17:04:04 +0000696 rootName = true;
Michael J. Spencera72df5f2010-12-01 06:21:53 +0000697#endif
698
Michael J. Spencerf616b212010-12-07 17:04:04 +0000699 return rootDir && rootName;
Michael J. Spencera72df5f2010-12-01 06:21:53 +0000700}
701
Michael J. Spencera68282c2010-12-07 18:12:07 +0000702bool is_relative(const Twine &path) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000703 return !is_absolute(path);
Michael J. Spencera72df5f2010-12-01 06:21:53 +0000704}
705
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +0000706} // end namespace path
707
708namespace fs {
709
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000710std::error_code getUniqueID(const Twine Path, UniqueID &Result) {
Rafael Espindola7f822a92013-07-29 21:26:49 +0000711 file_status Status;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000712 std::error_code EC = status(Path, Status);
Rafael Espindola7f822a92013-07-29 21:26:49 +0000713 if (EC)
714 return EC;
715 Result = Status.getUniqueID();
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000716 return std::error_code();
Rafael Espindola7f822a92013-07-29 21:26:49 +0000717}
718
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000719std::error_code createUniqueFile(const Twine &Model, int &ResultFd,
720 SmallVectorImpl<char> &ResultPath,
721 unsigned Mode) {
Rafael Espindolac9d2e5b2013-07-05 21:01:08 +0000722 return createUniqueEntity(Model, ResultFd, ResultPath, false, Mode, FS_File);
723}
724
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000725std::error_code createUniqueFile(const Twine &Model,
726 SmallVectorImpl<char> &ResultPath) {
Rafael Espindolac9d2e5b2013-07-05 21:01:08 +0000727 int Dummy;
728 return createUniqueEntity(Model, Dummy, ResultPath, false, 0, FS_Name);
729}
730
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000731static std::error_code
732createTemporaryFile(const Twine &Model, int &ResultFD,
733 llvm::SmallVectorImpl<char> &ResultPath, FSEntity Type) {
Rafael Espindola325fa0f2013-07-05 19:56:49 +0000734 SmallString<128> Storage;
735 StringRef P = Model.toNullTerminatedStringRef(Storage);
736 assert(P.find_first_of(separators) == StringRef::npos &&
737 "Model must be a simple filename.");
738 // Use P.begin() so that createUniqueEntity doesn't need to recreate Storage.
739 return createUniqueEntity(P.begin(), ResultFD, ResultPath,
740 true, owner_read | owner_write, Type);
741}
742
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000743static std::error_code
Rafael Espindola325fa0f2013-07-05 19:56:49 +0000744createTemporaryFile(const Twine &Prefix, StringRef Suffix, int &ResultFD,
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000745 llvm::SmallVectorImpl<char> &ResultPath, FSEntity Type) {
Rafael Espindolad3c89042013-07-25 15:00:17 +0000746 const char *Middle = Suffix.empty() ? "-%%%%%%" : "-%%%%%%.";
747 return createTemporaryFile(Prefix + Middle + Suffix, ResultFD, ResultPath,
Rafael Espindola325fa0f2013-07-05 19:56:49 +0000748 Type);
749}
750
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000751std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
752 int &ResultFD,
753 SmallVectorImpl<char> &ResultPath) {
Rafael Espindola325fa0f2013-07-05 19:56:49 +0000754 return createTemporaryFile(Prefix, Suffix, ResultFD, ResultPath, FS_File);
755}
756
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000757std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
758 SmallVectorImpl<char> &ResultPath) {
Rafael Espindola325fa0f2013-07-05 19:56:49 +0000759 int Dummy;
760 return createTemporaryFile(Prefix, Suffix, Dummy, ResultPath, FS_Name);
761}
762
763
Rafael Espindolae79a8722013-06-28 03:48:47 +0000764// This is a mkdtemp with a different pattern. We use createUniqueEntity mostly
Rafael Espindola31a24432013-06-28 10:55:41 +0000765// for consistency. We should try using mkdtemp.
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000766std::error_code createUniqueDirectory(const Twine &Prefix,
767 SmallVectorImpl<char> &ResultPath) {
Rafael Espindolae79a8722013-06-28 03:48:47 +0000768 int Dummy;
769 return createUniqueEntity(Prefix + "-%%%%%%", Dummy, ResultPath,
770 true, 0, FS_Dir);
Rafael Espindola7ffacc42013-06-27 03:45:31 +0000771}
772
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000773std::error_code make_absolute(SmallVectorImpl<char> &path) {
Michael J. Spencer92903a32010-12-07 03:57:17 +0000774 StringRef p(path.data(), path.size());
775
Daniel Dunbarb23158c2012-02-29 00:20:37 +0000776 bool rootDirectory = path::has_root_directory(p),
777#ifdef LLVM_ON_WIN32
Daniel Dunbar39ea4582012-02-29 00:46:46 +0000778 rootName = path::has_root_name(p);
Daniel Dunbarb23158c2012-02-29 00:20:37 +0000779#else
780 rootName = true;
781#endif
Michael J. Spencer92903a32010-12-07 03:57:17 +0000782
783 // Already absolute.
784 if (rootName && rootDirectory)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000785 return std::error_code();
Michael J. Spencer92903a32010-12-07 03:57:17 +0000786
787 // All of the following conditions will need the current directory.
788 SmallString<128> current_dir;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000789 if (std::error_code ec = current_path(current_dir))
790 return ec;
Michael J. Spencer92903a32010-12-07 03:57:17 +0000791
792 // Relative path. Prepend the current directory.
793 if (!rootName && !rootDirectory) {
794 // Append path to the current directory.
Michael J. Spencer1e090f02010-12-07 03:57:37 +0000795 path::append(current_dir, p);
Michael J. Spencer92903a32010-12-07 03:57:17 +0000796 // Set path to the result.
797 path.swap(current_dir);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000798 return std::error_code();
Michael J. Spencer92903a32010-12-07 03:57:17 +0000799 }
800
801 if (!rootName && rootDirectory) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000802 StringRef cdrn = path::root_name(current_dir);
Michael J. Spencer92903a32010-12-07 03:57:17 +0000803 SmallString<128> curDirRootName(cdrn.begin(), cdrn.end());
Michael J. Spencer1e090f02010-12-07 03:57:37 +0000804 path::append(curDirRootName, p);
Michael J. Spencer92903a32010-12-07 03:57:17 +0000805 // Set path to the result.
806 path.swap(curDirRootName);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000807 return std::error_code();
Michael J. Spencer92903a32010-12-07 03:57:17 +0000808 }
809
810 if (rootName && !rootDirectory) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000811 StringRef pRootName = path::root_name(p);
812 StringRef bRootDirectory = path::root_directory(current_dir);
813 StringRef bRelativePath = path::relative_path(current_dir);
814 StringRef pRelativePath = path::relative_path(p);
Michael J. Spencer92903a32010-12-07 03:57:17 +0000815
816 SmallString<128> res;
Michael J. Spencer1e090f02010-12-07 03:57:37 +0000817 path::append(res, pRootName, bRootDirectory, bRelativePath, pRelativePath);
Michael J. Spencer92903a32010-12-07 03:57:17 +0000818 path.swap(res);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000819 return std::error_code();
Michael J. Spencer92903a32010-12-07 03:57:17 +0000820 }
821
822 llvm_unreachable("All rootName and rootDirectory combinations should have "
823 "occurred above!");
824}
825
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000826std::error_code create_directories(const Twine &Path, bool IgnoreExisting) {
Rafael Espindolab6f72b22014-02-13 16:58:19 +0000827 SmallString<128> PathStorage;
828 StringRef P = Path.toStringRef(PathStorage);
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000829
Rafael Espindolab6f72b22014-02-13 16:58:19 +0000830 // Be optimistic and try to create the directory
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000831 std::error_code EC = create_directory(P, IgnoreExisting);
Rafael Espindolab6f72b22014-02-13 16:58:19 +0000832 // If we succeeded, or had any error other than the parent not existing, just
833 // return it.
Rafael Espindola2a826e42014-06-13 17:20:48 +0000834 if (EC != errc::no_such_file_or_directory)
Rafael Espindolab6f72b22014-02-13 16:58:19 +0000835 return EC;
Michael J. Spencerf616b212010-12-07 17:04:04 +0000836
Rafael Espindolab6f72b22014-02-13 16:58:19 +0000837 // We failed because of a no_such_file_or_directory, try to create the
838 // parent.
839 StringRef Parent = path::parent_path(P);
840 if (Parent.empty())
841 return EC;
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000842
Rafael Espindolab6f72b22014-02-13 16:58:19 +0000843 if ((EC = create_directories(Parent)))
844 return EC;
845
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000846 return create_directory(P, IgnoreExisting);
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000847}
848
Justin Bognercd45f962014-06-19 19:35:39 +0000849std::error_code copy_file(const Twine &From, const Twine &To) {
850 int ReadFD, WriteFD;
851 if (std::error_code EC = openFileForRead(From, ReadFD))
852 return EC;
853 if (std::error_code EC = openFileForWrite(To, WriteFD, F_None)) {
854 close(ReadFD);
855 return EC;
856 }
857
858 const size_t BufSize = 4096;
859 char *Buf = new char[BufSize];
860 int BytesRead = 0, BytesWritten = 0;
861 for (;;) {
862 BytesRead = read(ReadFD, Buf, BufSize);
863 if (BytesRead <= 0)
864 break;
865 while (BytesRead) {
866 BytesWritten = write(WriteFD, Buf, BytesRead);
867 if (BytesWritten < 0)
868 break;
869 BytesRead -= BytesWritten;
870 }
871 if (BytesWritten < 0)
872 break;
873 }
874 close(ReadFD);
875 close(WriteFD);
876 delete[] Buf;
877
878 if (BytesRead < 0 || BytesWritten < 0)
879 return std::error_code(errno, std::generic_category());
880 return std::error_code();
881}
882
Michael J. Spencer730f51a2010-12-09 17:37:02 +0000883bool exists(file_status status) {
884 return status_known(status) && status.type() != file_type::file_not_found;
885}
886
887bool status_known(file_status s) {
888 return s.type() != file_type::status_error;
889}
890
891bool is_directory(file_status status) {
892 return status.type() == file_type::directory_file;
893}
894
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000895std::error_code is_directory(const Twine &path, bool &result) {
Michael J. Spencer0d771ed2011-01-11 01:21:55 +0000896 file_status st;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000897 if (std::error_code ec = status(path, st))
Michael J. Spencer0d771ed2011-01-11 01:21:55 +0000898 return ec;
899 result = is_directory(st);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000900 return std::error_code();
Michael J. Spencer0d771ed2011-01-11 01:21:55 +0000901}
902
Michael J. Spencer730f51a2010-12-09 17:37:02 +0000903bool is_regular_file(file_status status) {
904 return status.type() == file_type::regular_file;
905}
906
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000907std::error_code is_regular_file(const Twine &path, bool &result) {
Michael J. Spencer0d771ed2011-01-11 01:21:55 +0000908 file_status st;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000909 if (std::error_code ec = status(path, st))
Michael J. Spencer0d771ed2011-01-11 01:21:55 +0000910 return ec;
911 result = is_regular_file(st);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000912 return std::error_code();
Michael J. Spencer0d771ed2011-01-11 01:21:55 +0000913}
914
Michael J. Spencer730f51a2010-12-09 17:37:02 +0000915bool is_other(file_status status) {
916 return exists(status) &&
917 !is_regular_file(status) &&
Rafael Espindola20063062014-03-20 17:39:04 +0000918 !is_directory(status);
Michael J. Spencer730f51a2010-12-09 17:37:02 +0000919}
920
Benjamin Kramer91ead3c2011-09-14 01:14:36 +0000921void directory_entry::replace_filename(const Twine &filename, file_status st) {
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000922 SmallString<128> path(Path.begin(), Path.end());
923 path::remove_filename(path);
924 path::append(path, filename);
925 Path = path.str();
926 Status = st;
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000927}
928
Michael J. Spencer4f8a8322011-12-13 23:17:12 +0000929/// @brief Identify the magic in magic.
Rafael Espindola9b404292013-06-11 17:22:12 +0000930 file_magic identify_magic(StringRef Magic) {
931 if (Magic.size() < 4)
Michael J. Spencer96ebd912012-06-19 05:29:57 +0000932 return file_magic::unknown;
Rafael Espindola9b404292013-06-11 17:22:12 +0000933 switch ((unsigned char)Magic[0]) {
Rui Ueyamafc149a62013-10-15 22:45:38 +0000934 case 0x00: {
Rui Ueyamae448f9e2013-11-15 21:22:02 +0000935 // COFF short import library file
936 if (Magic[1] == (char)0x00 && Magic[2] == (char)0xff &&
937 Magic[3] == (char)0xff)
938 return file_magic::coff_import_library;
Rui Ueyamafc149a62013-10-15 22:45:38 +0000939 // Windows resource file
Rui Ueyama50a86e12013-10-16 03:29:49 +0000940 const char Expected[] = { 0, 0, 0, 0, '\x20', 0, 0, 0, '\xff' };
Rui Ueyamafc149a62013-10-15 22:45:38 +0000941 if (Magic.size() >= sizeof(Expected) &&
942 memcmp(Magic.data(), Expected, sizeof(Expected)) == 0)
943 return file_magic::windows_resource;
Rui Ueyama829c4392013-11-14 22:09:08 +0000944 // 0x0000 = COFF unknown machine type
945 if (Magic[1] == 0)
946 return file_magic::coff_object;
Rui Ueyamafc149a62013-10-15 22:45:38 +0000947 break;
948 }
Michael J. Spencer4f8a8322011-12-13 23:17:12 +0000949 case 0xDE: // 0x0B17C0DE = BC wraper
Rafael Espindola9b404292013-06-11 17:22:12 +0000950 if (Magic[1] == (char)0xC0 && Magic[2] == (char)0x17 &&
951 Magic[3] == (char)0x0B)
Michael J. Spencer4f8a8322011-12-13 23:17:12 +0000952 return file_magic::bitcode;
953 break;
954 case 'B':
Rafael Espindola9b404292013-06-11 17:22:12 +0000955 if (Magic[1] == 'C' && Magic[2] == (char)0xC0 && Magic[3] == (char)0xDE)
Michael J. Spencer4f8a8322011-12-13 23:17:12 +0000956 return file_magic::bitcode;
957 break;
958 case '!':
Rafael Espindola9b404292013-06-11 17:22:12 +0000959 if (Magic.size() >= 8)
960 if (memcmp(Magic.data(),"!<arch>\n",8) == 0)
Michael J. Spencer4f8a8322011-12-13 23:17:12 +0000961 return file_magic::archive;
962 break;
963
964 case '\177':
Rafael Espindola823de7c2013-06-11 17:25:45 +0000965 if (Magic.size() >= 18 && Magic[1] == 'E' && Magic[2] == 'L' &&
966 Magic[3] == 'F') {
Rafael Espindola9b404292013-06-11 17:22:12 +0000967 bool Data2MSB = Magic[5] == 2;
Michael J. Spencerb8055cb2013-04-05 20:10:04 +0000968 unsigned high = Data2MSB ? 16 : 17;
969 unsigned low = Data2MSB ? 17 : 16;
Rafael Espindola823de7c2013-06-11 17:25:45 +0000970 if (Magic[high] == 0)
Rafael Espindola9b404292013-06-11 17:22:12 +0000971 switch (Magic[low]) {
Michael J. Spencer4f8a8322011-12-13 23:17:12 +0000972 default: break;
973 case 1: return file_magic::elf_relocatable;
974 case 2: return file_magic::elf_executable;
975 case 3: return file_magic::elf_shared_object;
976 case 4: return file_magic::elf_core;
977 }
978 }
979 break;
980
981 case 0xCA:
Rafael Espindola9b404292013-06-11 17:22:12 +0000982 if (Magic[1] == char(0xFE) && Magic[2] == char(0xBA) &&
983 Magic[3] == char(0xBE)) {
Michael J. Spencer4f8a8322011-12-13 23:17:12 +0000984 // This is complicated by an overlap with Java class files.
985 // See the Mach-O section in /usr/share/file/magic for details.
Rafael Espindola9b404292013-06-11 17:22:12 +0000986 if (Magic.size() >= 8 && Magic[7] < 43)
Alexey Samsonove6388e62013-06-18 15:03:28 +0000987 return file_magic::macho_universal_binary;
Michael J. Spencer4f8a8322011-12-13 23:17:12 +0000988 }
989 break;
990
991 // The two magic numbers for mach-o are:
992 // 0xfeedface - 32-bit mach-o
993 // 0xfeedfacf - 64-bit mach-o
994 case 0xFE:
995 case 0xCE:
996 case 0xCF: {
997 uint16_t type = 0;
Rafael Espindola9b404292013-06-11 17:22:12 +0000998 if (Magic[0] == char(0xFE) && Magic[1] == char(0xED) &&
999 Magic[2] == char(0xFA) &&
1000 (Magic[3] == char(0xCE) || Magic[3] == char(0xCF))) {
Michael J. Spencer4f8a8322011-12-13 23:17:12 +00001001 /* Native endian */
Rafael Espindola9b404292013-06-11 17:22:12 +00001002 if (Magic.size() >= 16) type = Magic[14] << 8 | Magic[15];
1003 } else if ((Magic[0] == char(0xCE) || Magic[0] == char(0xCF)) &&
1004 Magic[1] == char(0xFA) && Magic[2] == char(0xED) &&
1005 Magic[3] == char(0xFE)) {
Michael J. Spencer4f8a8322011-12-13 23:17:12 +00001006 /* Reverse endian */
Rafael Espindola9b404292013-06-11 17:22:12 +00001007 if (Magic.size() >= 14) type = Magic[13] << 8 | Magic[12];
Michael J. Spencer4f8a8322011-12-13 23:17:12 +00001008 }
1009 switch (type) {
1010 default: break;
1011 case 1: return file_magic::macho_object;
1012 case 2: return file_magic::macho_executable;
1013 case 3: return file_magic::macho_fixed_virtual_memory_shared_lib;
1014 case 4: return file_magic::macho_core;
Rafael Espindola134cc992013-06-10 20:32:27 +00001015 case 5: return file_magic::macho_preload_executable;
Michael J. Spencer4f8a8322011-12-13 23:17:12 +00001016 case 6: return file_magic::macho_dynamically_linked_shared_lib;
1017 case 7: return file_magic::macho_dynamic_linker;
1018 case 8: return file_magic::macho_bundle;
1019 case 9: return file_magic::macho_dynamic_linker;
1020 case 10: return file_magic::macho_dsym_companion;
1021 }
1022 break;
1023 }
1024 case 0xF0: // PowerPC Windows
1025 case 0x83: // Alpha 32-bit
1026 case 0x84: // Alpha 64-bit
1027 case 0x66: // MPS R4000 Windows
1028 case 0x50: // mc68K
1029 case 0x4c: // 80386 Windows
Saleem Abdulrasool9b7c0af2014-03-13 07:02:35 +00001030 case 0xc4: // ARMNT Windows
Rafael Espindola9b404292013-06-11 17:22:12 +00001031 if (Magic[1] == 0x01)
Michael J. Spencer4f8a8322011-12-13 23:17:12 +00001032 return file_magic::coff_object;
1033
1034 case 0x90: // PA-RISC Windows
1035 case 0x68: // mc68K Windows
Rafael Espindola9b404292013-06-11 17:22:12 +00001036 if (Magic[1] == 0x02)
Michael J. Spencer4f8a8322011-12-13 23:17:12 +00001037 return file_magic::coff_object;
1038 break;
1039
1040 case 0x4d: // Possible MS-DOS stub on Windows PE file
Rafael Espindola9b404292013-06-11 17:22:12 +00001041 if (Magic[1] == 0x5a) {
Michael J. Spencer4f8a8322011-12-13 23:17:12 +00001042 uint32_t off =
Rafael Espindola9b404292013-06-11 17:22:12 +00001043 *reinterpret_cast<const support::ulittle32_t*>(Magic.data() + 0x3c);
Michael J. Spencer4f8a8322011-12-13 23:17:12 +00001044 // PE/COFF file, either EXE or DLL.
Rafael Espindola9b404292013-06-11 17:22:12 +00001045 if (off < Magic.size() && memcmp(Magic.data() + off, "PE\0\0",4) == 0)
Michael J. Spencer4f8a8322011-12-13 23:17:12 +00001046 return file_magic::pecoff_executable;
1047 }
1048 break;
1049
1050 case 0x64: // x86-64 Windows.
Rafael Espindola9b404292013-06-11 17:22:12 +00001051 if (Magic[1] == char(0x86))
Michael J. Spencer4f8a8322011-12-13 23:17:12 +00001052 return file_magic::coff_object;
1053 break;
1054
1055 default:
1056 break;
1057 }
1058 return file_magic::unknown;
1059}
1060
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001061std::error_code identify_magic(const Twine &Path, file_magic &Result) {
Rafael Espindolada70bfd2014-06-11 22:53:00 +00001062 int FD;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001063 if (std::error_code EC = openFileForRead(Path, FD))
Rafael Espindolada70bfd2014-06-11 22:53:00 +00001064 return EC;
Michael J. Spencer94b2ab32011-01-15 20:39:36 +00001065
Rafael Espindolada70bfd2014-06-11 22:53:00 +00001066 char Buffer[32];
1067 int Length = read(FD, Buffer, sizeof(Buffer));
1068 if (Length < 0)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001069 return std::error_code(errno, std::generic_category());
Rafael Espindolada70bfd2014-06-11 22:53:00 +00001070
1071 Result = identify_magic(StringRef(Buffer, Length));
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001072 return std::error_code();
Michael J. Spencer94b2ab32011-01-15 20:39:36 +00001073}
1074
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001075std::error_code directory_entry::status(file_status &result) const {
Michael J. Spencerf8dc1862011-01-05 16:39:13 +00001076 return fs::status(Path, result);
1077}
1078
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +00001079} // end namespace fs
1080} // end namespace sys
1081} // end namespace llvm
Michael J. Spencerebad2f92010-11-29 22:28:51 +00001082
1083// Include the truly platform-specific parts.
1084#if defined(LLVM_ON_UNIX)
Rafael Espindolaf1fc3822013-06-26 19:33:03 +00001085#include "Unix/Path.inc"
Michael J. Spencerebad2f92010-11-29 22:28:51 +00001086#endif
1087#if defined(LLVM_ON_WIN32)
Rafael Espindolaf1fc3822013-06-26 19:33:03 +00001088#include "Windows/Path.inc"
Michael J. Spencerebad2f92010-11-29 22:28:51 +00001089#endif