LLVM  3.7.0
Path.cpp
Go to the documentation of this file.
1 //===-- Path.cpp - Implement OS Path Concept ------------------------------===//
2 //
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 //
10 // This file implements the operating system Path API.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Support/COFF.h"
15 #include "llvm/Support/Endian.h"
16 #include "llvm/Support/Errc.h"
19 #include "llvm/Support/Path.h"
20 #include "llvm/Support/Process.h"
21 #include <cctype>
22 #include <cstring>
23 
24 #if !defined(_MSC_VER) && !defined(__MINGW32__)
25 #include <unistd.h>
26 #else
27 #include <io.h>
28 #endif
29 
30 using namespace llvm;
31 using namespace llvm::support::endian;
32 
33 namespace {
34  using llvm::StringRef;
36 
37 #ifdef LLVM_ON_WIN32
38  const char *separators = "\\/";
39  const char preferred_separator = '\\';
40 #else
41  const char separators = '/';
42  const char preferred_separator = '/';
43 #endif
44 
45  StringRef find_first_component(StringRef path) {
46  // 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  // * {file,directory}name
51 
52  if (path.empty())
53  return path;
54 
55 #ifdef LLVM_ON_WIN32
56  // C:
57  if (path.size() >= 2 && std::isalpha(static_cast<unsigned char>(path[0])) &&
58  path[1] == ':')
59  return path.substr(0, 2);
60 #endif
61 
62  // //net
63  if ((path.size() > 2) &&
64  is_separator(path[0]) &&
65  path[0] == path[1] &&
66  !is_separator(path[2])) {
67  // Find the next directory separator.
68  size_t end = path.find_first_of(separators, 2);
69  return path.substr(0, end);
70  }
71 
72  // {/,\}
73  if (is_separator(path[0]))
74  return path.substr(0, 1);
75 
76  // * {file,directory}name
77  size_t end = path.find_first_of(separators);
78  return path.substr(0, end);
79  }
80 
81  size_t filename_pos(StringRef str) {
82  if (str.size() == 2 &&
83  is_separator(str[0]) &&
84  str[0] == str[1])
85  return 0;
86 
87  if (str.size() > 0 && is_separator(str[str.size() - 1]))
88  return str.size() - 1;
89 
90  size_t pos = str.find_last_of(separators, str.size() - 1);
91 
92 #ifdef LLVM_ON_WIN32
93  if (pos == StringRef::npos)
94  pos = str.find_last_of(':', str.size() - 2);
95 #endif
96 
97  if (pos == StringRef::npos ||
98  (pos == 1 && is_separator(str[0])))
99  return 0;
100 
101  return pos + 1;
102  }
103 
104  size_t root_dir_start(StringRef str) {
105  // case "c:/"
106 #ifdef LLVM_ON_WIN32
107  if (str.size() > 2 &&
108  str[1] == ':' &&
109  is_separator(str[2]))
110  return 2;
111 #endif
112 
113  // case "//"
114  if (str.size() == 2 &&
115  is_separator(str[0]) &&
116  str[0] == str[1])
117  return StringRef::npos;
118 
119  // case "//net"
120  if (str.size() > 3 &&
121  is_separator(str[0]) &&
122  str[0] == str[1] &&
123  !is_separator(str[2])) {
124  return str.find_first_of(separators, 2);
125  }
126 
127  // case "/"
128  if (str.size() > 0 && is_separator(str[0]))
129  return 0;
130 
131  return StringRef::npos;
132  }
133 
134  size_t parent_path_end(StringRef path) {
135  size_t end_pos = filename_pos(path);
136 
137  bool filename_was_sep = path.size() > 0 && is_separator(path[end_pos]);
138 
139  // Skip separators except for root dir.
140  size_t root_dir_pos = root_dir_start(path.substr(0, end_pos));
141 
142  while(end_pos > 0 &&
143  (end_pos - 1) != root_dir_pos &&
144  is_separator(path[end_pos - 1]))
145  --end_pos;
146 
147  if (end_pos == 1 && root_dir_pos == 0 && filename_was_sep)
148  return StringRef::npos;
149 
150  return end_pos;
151  }
152 } // end unnamed namespace
153 
154 enum FSEntity {
158 };
159 
160 static std::error_code createUniqueEntity(const Twine &Model, int &ResultFD,
161  SmallVectorImpl<char> &ResultPath,
162  bool MakeAbsolute, unsigned Mode,
163  FSEntity Type) {
164  SmallString<128> ModelStorage;
165  Model.toVector(ModelStorage);
166 
167  if (MakeAbsolute) {
168  // Make model absolute by prepending a temp directory if it's not already.
169  if (!sys::path::is_absolute(Twine(ModelStorage))) {
170  SmallString<128> TDir;
172  sys::path::append(TDir, Twine(ModelStorage));
173  ModelStorage.swap(TDir);
174  }
175  }
176 
177  // From here on, DO NOT modify model. It may be needed if the randomly chosen
178  // path already exists.
179  ResultPath = ModelStorage;
180  // Null terminate.
181  ResultPath.push_back(0);
182  ResultPath.pop_back();
183 
184 retry_random_path:
185  // Replace '%' with random chars.
186  for (unsigned i = 0, e = ModelStorage.size(); i != e; ++i) {
187  if (ModelStorage[i] == '%')
188  ResultPath[i] = "0123456789abcdef"[sys::Process::GetRandomNumber() & 15];
189  }
190 
191  // Try to open + create the file.
192  switch (Type) {
193  case FS_File: {
194  if (std::error_code EC =
195  sys::fs::openFileForWrite(Twine(ResultPath.begin()), ResultFD,
196  sys::fs::F_RW | sys::fs::F_Excl, Mode)) {
197  if (EC == errc::file_exists)
198  goto retry_random_path;
199  return EC;
200  }
201 
202  return std::error_code();
203  }
204 
205  case FS_Name: {
206  std::error_code EC =
209  return std::error_code();
210  if (EC)
211  return EC;
212  goto retry_random_path;
213  }
214 
215  case FS_Dir: {
216  if (std::error_code EC =
217  sys::fs::create_directory(ResultPath.begin(), false)) {
218  if (EC == errc::file_exists)
219  goto retry_random_path;
220  return EC;
221  }
222  return std::error_code();
223  }
224  }
225  llvm_unreachable("Invalid Type");
226 }
227 
228 namespace llvm {
229 namespace sys {
230 namespace path {
231 
233  const_iterator i;
234  i.Path = path;
235  i.Component = find_first_component(path);
236  i.Position = 0;
237  return i;
238 }
239 
241  const_iterator i;
242  i.Path = path;
243  i.Position = path.size();
244  return i;
245 }
246 
247 const_iterator &const_iterator::operator++() {
248  assert(Position < Path.size() && "Tried to increment past end!");
249 
250  // Increment Position to past the current component
251  Position += Component.size();
252 
253  // Check for end.
254  if (Position == Path.size()) {
255  Component = StringRef();
256  return *this;
257  }
258 
259  // Both POSIX and Windows treat paths that begin with exactly two separators
260  // specially.
261  bool was_net = Component.size() > 2 &&
262  is_separator(Component[0]) &&
263  Component[1] == Component[0] &&
264  !is_separator(Component[2]);
265 
266  // Handle separators.
267  if (is_separator(Path[Position])) {
268  // Root dir.
269  if (was_net
270 #ifdef LLVM_ON_WIN32
271  // c:/
272  || Component.endswith(":")
273 #endif
274  ) {
275  Component = Path.substr(Position, 1);
276  return *this;
277  }
278 
279  // Skip extra separators.
280  while (Position != Path.size() &&
281  is_separator(Path[Position])) {
282  ++Position;
283  }
284 
285  // Treat trailing '/' as a '.'.
286  if (Position == Path.size()) {
287  --Position;
288  Component = ".";
289  return *this;
290  }
291  }
292 
293  // Find next component.
294  size_t end_pos = Path.find_first_of(separators, Position);
295  Component = Path.slice(Position, end_pos);
296 
297  return *this;
298 }
299 
301  return Path.begin() == RHS.Path.begin() && Position == RHS.Position;
302 }
303 
304 ptrdiff_t const_iterator::operator-(const const_iterator &RHS) const {
305  return Position - RHS.Position;
306 }
307 
310  I.Path = Path;
311  I.Position = Path.size();
312  return ++I;
313 }
314 
317  I.Path = Path;
318  I.Component = Path.substr(0, 0);
319  I.Position = 0;
320  return I;
321 }
322 
323 reverse_iterator &reverse_iterator::operator++() {
324  // If we're at the end and the previous char was a '/', return '.' unless
325  // we are the root path.
326  size_t root_dir_pos = root_dir_start(Path);
327  if (Position == Path.size() &&
328  Path.size() > root_dir_pos + 1 &&
329  is_separator(Path[Position - 1])) {
330  --Position;
331  Component = ".";
332  return *this;
333  }
334 
335  // Skip separators unless it's the root directory.
336  size_t end_pos = Position;
337 
338  while(end_pos > 0 &&
339  (end_pos - 1) != root_dir_pos &&
340  is_separator(Path[end_pos - 1]))
341  --end_pos;
342 
343  // Find next separator.
344  size_t start_pos = filename_pos(Path.substr(0, end_pos));
345  Component = Path.slice(start_pos, end_pos);
346  Position = start_pos;
347  return *this;
348 }
349 
351  return Path.begin() == RHS.Path.begin() && Component == RHS.Component &&
352  Position == RHS.Position;
353 }
354 
356  const_iterator b = begin(path),
357  pos = b,
358  e = end(path);
359  if (b != e) {
360  bool has_net = b->size() > 2 && is_separator((*b)[0]) && (*b)[1] == (*b)[0];
361  bool has_drive =
362 #ifdef LLVM_ON_WIN32
363  b->endswith(":");
364 #else
365  false;
366 #endif
367 
368  if (has_net || has_drive) {
369  if ((++pos != e) && is_separator((*pos)[0])) {
370  // {C:/,//net/}, so get the first two components.
371  return path.substr(0, b->size() + pos->size());
372  } else {
373  // just {C:,//net}, return the first component.
374  return *b;
375  }
376  }
377 
378  // POSIX style root directory.
379  if (is_separator((*b)[0])) {
380  return *b;
381  }
382  }
383 
384  return StringRef();
385 }
386 
388  const_iterator b = begin(path),
389  e = end(path);
390  if (b != e) {
391  bool has_net = b->size() > 2 && is_separator((*b)[0]) && (*b)[1] == (*b)[0];
392  bool has_drive =
393 #ifdef LLVM_ON_WIN32
394  b->endswith(":");
395 #else
396  false;
397 #endif
398 
399  if (has_net || has_drive) {
400  // just {C:,//net}, return the first component.
401  return *b;
402  }
403  }
404 
405  // No path or no name.
406  return StringRef();
407 }
408 
410  const_iterator b = begin(path),
411  pos = b,
412  e = end(path);
413  if (b != e) {
414  bool has_net = b->size() > 2 && is_separator((*b)[0]) && (*b)[1] == (*b)[0];
415  bool has_drive =
416 #ifdef LLVM_ON_WIN32
417  b->endswith(":");
418 #else
419  false;
420 #endif
421 
422  if ((has_net || has_drive) &&
423  // {C:,//net}, skip to the next component.
424  (++pos != e) && is_separator((*pos)[0])) {
425  return *pos;
426  }
427 
428  // POSIX style root directory.
429  if (!has_net && is_separator((*b)[0])) {
430  return *b;
431  }
432  }
433 
434  // No path or no root.
435  return StringRef();
436 }
437 
439  StringRef root = root_path(path);
440  return path.substr(root.size());
441 }
442 
443 void append(SmallVectorImpl<char> &path, const Twine &a,
444  const Twine &b,
445  const Twine &c,
446  const Twine &d) {
447  SmallString<32> a_storage;
448  SmallString<32> b_storage;
449  SmallString<32> c_storage;
450  SmallString<32> d_storage;
451 
452  SmallVector<StringRef, 4> components;
453  if (!a.isTriviallyEmpty()) components.push_back(a.toStringRef(a_storage));
454  if (!b.isTriviallyEmpty()) components.push_back(b.toStringRef(b_storage));
455  if (!c.isTriviallyEmpty()) components.push_back(c.toStringRef(c_storage));
456  if (!d.isTriviallyEmpty()) components.push_back(d.toStringRef(d_storage));
457 
459  e = components.end();
460  i != e; ++i) {
461  bool path_has_sep = !path.empty() && is_separator(path[path.size() - 1]);
462  bool component_has_sep = !i->empty() && is_separator((*i)[0]);
463  bool is_root_name = has_root_name(*i);
464 
465  if (path_has_sep) {
466  // Strip separators from beginning of component.
467  size_t loc = i->find_first_not_of(separators);
468  StringRef c = i->substr(loc);
469 
470  // Append it.
471  path.append(c.begin(), c.end());
472  continue;
473  }
474 
475  if (!component_has_sep && !(path.empty() || is_root_name)) {
476  // Add a separator.
477  path.push_back(preferred_separator);
478  }
479 
480  path.append(i->begin(), i->end());
481  }
482 }
483 
486  for (; begin != end; ++begin)
487  path::append(path, *begin);
488 }
489 
491  size_t end_pos = parent_path_end(path);
492  if (end_pos == StringRef::npos)
493  return StringRef();
494  else
495  return path.substr(0, end_pos);
496 }
497 
499  size_t end_pos = parent_path_end(StringRef(path.begin(), path.size()));
500  if (end_pos != StringRef::npos)
501  path.set_size(end_pos);
502 }
503 
505  StringRef p(path.begin(), path.size());
506  SmallString<32> ext_storage;
507  StringRef ext = extension.toStringRef(ext_storage);
508 
509  // Erase existing extension.
510  size_t pos = p.find_last_of('.');
511  if (pos != StringRef::npos && pos >= filename_pos(p))
512  path.set_size(pos);
513 
514  // Append '.' if needed.
515  if (ext.size() > 0 && ext[0] != '.')
516  path.push_back('.');
517 
518  // Append extension.
519  path.append(ext.begin(), ext.end());
520 }
521 
522 void native(const Twine &path, SmallVectorImpl<char> &result) {
523  assert((!path.isSingleStringRef() ||
524  path.getSingleStringRef().data() != result.data()) &&
525  "path and result are not allowed to overlap!");
526  // Clear result.
527  result.clear();
528  path.toVector(result);
529  native(result);
530 }
531 
533 #ifdef LLVM_ON_WIN32
534  std::replace(Path.begin(), Path.end(), '/', '\\');
535 #else
536  for (auto PI = Path.begin(), PE = Path.end(); PI < PE; ++PI) {
537  if (*PI == '\\') {
538  auto PN = PI + 1;
539  if (PN < PE && *PN == '\\')
540  ++PI; // increment once, the for loop will move over the escaped slash
541  else
542  *PI = '/';
543  }
544  }
545 #endif
546 }
547 
549  return *rbegin(path);
550 }
551 
553  StringRef fname = filename(path);
554  size_t pos = fname.find_last_of('.');
555  if (pos == StringRef::npos)
556  return fname;
557  else
558  if ((fname.size() == 1 && fname == ".") ||
559  (fname.size() == 2 && fname == ".."))
560  return fname;
561  else
562  return fname.substr(0, pos);
563 }
564 
566  StringRef fname = filename(path);
567  size_t pos = fname.find_last_of('.');
568  if (pos == StringRef::npos)
569  return StringRef();
570  else
571  if ((fname.size() == 1 && fname == ".") ||
572  (fname.size() == 2 && fname == ".."))
573  return StringRef();
574  else
575  return fname.substr(pos);
576 }
577 
578 bool is_separator(char value) {
579  switch(value) {
580 #ifdef LLVM_ON_WIN32
581  case '\\': // fall through
582 #endif
583  case '/': return true;
584  default: return false;
585  }
586 }
587 
588 static const char preferred_separator_string[] = { preferred_separator, '\0' };
589 
592 }
593 
594 bool has_root_name(const Twine &path) {
595  SmallString<128> path_storage;
596  StringRef p = path.toStringRef(path_storage);
597 
598  return !root_name(p).empty();
599 }
600 
601 bool has_root_directory(const Twine &path) {
602  SmallString<128> path_storage;
603  StringRef p = path.toStringRef(path_storage);
604 
605  return !root_directory(p).empty();
606 }
607 
608 bool has_root_path(const Twine &path) {
609  SmallString<128> path_storage;
610  StringRef p = path.toStringRef(path_storage);
611 
612  return !root_path(p).empty();
613 }
614 
615 bool has_relative_path(const Twine &path) {
616  SmallString<128> path_storage;
617  StringRef p = path.toStringRef(path_storage);
618 
619  return !relative_path(p).empty();
620 }
621 
622 bool has_filename(const Twine &path) {
623  SmallString<128> path_storage;
624  StringRef p = path.toStringRef(path_storage);
625 
626  return !filename(p).empty();
627 }
628 
629 bool has_parent_path(const Twine &path) {
630  SmallString<128> path_storage;
631  StringRef p = path.toStringRef(path_storage);
632 
633  return !parent_path(p).empty();
634 }
635 
636 bool has_stem(const Twine &path) {
637  SmallString<128> path_storage;
638  StringRef p = path.toStringRef(path_storage);
639 
640  return !stem(p).empty();
641 }
642 
643 bool has_extension(const Twine &path) {
644  SmallString<128> path_storage;
645  StringRef p = path.toStringRef(path_storage);
646 
647  return !extension(p).empty();
648 }
649 
650 bool is_absolute(const Twine &path) {
651  SmallString<128> path_storage;
652  StringRef p = path.toStringRef(path_storage);
653 
654  bool rootDir = has_root_directory(p),
655 #ifdef LLVM_ON_WIN32
656  rootName = has_root_name(p);
657 #else
658  rootName = true;
659 #endif
660 
661  return rootDir && rootName;
662 }
663 
664 bool is_relative(const Twine &path) {
665  return !is_absolute(path);
666 }
667 
668 } // end namespace path
669 
670 namespace fs {
671 
672 std::error_code getUniqueID(const Twine Path, UniqueID &Result) {
674  std::error_code EC = status(Path, Status);
675  if (EC)
676  return EC;
677  Result = Status.getUniqueID();
678  return std::error_code();
679 }
680 
681 std::error_code createUniqueFile(const Twine &Model, int &ResultFd,
682  SmallVectorImpl<char> &ResultPath,
683  unsigned Mode) {
684  return createUniqueEntity(Model, ResultFd, ResultPath, false, Mode, FS_File);
685 }
686 
687 std::error_code createUniqueFile(const Twine &Model,
688  SmallVectorImpl<char> &ResultPath) {
689  int Dummy;
690  return createUniqueEntity(Model, Dummy, ResultPath, false, 0, FS_Name);
691 }
692 
693 static std::error_code
694 createTemporaryFile(const Twine &Model, int &ResultFD,
696  SmallString<128> Storage;
697  StringRef P = Model.toNullTerminatedStringRef(Storage);
698  assert(P.find_first_of(separators) == StringRef::npos &&
699  "Model must be a simple filename.");
700  // Use P.begin() so that createUniqueEntity doesn't need to recreate Storage.
701  return createUniqueEntity(P.begin(), ResultFD, ResultPath,
702  true, owner_read | owner_write, Type);
703 }
704 
705 static std::error_code
706 createTemporaryFile(const Twine &Prefix, StringRef Suffix, int &ResultFD,
708  const char *Middle = Suffix.empty() ? "-%%%%%%" : "-%%%%%%.";
709  return createTemporaryFile(Prefix + Middle + Suffix, ResultFD, ResultPath,
710  Type);
711 }
712 
713 std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
714  int &ResultFD,
715  SmallVectorImpl<char> &ResultPath) {
716  return createTemporaryFile(Prefix, Suffix, ResultFD, ResultPath, FS_File);
717 }
718 
719 std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
720  SmallVectorImpl<char> &ResultPath) {
721  int Dummy;
722  return createTemporaryFile(Prefix, Suffix, Dummy, ResultPath, FS_Name);
723 }
724 
725 
726 // This is a mkdtemp with a different pattern. We use createUniqueEntity mostly
727 // for consistency. We should try using mkdtemp.
728 std::error_code createUniqueDirectory(const Twine &Prefix,
729  SmallVectorImpl<char> &ResultPath) {
730  int Dummy;
731  return createUniqueEntity(Prefix + "-%%%%%%", Dummy, ResultPath,
732  true, 0, FS_Dir);
733 }
734 
735 std::error_code make_absolute(SmallVectorImpl<char> &path) {
736  StringRef p(path.data(), path.size());
737 
738  bool rootDirectory = path::has_root_directory(p),
739 #ifdef LLVM_ON_WIN32
740  rootName = path::has_root_name(p);
741 #else
742  rootName = true;
743 #endif
744 
745  // Already absolute.
746  if (rootName && rootDirectory)
747  return std::error_code();
748 
749  // All of the following conditions will need the current directory.
750  SmallString<128> current_dir;
751  if (std::error_code ec = current_path(current_dir))
752  return ec;
753 
754  // Relative path. Prepend the current directory.
755  if (!rootName && !rootDirectory) {
756  // Append path to the current directory.
757  path::append(current_dir, p);
758  // Set path to the result.
759  path.swap(current_dir);
760  return std::error_code();
761  }
762 
763  if (!rootName && rootDirectory) {
764  StringRef cdrn = path::root_name(current_dir);
765  SmallString<128> curDirRootName(cdrn.begin(), cdrn.end());
766  path::append(curDirRootName, p);
767  // Set path to the result.
768  path.swap(curDirRootName);
769  return std::error_code();
770  }
771 
772  if (rootName && !rootDirectory) {
773  StringRef pRootName = path::root_name(p);
774  StringRef bRootDirectory = path::root_directory(current_dir);
775  StringRef bRelativePath = path::relative_path(current_dir);
776  StringRef pRelativePath = path::relative_path(p);
777 
778  SmallString<128> res;
779  path::append(res, pRootName, bRootDirectory, bRelativePath, pRelativePath);
780  path.swap(res);
781  return std::error_code();
782  }
783 
784  llvm_unreachable("All rootName and rootDirectory combinations should have "
785  "occurred above!");
786 }
787 
788 std::error_code create_directories(const Twine &Path, bool IgnoreExisting) {
789  SmallString<128> PathStorage;
790  StringRef P = Path.toStringRef(PathStorage);
791 
792  // Be optimistic and try to create the directory
793  std::error_code EC = create_directory(P, IgnoreExisting);
794  // If we succeeded, or had any error other than the parent not existing, just
795  // return it.
797  return EC;
798 
799  // We failed because of a no_such_file_or_directory, try to create the
800  // parent.
801  StringRef Parent = path::parent_path(P);
802  if (Parent.empty())
803  return EC;
804 
805  if ((EC = create_directories(Parent)))
806  return EC;
807 
808  return create_directory(P, IgnoreExisting);
809 }
810 
811 std::error_code copy_file(const Twine &From, const Twine &To) {
812  int ReadFD, WriteFD;
813  if (std::error_code EC = openFileForRead(From, ReadFD))
814  return EC;
815  if (std::error_code EC = openFileForWrite(To, WriteFD, F_None)) {
816  close(ReadFD);
817  return EC;
818  }
819 
820  const size_t BufSize = 4096;
821  char *Buf = new char[BufSize];
822  int BytesRead = 0, BytesWritten = 0;
823  for (;;) {
824  BytesRead = read(ReadFD, Buf, BufSize);
825  if (BytesRead <= 0)
826  break;
827  while (BytesRead) {
828  BytesWritten = write(WriteFD, Buf, BytesRead);
829  if (BytesWritten < 0)
830  break;
831  BytesRead -= BytesWritten;
832  }
833  if (BytesWritten < 0)
834  break;
835  }
836  close(ReadFD);
837  close(WriteFD);
838  delete[] Buf;
839 
840  if (BytesRead < 0 || BytesWritten < 0)
841  return std::error_code(errno, std::generic_category());
842  return std::error_code();
843 }
844 
846  return status_known(status) && status.type() != file_type::file_not_found;
847 }
848 
850  return s.type() != file_type::status_error;
851 }
852 
854  return status.type() == file_type::directory_file;
855 }
856 
857 std::error_code is_directory(const Twine &path, bool &result) {
858  file_status st;
859  if (std::error_code ec = status(path, st))
860  return ec;
861  result = is_directory(st);
862  return std::error_code();
863 }
864 
866  return status.type() == file_type::regular_file;
867 }
868 
869 std::error_code is_regular_file(const Twine &path, bool &result) {
870  file_status st;
871  if (std::error_code ec = status(path, st))
872  return ec;
873  result = is_regular_file(st);
874  return std::error_code();
875 }
876 
878  return exists(status) &&
879  !is_regular_file(status) &&
880  !is_directory(status);
881 }
882 
883 std::error_code is_other(const Twine &Path, bool &Result) {
884  file_status FileStatus;
885  if (std::error_code EC = status(Path, FileStatus))
886  return EC;
887  Result = is_other(FileStatus);
888  return std::error_code();
889 }
890 
891 void directory_entry::replace_filename(const Twine &filename, file_status st) {
892  SmallString<128> path(Path.begin(), Path.end());
893  path::remove_filename(path);
894  path::append(path, filename);
895  Path = path.str();
896  Status = st;
897 }
898 
899 /// @brief Identify the magic in magic.
901  if (Magic.size() < 4)
902  return file_magic::unknown;
903  switch ((unsigned char)Magic[0]) {
904  case 0x00: {
905  // COFF bigobj or short import library file
906  if (Magic[1] == (char)0x00 && Magic[2] == (char)0xff &&
907  Magic[3] == (char)0xff) {
908  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 = read16le(
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;
921  }
922  // Windows resource file
923  const char Expected[] = { 0, 0, 0, 0, '\x20', 0, 0, 0, '\xff' };
924  if (Magic.size() >= sizeof(Expected) &&
925  memcmp(Magic.data(), Expected, sizeof(Expected)) == 0)
926  return file_magic::windows_resource;
927  // 0x0000 = COFF unknown machine type
928  if (Magic[1] == 0)
929  return file_magic::coff_object;
930  break;
931  }
932  case 0xDE: // 0x0B17C0DE = BC wraper
933  if (Magic[1] == (char)0xC0 && Magic[2] == (char)0x17 &&
934  Magic[3] == (char)0x0B)
935  return file_magic::bitcode;
936  break;
937  case 'B':
938  if (Magic[1] == 'C' && Magic[2] == (char)0xC0 && Magic[3] == (char)0xDE)
939  return file_magic::bitcode;
940  break;
941  case '!':
942  if (Magic.size() >= 8)
943  if (memcmp(Magic.data(),"!<arch>\n",8) == 0)
944  return file_magic::archive;
945  break;
946 
947  case '\177':
948  if (Magic.size() >= 18 && Magic[1] == 'E' && Magic[2] == 'L' &&
949  Magic[3] == 'F') {
950  bool Data2MSB = Magic[5] == 2;
951  unsigned high = Data2MSB ? 16 : 17;
952  unsigned low = Data2MSB ? 17 : 16;
953  if (Magic[high] == 0)
954  switch (Magic[low]) {
955  default: return file_magic::elf;
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  else
962  // It's still some type of ELF file.
963  return file_magic::elf;
964  }
965  break;
966 
967  case 0xCA:
968  if (Magic[1] == char(0xFE) && Magic[2] == char(0xBA) &&
969  Magic[3] == char(0xBE)) {
970  // This is complicated by an overlap with Java class files.
971  // See the Mach-O section in /usr/share/file/magic for details.
972  if (Magic.size() >= 8 && Magic[7] < 43)
973  return file_magic::macho_universal_binary;
974  }
975  break;
976 
977  // The two magic numbers for mach-o are:
978  // 0xfeedface - 32-bit mach-o
979  // 0xfeedfacf - 64-bit mach-o
980  case 0xFE:
981  case 0xCE:
982  case 0xCF: {
983  uint16_t type = 0;
984  if (Magic[0] == char(0xFE) && Magic[1] == char(0xED) &&
985  Magic[2] == char(0xFA) &&
986  (Magic[3] == char(0xCE) || Magic[3] == char(0xCF))) {
987  /* Native endian */
988  if (Magic.size() >= 16) type = Magic[14] << 8 | Magic[15];
989  } else if ((Magic[0] == char(0xCE) || Magic[0] == char(0xCF)) &&
990  Magic[1] == char(0xFA) && Magic[2] == char(0xED) &&
991  Magic[3] == char(0xFE)) {
992  /* Reverse endian */
993  if (Magic.size() >= 14) type = Magic[13] << 8 | Magic[12];
994  }
995  switch (type) {
996  default: break;
997  case 1: return file_magic::macho_object;
998  case 2: return file_magic::macho_executable;
999  case 3: return file_magic::macho_fixed_virtual_memory_shared_lib;
1000  case 4: return file_magic::macho_core;
1001  case 5: return file_magic::macho_preload_executable;
1002  case 6: return file_magic::macho_dynamically_linked_shared_lib;
1003  case 7: return file_magic::macho_dynamic_linker;
1004  case 8: return file_magic::macho_bundle;
1005  case 9: return file_magic::macho_dynamically_linked_shared_lib_stub;
1006  case 10: return file_magic::macho_dsym_companion;
1007  case 11: return file_magic::macho_kext_bundle;
1008  }
1009  break;
1010  }
1011  case 0xF0: // PowerPC Windows
1012  case 0x83: // Alpha 32-bit
1013  case 0x84: // Alpha 64-bit
1014  case 0x66: // MPS R4000 Windows
1015  case 0x50: // mc68K
1016  case 0x4c: // 80386 Windows
1017  case 0xc4: // ARMNT Windows
1018  if (Magic[1] == 0x01)
1019  return file_magic::coff_object;
1020 
1021  case 0x90: // PA-RISC Windows
1022  case 0x68: // mc68K Windows
1023  if (Magic[1] == 0x02)
1024  return file_magic::coff_object;
1025  break;
1026 
1027  case 'M': // Possible MS-DOS stub on Windows PE file
1028  if (Magic[1] == 'Z') {
1029  uint32_t off = read32le(Magic.data() + 0x3c);
1030  // PE/COFF file, either EXE or DLL.
1031  if (off < Magic.size() &&
1032  memcmp(Magic.data()+off, COFF::PEMagic, sizeof(COFF::PEMagic)) == 0)
1033  return file_magic::pecoff_executable;
1034  }
1035  break;
1036 
1037  case 0x64: // x86-64 Windows.
1038  if (Magic[1] == char(0x86))
1039  return file_magic::coff_object;
1040  break;
1041 
1042  default:
1043  break;
1044  }
1045  return file_magic::unknown;
1046 }
1047 
1048 std::error_code identify_magic(const Twine &Path, file_magic &Result) {
1049  int FD;
1050  if (std::error_code EC = openFileForRead(Path, FD))
1051  return EC;
1052 
1053  char Buffer[32];
1054  int Length = read(FD, Buffer, sizeof(Buffer));
1055  if (close(FD) != 0 || Length < 0)
1056  return std::error_code(errno, std::generic_category());
1057 
1058  Result = identify_magic(StringRef(Buffer, Length));
1059  return std::error_code();
1060 }
1061 
1062 std::error_code directory_entry::status(file_status &result) const {
1063  return fs::status(Path, result);
1064 }
1065 
1066 } // end namespace fs
1067 } // end namespace sys
1068 } // end namespace llvm
1069 
1070 // Include the truly platform-specific parts.
1071 #if defined(LLVM_ON_UNIX)
1072 #include "Unix/Path.inc"
1073 #endif
1074 #if defined(LLVM_ON_WIN32)
1075 #include "Windows/Path.inc"
1076 #endif
void toVector(SmallVectorImpl< char > &Out) const
Append the concatenated string into the given SmallString or SmallVector.
Definition: Twine.cpp:26
void push_back(const T &Elt)
Definition: SmallVector.h:222
const_iterator end(StringRef path)
Get end iterator over path.
Definition: Path.cpp:240
bool isSingleStringRef() const
Return true if this twine can be dynamically accessed as a single StringRef value with getSingleStrin...
Definition: Twine.h:405
StringRef root_name(StringRef path)
Get root name.
Definition: Path.cpp:387
StringRef stem(StringRef path)
Get stem.
Definition: Path.cpp:552
size_t size() const
size - Get the string size.
Definition: StringRef.h:113
std::error_code create_directories(const Twine &path, bool IgnoreExisting=true)
Create all the non-existent directories in path.
Definition: Path.cpp:788
value_type read(const void *memory)
Read a value of a particular endianness from memory.
Definition: Endian.h:49
std::error_code createUniqueFile(const Twine &Model, int &ResultFD, SmallVectorImpl< char > &ResultPath, unsigned Mode=all_read|all_write)
Create a uniquely named file.
Definition: Path.cpp:681
F_Excl - When opening a file, this flag makes raw_fd_ostream report an error if the file already exis...
Definition: FileSystem.h:583
bool is_relative(const Twine &path)
Is path relative?
Definition: Path.cpp:664
static std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix, int &ResultFD, llvm::SmallVectorImpl< char > &ResultPath, FSEntity Type)
Definition: Path.cpp:706
void replace_extension(SmallVectorImpl< char > &path, const Twine &extension)
Replace the file extension of path with extension.
Definition: Path.cpp:504
UniqueID getUniqueID() const
bool has_stem(const Twine &path)
Has stem?
Definition: Path.cpp:636
StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition: StringRef.h:405
StringRef root_directory(StringRef path)
Get root directory.
Definition: Path.cpp:409
std::string str() const
str - Get the contents as an std::string.
Definition: StringRef.h:188
std::error_code current_path(SmallVectorImpl< char > &result)
Get the current path.
const_iterator begin(StringRef path)
Get begin iterator over path.
Definition: Path.cpp:232
std::error_code make_absolute(SmallVectorImpl< char > &path)
Make path an absolute path.
Definition: Path.cpp:735
static std::error_code createUniqueEntity(const Twine &Model, int &ResultFD, SmallVectorImpl< char > &ResultPath, bool MakeAbsolute, unsigned Mode, FSEntity Type)
Definition: Path.cpp:160
bool has_root_directory(const Twine &path)
Has root directory?
Definition: Path.cpp:601
file_status - Represents the result of a call to stat and friends.
Definition: FileSystem.h:138
Definition: Path.cpp:155
static const char BigObjMagic[]
Definition: Support/COFF.h:39
bool status_known(file_status s)
Is status available?
Definition: Path.cpp:849
void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
Definition: Path.cpp:443
void remove_filename(SmallVectorImpl< char > &path)
Remove the last component from path unless it is the root dir.
Definition: Path.cpp:498
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:79
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Definition: ErrorHandling.h:98
bool is_absolute(const Twine &path)
Is path absolute?
Definition: Path.cpp:650
StringRef extension(StringRef path)
Get extension.
Definition: Path.cpp:565
bool LLVM_ATTRIBUTE_UNUSED_RESULT empty() const
Definition: SmallVector.h:57
bool is_separator(char value)
Check whether the given char is a path separator on the host OS.
Definition: Path.cpp:578
const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Definition: StringRef.h:107
std::error_code create_directory(const Twine &path, bool IgnoreExisting=true)
Create the directory in path.
static const char preferred_separator_string[]
Definition: Path.cpp:588
StringRef root_path(StringRef path)
Get root path.
Definition: Path.cpp:355
bool has_relative_path(const Twine &path)
Has relative path?
Definition: Path.cpp:615
StringRef getSingleStringRef() const
This returns the twine as a single StringRef.
Definition: Twine.h:438
Open the file for read and write.
Definition: FileSystem.h:595
iterator begin() const
Definition: StringRef.h:90
std::error_code copy_file(const Twine &From, const Twine &To)
Copy the contents of From to To.
Definition: Path.cpp:811
#define P(N)
StringRef filename(StringRef path)
Get filename.
Definition: Path.cpp:548
uint32_t read32le(const void *p)
Definition: Endian.h:212
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:45
void swap(SmallVectorImpl &RHS)
Definition: SmallVector.h:693
bool has_filename(const Twine &path)
Has filename?
Definition: Path.cpp:622
bool is_other(file_status status)
Does this status represent something that exists but is not a directory, regular file, or symlink?
Definition: Path.cpp:877
std::error_code getUniqueID(const Twine Path, UniqueID &Result)
Definition: Path.cpp:672
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
Definition: SmallVector.h:416
bool is_directory(file_status status)
Does status represent a directory?
Definition: Path.cpp:853
static const char *const Magic
Definition: Archive.cpp:26
file_magic identify_magic(StringRef magic)
Identify the type of a binary file based on how magical it is.
Definition: Path.cpp:900
size_t find_last_of(char C, size_t From=npos) const
Find the last character in the string that is C, or npos if not found.
Definition: StringRef.h:301
StringRef relative_path(StringRef path)
Get relative path.
Definition: Path.cpp:438
StringRef toStringRef(SmallVectorImpl< char > &Out) const
This returns the twine as a single StringRef if it can be represented as such.
Definition: Twine.h:454
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:861
std::error_code createUniqueDirectory(const Twine &Prefix, SmallVectorImpl< char > &ResultPath)
Definition: Path.cpp:728
StringRef parent_path(StringRef path)
Get parent path.
Definition: Path.cpp:490
bool is_regular_file(file_status status)
Does status represent a regular file?
Definition: Path.cpp:865
StringRef get_separator()
Return the preferred separator for this platform.
Definition: Path.cpp:590
Path iterator.
Definition: Path.h:50
Reverse path iterator.
Definition: Path.h:77
void write(void *memory, value_type value)
Write a value to memory with a particular endianness.
Definition: Endian.h:73
static unsigned GetRandomNumber()
Get the result of a process wide random number generator.
void set_size(size_type N)
Set the array size to N, which the current array must have enough capacity for.
Definition: SmallVector.h:685
Provides a library for accessing information about this process and other processes on the operating ...
file_magic - An "enum class" enumeration of file types based on magic (the first N bytes of the file)...
Definition: FileSystem.h:224
pointer data()
Return a pointer to the vector's buffer, even if empty().
Definition: SmallVector.h:134
static const size_t npos
Definition: StringRef.h:44
std::error_code openFileForRead(const Twine &Name, int &ResultFD)
uint16_t read16le(const void *p)
Definition: Endian.h:211
reverse_iterator rbegin(StringRef path)
Get reverse begin iterator over path.
Definition: Path.cpp:308
#define I(x, y, z)
Definition: MD5.cpp:54
static const char PEMagic[]
Definition: Support/COFF.h:37
bool has_root_path(const Twine &path)
Has root path?
Definition: Path.cpp:608
bool has_root_name(const Twine &path)
Has root name?
Definition: Path.cpp:594
reverse_iterator rend(StringRef path)
Get reverse end iterator over path.
Definition: Path.cpp:315
size_t find_first_of(char C, size_t From=0) const
Find the first character in the string that is C, or npos if not found.
Definition: StringRef.h:279
void system_temp_directory(bool erasedOnReboot, SmallVectorImpl< char > &result)
Get the typical temporary directory for the system, e.g., "/var/tmp" or "C:/TEMP".
StringRef toNullTerminatedStringRef(SmallVectorImpl< char > &Out) const
This returns the twine as a single null terminated StringRef if it can be represented as such...
Definition: Twine.cpp:31
bool isTriviallyEmpty() const
Check if this twine is trivially empty; a false return value does not necessarily mean the twine is e...
Definition: Twine.h:399
iterator end() const
Definition: StringRef.h:92
bool has_extension(const Twine &path)
Has extension?
Definition: Path.cpp:643
std::error_code access(const Twine &Path, AccessMode Mode)
Can the file be accessed?
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:40
bool operator==(uint64_t V1, const APInt &V2)
Definition: APInt.h:1734
std::error_code status(const Twine &path, file_status &result)
Get file status as if by POSIX stat().
bool exists(file_status status)
Does file exist?
Definition: Path.cpp:845
file_type type() const
Definition: FileSystem.h:196
void operator-(int, ilist_iterator< T >)=delete
bool has_parent_path(const Twine &path)
Has parent path?
Definition: Path.cpp:629
FSEntity
Definition: Path.cpp:154
bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:110
std::error_code openFileForWrite(const Twine &Name, int &ResultFD, OpenFlags Flags, unsigned Mode=0666)