blob: 63ea9119fab5173b11e4b81075a8f031b4af802f [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
Zachary Turner82a0c972017-03-20 23:33:18 +000014#include "llvm/Support/Path.h"
15#include "llvm/ADT/ArrayRef.h"
Rui Ueyama5c69ff52014-09-11 22:34:32 +000016#include "llvm/Support/Endian.h"
Rafael Espindola2a826e42014-06-13 17:20:48 +000017#include "llvm/Support/Errc.h"
Michael J. Spencerebad2f92010-11-29 22:28:51 +000018#include "llvm/Support/ErrorHandling.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/Support/FileSystem.h"
Aaron Ballman07e76182014-02-11 03:40:14 +000020#include "llvm/Support/Process.h"
Rafael Espindola58fe67a2017-11-13 18:33:44 +000021#include "llvm/Support/Signals.h"
Michael J. Spencerebad2f92010-11-29 22:28:51 +000022#include <cctype>
Michael J. Spencer848f46b2010-12-28 01:49:01 +000023#include <cstring>
Rafael Espindola4526b1d2013-06-18 17:01:00 +000024
25#if !defined(_MSC_VER) && !defined(__MINGW32__)
Douglas Gregora86ddf02013-03-21 21:46:10 +000026#include <unistd.h>
Rafael Espindola4526b1d2013-06-18 17:01:00 +000027#else
28#include <io.h>
Douglas Gregora86ddf02013-03-21 21:46:10 +000029#endif
Michael J. Spencerebad2f92010-11-29 22:28:51 +000030
Rafael Espindola7a0b6402014-02-24 03:07:41 +000031using namespace llvm;
Rui Ueyama3206b792015-03-02 21:19:12 +000032using namespace llvm::support::endian;
Rafael Espindola7a0b6402014-02-24 03:07:41 +000033
Michael J. Spencerebad2f92010-11-29 22:28:51 +000034namespace {
35 using llvm::StringRef;
Zhanyong Wan606bb1a2011-02-11 21:24:40 +000036 using llvm::sys::path::is_separator;
Zachary Turner5c5091f2017-03-16 22:28:04 +000037 using llvm::sys::path::Style;
Michael J. Spencerebad2f92010-11-29 22:28:51 +000038
Zachary Turner5c5091f2017-03-16 22:28:04 +000039 inline Style real_style(Style style) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +000040#ifdef LLVM_ON_WIN32
Zachary Turner5c5091f2017-03-16 22:28:04 +000041 return (style == Style::posix) ? Style::posix : Style::windows;
Michael J. Spencerebad2f92010-11-29 22:28:51 +000042#else
Zachary Turner5c5091f2017-03-16 22:28:04 +000043 return (style == Style::windows) ? Style::windows : Style::posix;
Michael J. Spencerebad2f92010-11-29 22:28:51 +000044#endif
Zachary Turner5c5091f2017-03-16 22:28:04 +000045 }
Michael J. Spencerebad2f92010-11-29 22:28:51 +000046
Zachary Turner5c5091f2017-03-16 22:28:04 +000047 inline const char *separators(Style style) {
48 if (real_style(style) == Style::windows)
49 return "\\/";
50 return "/";
51 }
52
53 inline char preferred_separator(Style style) {
54 if (real_style(style) == Style::windows)
55 return '\\';
56 return '/';
57 }
58
59 StringRef find_first_component(StringRef path, Style style) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +000060 // Look for this first component in the following order.
61 // * empty (in this case we return an empty string)
62 // * either C: or {//,\\}net.
63 // * {/,\}
Michael J. Spencerebad2f92010-11-29 22:28:51 +000064 // * {file,directory}name
65
66 if (path.empty())
67 return path;
68
Zachary Turner5c5091f2017-03-16 22:28:04 +000069 if (real_style(style) == Style::windows) {
70 // C:
71 if (path.size() >= 2 &&
72 std::isalpha(static_cast<unsigned char>(path[0])) && path[1] == ':')
73 return path.substr(0, 2);
74 }
Michael J. Spencerebad2f92010-11-29 22:28:51 +000075
76 // //net
Zachary Turner5c5091f2017-03-16 22:28:04 +000077 if ((path.size() > 2) && is_separator(path[0], style) &&
78 path[0] == path[1] && !is_separator(path[2], style)) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +000079 // Find the next directory separator.
Zachary Turner5c5091f2017-03-16 22:28:04 +000080 size_t end = path.find_first_of(separators(style), 2);
Benjamin Kramerffa42ce2010-12-17 20:27:37 +000081 return path.substr(0, end);
Michael J. Spencerebad2f92010-11-29 22:28:51 +000082 }
83
84 // {/,\}
Zachary Turner5c5091f2017-03-16 22:28:04 +000085 if (is_separator(path[0], style))
Benjamin Kramerffa42ce2010-12-17 20:27:37 +000086 return path.substr(0, 1);
Michael J. Spencerebad2f92010-11-29 22:28:51 +000087
Michael J. Spencerebad2f92010-11-29 22:28:51 +000088 // * {file,directory}name
Zachary Turner5c5091f2017-03-16 22:28:04 +000089 size_t end = path.find_first_of(separators(style));
Benjamin Kramerffa42ce2010-12-17 20:27:37 +000090 return path.substr(0, end);
Michael J. Spencerebad2f92010-11-29 22:28:51 +000091 }
Michael J. Spencer545cbdf2010-11-30 23:28:07 +000092
Zachary Turner5c5091f2017-03-16 22:28:04 +000093 size_t filename_pos(StringRef str, Style style) {
94 if (str.size() == 2 && is_separator(str[0], style) && str[0] == str[1])
Michael J. Spencer545cbdf2010-11-30 23:28:07 +000095 return 0;
96
Zachary Turner5c5091f2017-03-16 22:28:04 +000097 if (str.size() > 0 && is_separator(str[str.size() - 1], style))
Michael J. Spencer545cbdf2010-11-30 23:28:07 +000098 return str.size() - 1;
99
Zachary Turner5c5091f2017-03-16 22:28:04 +0000100 size_t pos = str.find_last_of(separators(style), str.size() - 1);
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000101
Zachary Turner5c5091f2017-03-16 22:28:04 +0000102 if (real_style(style) == Style::windows) {
103 if (pos == StringRef::npos)
104 pos = str.find_last_of(':', str.size() - 2);
105 }
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000106
Zachary Turner5c5091f2017-03-16 22:28:04 +0000107 if (pos == StringRef::npos || (pos == 1 && is_separator(str[0], style)))
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000108 return 0;
109
110 return pos + 1;
111 }
112
Zachary Turner5c5091f2017-03-16 22:28:04 +0000113 size_t root_dir_start(StringRef str, Style style) {
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000114 // case "c:/"
Zachary Turner5c5091f2017-03-16 22:28:04 +0000115 if (real_style(style) == Style::windows) {
116 if (str.size() > 2 && str[1] == ':' && is_separator(str[2], style))
117 return 2;
118 }
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000119
120 // case "//"
Zachary Turner5c5091f2017-03-16 22:28:04 +0000121 if (str.size() == 2 && is_separator(str[0], style) && str[0] == str[1])
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000122 return StringRef::npos;
123
124 // case "//net"
Zachary Turner5c5091f2017-03-16 22:28:04 +0000125 if (str.size() > 3 && is_separator(str[0], style) && str[0] == str[1] &&
126 !is_separator(str[2], style)) {
127 return str.find_first_of(separators(style), 2);
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000128 }
129
130 // case "/"
Zachary Turner5c5091f2017-03-16 22:28:04 +0000131 if (str.size() > 0 && is_separator(str[0], style))
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000132 return 0;
133
134 return StringRef::npos;
135 }
136
Zachary Turner5c5091f2017-03-16 22:28:04 +0000137 size_t parent_path_end(StringRef path, Style style) {
138 size_t end_pos = filename_pos(path, style);
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000139
Zachary Turner5c5091f2017-03-16 22:28:04 +0000140 bool filename_was_sep =
141 path.size() > 0 && is_separator(path[end_pos], style);
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000142
143 // Skip separators except for root dir.
Zachary Turner5c5091f2017-03-16 22:28:04 +0000144 size_t root_dir_pos = root_dir_start(path.substr(0, end_pos), style);
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000145
Zachary Turner5c5091f2017-03-16 22:28:04 +0000146 while (end_pos > 0 && (end_pos - 1) != root_dir_pos &&
147 is_separator(path[end_pos - 1], style))
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000148 --end_pos;
149
150 if (end_pos == 1 && root_dir_pos == 0 && filename_was_sep)
151 return StringRef::npos;
152
153 return end_pos;
154 }
Zhanyong Wan606bb1a2011-02-11 21:24:40 +0000155} // end unnamed namespace
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000156
Rafael Espindolae79a8722013-06-28 03:48:47 +0000157enum FSEntity {
158 FS_Dir,
159 FS_File,
160 FS_Name
161};
162
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000163static std::error_code createUniqueEntity(const Twine &Model, int &ResultFD,
164 SmallVectorImpl<char> &ResultPath,
165 bool MakeAbsolute, unsigned Mode,
166 FSEntity Type) {
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000167 SmallString<128> ModelStorage;
168 Model.toVector(ModelStorage);
169
170 if (MakeAbsolute) {
171 // Make model absolute by prepending a temp directory if it's not already.
172 if (!sys::path::is_absolute(Twine(ModelStorage))) {
173 SmallString<128> TDir;
Rafael Espindola016a6d52014-08-26 14:47:52 +0000174 sys::path::system_temp_directory(true, TDir);
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000175 sys::path::append(TDir, Twine(ModelStorage));
176 ModelStorage.swap(TDir);
177 }
178 }
179
180 // From here on, DO NOT modify model. It may be needed if the randomly chosen
181 // path already exists.
182 ResultPath = ModelStorage;
183 // Null terminate.
184 ResultPath.push_back(0);
185 ResultPath.pop_back();
186
187retry_random_path:
188 // Replace '%' with random chars.
189 for (unsigned i = 0, e = ModelStorage.size(); i != e; ++i) {
190 if (ModelStorage[i] == '%')
191 ResultPath[i] = "0123456789abcdef"[sys::Process::GetRandomNumber() & 15];
192 }
193
194 // Try to open + create the file.
195 switch (Type) {
196 case FS_File: {
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000197 if (std::error_code EC =
Rafael Espindola90c7f1c2014-02-24 18:20:12 +0000198 sys::fs::openFileForWrite(Twine(ResultPath.begin()), ResultFD,
199 sys::fs::F_RW | sys::fs::F_Excl, Mode)) {
Rafael Espindola2a826e42014-06-13 17:20:48 +0000200 if (EC == errc::file_exists)
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000201 goto retry_random_path;
202 return EC;
203 }
204
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000205 return std::error_code();
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000206 }
207
208 case FS_Name: {
Rafael Espindola281f23a2014-09-11 20:30:02 +0000209 std::error_code EC =
210 sys::fs::access(ResultPath.begin(), sys::fs::AccessMode::Exist);
211 if (EC == errc::no_such_file_or_directory)
212 return std::error_code();
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000213 if (EC)
214 return EC;
Rafael Espindola281f23a2014-09-11 20:30:02 +0000215 goto retry_random_path;
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000216 }
217
218 case FS_Dir: {
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000219 if (std::error_code EC =
220 sys::fs::create_directory(ResultPath.begin(), false)) {
Rafael Espindola2a826e42014-06-13 17:20:48 +0000221 if (EC == errc::file_exists)
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000222 goto retry_random_path;
223 return EC;
224 }
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000225 return std::error_code();
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000226 }
227 }
228 llvm_unreachable("Invalid Type");
229}
Rafael Espindolae79a8722013-06-28 03:48:47 +0000230
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000231namespace llvm {
232namespace sys {
233namespace path {
234
Zachary Turner5c5091f2017-03-16 22:28:04 +0000235const_iterator begin(StringRef path, Style style) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000236 const_iterator i;
237 i.Path = path;
Zachary Turner5c5091f2017-03-16 22:28:04 +0000238 i.Component = find_first_component(path, style);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000239 i.Position = 0;
Zachary Turner5c5091f2017-03-16 22:28:04 +0000240 i.S = style;
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000241 return i;
242}
243
Benjamin Kramer292b44b2010-12-17 18:19:06 +0000244const_iterator end(StringRef path) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000245 const_iterator i;
246 i.Path = path;
247 i.Position = path.size();
248 return i;
249}
250
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000251const_iterator &const_iterator::operator++() {
252 assert(Position < Path.size() && "Tried to increment past end!");
253
254 // Increment Position to past the current component
255 Position += Component.size();
256
257 // Check for end.
258 if (Position == Path.size()) {
259 Component = StringRef();
260 return *this;
261 }
262
263 // Both POSIX and Windows treat paths that begin with exactly two separators
264 // specially.
Zachary Turner5c5091f2017-03-16 22:28:04 +0000265 bool was_net = Component.size() > 2 && is_separator(Component[0], S) &&
266 Component[1] == Component[0] && !is_separator(Component[2], S);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000267
268 // Handle separators.
Zachary Turner5c5091f2017-03-16 22:28:04 +0000269 if (is_separator(Path[Position], S)) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000270 // Root dir.
Zachary Turner5c5091f2017-03-16 22:28:04 +0000271 if (was_net ||
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000272 // c:/
Zachary Turner5c5091f2017-03-16 22:28:04 +0000273 (real_style(S) == Style::windows && Component.endswith(":"))) {
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000274 Component = Path.substr(Position, 1);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000275 return *this;
276 }
277
278 // Skip extra separators.
Zachary Turner5c5091f2017-03-16 22:28:04 +0000279 while (Position != Path.size() && is_separator(Path[Position], S)) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000280 ++Position;
281 }
282
283 // Treat trailing '/' as a '.'.
284 if (Position == Path.size()) {
285 --Position;
286 Component = ".";
287 return *this;
288 }
289 }
290
291 // Find next component.
Zachary Turner5c5091f2017-03-16 22:28:04 +0000292 size_t end_pos = Path.find_first_of(separators(S), Position);
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000293 Component = Path.slice(Position, end_pos);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000294
295 return *this;
296}
297
Justin Bogner487e7642014-08-04 17:36:41 +0000298bool const_iterator::operator==(const const_iterator &RHS) const {
299 return Path.begin() == RHS.Path.begin() && Position == RHS.Position;
300}
301
302ptrdiff_t const_iterator::operator-(const const_iterator &RHS) const {
303 return Position - RHS.Position;
304}
305
Zachary Turner5c5091f2017-03-16 22:28:04 +0000306reverse_iterator rbegin(StringRef Path, Style style) {
Justin Bogner487e7642014-08-04 17:36:41 +0000307 reverse_iterator I;
308 I.Path = Path;
309 I.Position = Path.size();
Zachary Turner5c5091f2017-03-16 22:28:04 +0000310 I.S = style;
Justin Bogner487e7642014-08-04 17:36:41 +0000311 return ++I;
312}
313
314reverse_iterator rend(StringRef Path) {
315 reverse_iterator I;
316 I.Path = Path;
317 I.Component = Path.substr(0, 0);
318 I.Position = 0;
319 return I;
320}
321
322reverse_iterator &reverse_iterator::operator++() {
Ben Langmuir8d116392014-03-05 19:56:30 +0000323 // If we're at the end and the previous char was a '/', return '.' unless
324 // we are the root path.
Zachary Turner5c5091f2017-03-16 22:28:04 +0000325 size_t root_dir_pos = root_dir_start(Path, S);
326 if (Position == Path.size() && Path.size() > root_dir_pos + 1 &&
327 is_separator(Path[Position - 1], S)) {
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000328 --Position;
329 Component = ".";
330 return *this;
331 }
332
333 // Skip separators unless it's the root directory.
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000334 size_t end_pos = Position;
335
Zachary Turner5c5091f2017-03-16 22:28:04 +0000336 while (end_pos > 0 && (end_pos - 1) != root_dir_pos &&
337 is_separator(Path[end_pos - 1], S))
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000338 --end_pos;
339
340 // Find next separator.
Zachary Turner5c5091f2017-03-16 22:28:04 +0000341 size_t start_pos = filename_pos(Path.substr(0, end_pos), S);
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000342 Component = Path.slice(start_pos, end_pos);
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000343 Position = start_pos;
344 return *this;
345}
346
Justin Bogner487e7642014-08-04 17:36:41 +0000347bool reverse_iterator::operator==(const reverse_iterator &RHS) const {
348 return Path.begin() == RHS.Path.begin() && Component == RHS.Component &&
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000349 Position == RHS.Position;
350}
351
Filipe Cabecinhas78949382016-04-29 16:48:07 +0000352ptrdiff_t reverse_iterator::operator-(const reverse_iterator &RHS) const {
353 return Position - RHS.Position;
354}
355
Zachary Turner5c5091f2017-03-16 22:28:04 +0000356StringRef root_path(StringRef path, Style style) {
357 const_iterator b = begin(path, style), pos = b, e = end(path);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000358 if (b != e) {
Zachary Turner5c5091f2017-03-16 22:28:04 +0000359 bool has_net =
360 b->size() > 2 && is_separator((*b)[0], style) && (*b)[1] == (*b)[0];
361 bool has_drive = (real_style(style) == Style::windows) && b->endswith(":");
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000362
363 if (has_net || has_drive) {
Zachary Turner5c5091f2017-03-16 22:28:04 +0000364 if ((++pos != e) && is_separator((*pos)[0], style)) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000365 // {C:/,//net/}, so get the first two components.
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000366 return path.substr(0, b->size() + pos->size());
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000367 } else {
368 // just {C:,//net}, return the first component.
Michael J. Spencerf616b212010-12-07 17:04:04 +0000369 return *b;
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000370 }
371 }
372
373 // POSIX style root directory.
Zachary Turner5c5091f2017-03-16 22:28:04 +0000374 if (is_separator((*b)[0], style)) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000375 return *b;
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000376 }
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000377 }
378
Michael J. Spencerf616b212010-12-07 17:04:04 +0000379 return StringRef();
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000380}
381
Zachary Turner5c5091f2017-03-16 22:28:04 +0000382StringRef root_name(StringRef path, Style style) {
383 const_iterator b = begin(path, style), e = end(path);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000384 if (b != e) {
Zachary Turner5c5091f2017-03-16 22:28:04 +0000385 bool has_net =
386 b->size() > 2 && is_separator((*b)[0], style) && (*b)[1] == (*b)[0];
387 bool has_drive = (real_style(style) == Style::windows) && b->endswith(":");
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000388
389 if (has_net || has_drive) {
390 // just {C:,//net}, return the first component.
Michael J. Spencerf616b212010-12-07 17:04:04 +0000391 return *b;
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000392 }
393 }
394
395 // No path or no name.
Michael J. Spencerf616b212010-12-07 17:04:04 +0000396 return StringRef();
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000397}
398
Zachary Turner5c5091f2017-03-16 22:28:04 +0000399StringRef root_directory(StringRef path, Style style) {
400 const_iterator b = begin(path, style), pos = b, e = end(path);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000401 if (b != e) {
Zachary Turner5c5091f2017-03-16 22:28:04 +0000402 bool has_net =
403 b->size() > 2 && is_separator((*b)[0], style) && (*b)[1] == (*b)[0];
404 bool has_drive = (real_style(style) == Style::windows) && b->endswith(":");
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000405
406 if ((has_net || has_drive) &&
407 // {C:,//net}, skip to the next component.
Zachary Turner5c5091f2017-03-16 22:28:04 +0000408 (++pos != e) && is_separator((*pos)[0], style)) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000409 return *pos;
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000410 }
411
412 // POSIX style root directory.
Zachary Turner5c5091f2017-03-16 22:28:04 +0000413 if (!has_net && is_separator((*b)[0], style)) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000414 return *b;
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000415 }
416 }
417
418 // No path or no root.
Michael J. Spencerf616b212010-12-07 17:04:04 +0000419 return StringRef();
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000420}
421
Zachary Turner5c5091f2017-03-16 22:28:04 +0000422StringRef relative_path(StringRef path, Style style) {
423 StringRef root = root_path(path, style);
Michael J. Spencere6462392012-02-29 00:06:24 +0000424 return path.substr(root.size());
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000425}
426
Zachary Turner5c5091f2017-03-16 22:28:04 +0000427void append(SmallVectorImpl<char> &path, Style style, const Twine &a,
428 const Twine &b, const Twine &c, const Twine &d) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000429 SmallString<32> a_storage;
430 SmallString<32> b_storage;
431 SmallString<32> c_storage;
432 SmallString<32> d_storage;
433
434 SmallVector<StringRef, 4> components;
435 if (!a.isTriviallyEmpty()) components.push_back(a.toStringRef(a_storage));
436 if (!b.isTriviallyEmpty()) components.push_back(b.toStringRef(b_storage));
437 if (!c.isTriviallyEmpty()) components.push_back(c.toStringRef(c_storage));
438 if (!d.isTriviallyEmpty()) components.push_back(d.toStringRef(d_storage));
439
Pawel Bylica64d08ff2015-10-22 08:12:15 +0000440 for (auto &component : components) {
Zachary Turner5c5091f2017-03-16 22:28:04 +0000441 bool path_has_sep =
442 !path.empty() && is_separator(path[path.size() - 1], style);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000443 if (path_has_sep) {
444 // Strip separators from beginning of component.
Zachary Turner5c5091f2017-03-16 22:28:04 +0000445 size_t loc = component.find_first_not_of(separators(style));
Pawel Bylica64d08ff2015-10-22 08:12:15 +0000446 StringRef c = component.substr(loc);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000447
448 // Append it.
449 path.append(c.begin(), c.end());
450 continue;
451 }
452
Benjamin Kramer324d96b2017-08-09 22:06:32 +0000453 bool component_has_sep =
454 !component.empty() && is_separator(component[0], style);
455 if (!component_has_sep &&
456 !(path.empty() || has_root_name(component, style))) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000457 // Add a separator.
Zachary Turner5c5091f2017-03-16 22:28:04 +0000458 path.push_back(preferred_separator(style));
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000459 }
460
Pawel Bylica64d08ff2015-10-22 08:12:15 +0000461 path.append(component.begin(), component.end());
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000462 }
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000463}
464
Zachary Turner5c5091f2017-03-16 22:28:04 +0000465void append(SmallVectorImpl<char> &path, const Twine &a, const Twine &b,
466 const Twine &c, const Twine &d) {
467 append(path, Style::native, a, b, c, d);
Argyrios Kyrtzidisa61736f2011-02-15 17:51:19 +0000468}
469
Zachary Turner5c5091f2017-03-16 22:28:04 +0000470void append(SmallVectorImpl<char> &path, const_iterator begin,
471 const_iterator end, Style style) {
472 for (; begin != end; ++begin)
473 path::append(path, style, *begin);
474}
475
476StringRef parent_path(StringRef path, Style style) {
477 size_t end_pos = parent_path_end(path, style);
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000478 if (end_pos == StringRef::npos)
Michael J. Spencerf616b212010-12-07 17:04:04 +0000479 return StringRef();
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000480 else
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000481 return path.substr(0, end_pos);
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000482}
483
Zachary Turner5c5091f2017-03-16 22:28:04 +0000484void remove_filename(SmallVectorImpl<char> &path, Style style) {
485 size_t end_pos = parent_path_end(StringRef(path.begin(), path.size()), style);
Michael J. Spencer1e090f02010-12-07 03:57:37 +0000486 if (end_pos != StringRef::npos)
487 path.set_size(end_pos);
Michael J. Spencer9c594092010-12-01 00:52:28 +0000488}
489
Zachary Turner5c5091f2017-03-16 22:28:04 +0000490void replace_extension(SmallVectorImpl<char> &path, const Twine &extension,
491 Style style) {
Michael J. Spencerfb3a95d2010-12-01 00:52:55 +0000492 StringRef p(path.begin(), path.size());
493 SmallString<32> ext_storage;
494 StringRef ext = extension.toStringRef(ext_storage);
495
496 // Erase existing extension.
497 size_t pos = p.find_last_of('.');
Zachary Turner5c5091f2017-03-16 22:28:04 +0000498 if (pos != StringRef::npos && pos >= filename_pos(p, style))
Michael J. Spencerfb3a95d2010-12-01 00:52:55 +0000499 path.set_size(pos);
500
501 // Append '.' if needed.
502 if (ext.size() > 0 && ext[0] != '.')
503 path.push_back('.');
504
505 // Append extension.
506 path.append(ext.begin(), ext.end());
Michael J. Spencerfb3a95d2010-12-01 00:52:55 +0000507}
508
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000509void replace_path_prefix(SmallVectorImpl<char> &Path,
Zachary Turner5c5091f2017-03-16 22:28:04 +0000510 const StringRef &OldPrefix, const StringRef &NewPrefix,
511 Style style) {
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000512 if (OldPrefix.empty() && NewPrefix.empty())
513 return;
514
515 StringRef OrigPath(Path.begin(), Path.size());
516 if (!OrigPath.startswith(OldPrefix))
517 return;
518
519 // If prefixes have the same size we can simply copy the new one over.
520 if (OldPrefix.size() == NewPrefix.size()) {
521 std::copy(NewPrefix.begin(), NewPrefix.end(), Path.begin());
522 return;
523 }
524
525 StringRef RelPath = OrigPath.substr(OldPrefix.size());
526 SmallString<256> NewPath;
Zachary Turner5c5091f2017-03-16 22:28:04 +0000527 path::append(NewPath, style, NewPrefix);
528 path::append(NewPath, style, RelPath);
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000529 Path.swap(NewPath);
530}
531
Zachary Turner5c5091f2017-03-16 22:28:04 +0000532void native(const Twine &path, SmallVectorImpl<char> &result, Style style) {
Benjamin Kramerbd4ac9b2013-09-11 10:45:21 +0000533 assert((!path.isSingleStringRef() ||
534 path.getSingleStringRef().data() != result.data()) &&
535 "path and result are not allowed to overlap!");
Michael J. Spencer80025002010-12-01 02:48:27 +0000536 // Clear result.
Michael J. Spencer98c7a112010-12-07 01:23:19 +0000537 result.clear();
Michael J. Spencer80025002010-12-01 02:48:27 +0000538 path.toVector(result);
Zachary Turner5c5091f2017-03-16 22:28:04 +0000539 native(result, style);
Benjamin Kramerbd4ac9b2013-09-11 10:45:21 +0000540}
541
Zachary Turner5c5091f2017-03-16 22:28:04 +0000542void native(SmallVectorImpl<char> &Path, Style style) {
Serge Pavlov9c761a32017-03-01 09:38:15 +0000543 if (Path.empty())
544 return;
Zachary Turner5c5091f2017-03-16 22:28:04 +0000545 if (real_style(style) == Style::windows) {
546 std::replace(Path.begin(), Path.end(), '/', '\\');
547 if (Path[0] == '~' && (Path.size() == 1 || is_separator(Path[1], style))) {
548 SmallString<128> PathHome;
549 home_directory(PathHome);
550 PathHome.append(Path.begin() + 1, Path.end());
551 Path = PathHome;
552 }
553 } else {
554 for (auto PI = Path.begin(), PE = Path.end(); PI < PE; ++PI) {
555 if (*PI == '\\') {
556 auto PN = PI + 1;
557 if (PN < PE && *PN == '\\')
558 ++PI; // increment once, the for loop will move over the escaped slash
559 else
560 *PI = '/';
561 }
Rafael Espindolad649b9d2014-08-08 21:29:34 +0000562 }
563 }
Michael J. Spencer80025002010-12-01 02:48:27 +0000564}
565
Zachary Turner5c5091f2017-03-16 22:28:04 +0000566std::string convert_to_slash(StringRef path, Style style) {
567 if (real_style(style) != Style::windows)
568 return path;
569
Rui Ueyama3e649032017-01-09 01:47:15 +0000570 std::string s = path.str();
571 std::replace(s.begin(), s.end(), '\\', '/');
572 return s;
Rui Ueyama3e649032017-01-09 01:47:15 +0000573}
574
Zachary Turner5c5091f2017-03-16 22:28:04 +0000575StringRef filename(StringRef path, Style style) { return *rbegin(path, style); }
Michael J. Spencer14269202010-12-01 03:18:17 +0000576
Zachary Turner5c5091f2017-03-16 22:28:04 +0000577StringRef stem(StringRef path, Style style) {
578 StringRef fname = filename(path, style);
Michael J. Spencer956955e2010-12-01 03:18:33 +0000579 size_t pos = fname.find_last_of('.');
580 if (pos == StringRef::npos)
Michael J. Spencerf616b212010-12-07 17:04:04 +0000581 return fname;
Michael J. Spencer956955e2010-12-01 03:18:33 +0000582 else
583 if ((fname.size() == 1 && fname == ".") ||
584 (fname.size() == 2 && fname == ".."))
Michael J. Spencerf616b212010-12-07 17:04:04 +0000585 return fname;
Michael J. Spencer956955e2010-12-01 03:18:33 +0000586 else
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000587 return fname.substr(0, pos);
Michael J. Spencer956955e2010-12-01 03:18:33 +0000588}
589
Zachary Turner5c5091f2017-03-16 22:28:04 +0000590StringRef extension(StringRef path, Style style) {
591 StringRef fname = filename(path, style);
Michael J. Spencer87106c52010-12-01 03:37:41 +0000592 size_t pos = fname.find_last_of('.');
593 if (pos == StringRef::npos)
Michael J. Spencerf616b212010-12-07 17:04:04 +0000594 return StringRef();
Michael J. Spencer87106c52010-12-01 03:37:41 +0000595 else
596 if ((fname.size() == 1 && fname == ".") ||
597 (fname.size() == 2 && fname == ".."))
Michael J. Spencerf616b212010-12-07 17:04:04 +0000598 return StringRef();
Michael J. Spencer87106c52010-12-01 03:37:41 +0000599 else
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000600 return fname.substr(pos);
Michael J. Spencer87106c52010-12-01 03:37:41 +0000601}
602
Zachary Turner5c5091f2017-03-16 22:28:04 +0000603bool is_separator(char value, Style style) {
604 if (value == '/')
605 return true;
606 if (real_style(style) == Style::windows)
607 return value == '\\';
608 return false;
Zhanyong Wan606bb1a2011-02-11 21:24:40 +0000609}
610
Zachary Turner5c5091f2017-03-16 22:28:04 +0000611StringRef get_separator(Style style) {
612 if (real_style(style) == Style::windows)
613 return "\\";
614 return "/";
Yaron Keren15217202014-05-16 13:16:30 +0000615}
616
Zachary Turner5c5091f2017-03-16 22:28:04 +0000617bool has_root_name(const Twine &path, Style style) {
Michael J. Spencer112a7692010-12-01 06:03:50 +0000618 SmallString<128> path_storage;
619 StringRef p = path.toStringRef(path_storage);
620
Zachary Turner5c5091f2017-03-16 22:28:04 +0000621 return !root_name(p, style).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000622}
623
Zachary Turner5c5091f2017-03-16 22:28:04 +0000624bool has_root_directory(const Twine &path, Style style) {
Michael J. Spencer112a7692010-12-01 06:03:50 +0000625 SmallString<128> path_storage;
626 StringRef p = path.toStringRef(path_storage);
627
Zachary Turner5c5091f2017-03-16 22:28:04 +0000628 return !root_directory(p, style).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000629}
630
Zachary Turner5c5091f2017-03-16 22:28:04 +0000631bool has_root_path(const Twine &path, Style style) {
Michael J. Spencer112a7692010-12-01 06:03:50 +0000632 SmallString<128> path_storage;
633 StringRef p = path.toStringRef(path_storage);
634
Zachary Turner5c5091f2017-03-16 22:28:04 +0000635 return !root_path(p, style).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000636}
637
Zachary Turner5c5091f2017-03-16 22:28:04 +0000638bool has_relative_path(const Twine &path, Style style) {
Michael J. Spencer6d4b7e72010-12-20 13:30:28 +0000639 SmallString<128> path_storage;
640 StringRef p = path.toStringRef(path_storage);
641
Zachary Turner5c5091f2017-03-16 22:28:04 +0000642 return !relative_path(p, style).empty();
Michael J. Spencer6d4b7e72010-12-20 13:30:28 +0000643}
644
Zachary Turner5c5091f2017-03-16 22:28:04 +0000645bool has_filename(const Twine &path, Style style) {
Michael J. Spencer112a7692010-12-01 06:03:50 +0000646 SmallString<128> path_storage;
647 StringRef p = path.toStringRef(path_storage);
648
Zachary Turner5c5091f2017-03-16 22:28:04 +0000649 return !filename(p, style).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000650}
651
Zachary Turner5c5091f2017-03-16 22:28:04 +0000652bool has_parent_path(const Twine &path, Style style) {
Michael J. Spencer112a7692010-12-01 06:03:50 +0000653 SmallString<128> path_storage;
654 StringRef p = path.toStringRef(path_storage);
655
Zachary Turner5c5091f2017-03-16 22:28:04 +0000656 return !parent_path(p, style).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000657}
658
Zachary Turner5c5091f2017-03-16 22:28:04 +0000659bool has_stem(const Twine &path, Style style) {
Michael J. Spencer112a7692010-12-01 06:03:50 +0000660 SmallString<128> path_storage;
661 StringRef p = path.toStringRef(path_storage);
662
Zachary Turner5c5091f2017-03-16 22:28:04 +0000663 return !stem(p, style).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000664}
665
Zachary Turner5c5091f2017-03-16 22:28:04 +0000666bool has_extension(const Twine &path, Style style) {
Michael J. Spencer112a7692010-12-01 06:03:50 +0000667 SmallString<128> path_storage;
668 StringRef p = path.toStringRef(path_storage);
669
Zachary Turner5c5091f2017-03-16 22:28:04 +0000670 return !extension(p, style).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000671}
672
Zachary Turner5c5091f2017-03-16 22:28:04 +0000673bool is_absolute(const Twine &path, Style style) {
Michael J. Spencera72df5f2010-12-01 06:21:53 +0000674 SmallString<128> path_storage;
675 StringRef p = path.toStringRef(path_storage);
676
Zachary Turner5c5091f2017-03-16 22:28:04 +0000677 bool rootDir = has_root_directory(p, style);
678 bool rootName =
679 (real_style(style) != Style::windows) || has_root_name(p, style);
Michael J. Spencera72df5f2010-12-01 06:21:53 +0000680
Michael J. Spencerf616b212010-12-07 17:04:04 +0000681 return rootDir && rootName;
Michael J. Spencera72df5f2010-12-01 06:21:53 +0000682}
683
Zachary Turner5c5091f2017-03-16 22:28:04 +0000684bool is_relative(const Twine &path, Style style) {
685 return !is_absolute(path, style);
686}
Douglas Katzmana26be4a2015-09-02 21:02:10 +0000687
Zachary Turner5c5091f2017-03-16 22:28:04 +0000688StringRef remove_leading_dotslash(StringRef Path, Style style) {
Douglas Katzmana26be4a2015-09-02 21:02:10 +0000689 // Remove leading "./" (or ".//" or "././" etc.)
Zachary Turner5c5091f2017-03-16 22:28:04 +0000690 while (Path.size() > 2 && Path[0] == '.' && is_separator(Path[1], style)) {
Douglas Katzmana26be4a2015-09-02 21:02:10 +0000691 Path = Path.substr(2);
Zachary Turner5c5091f2017-03-16 22:28:04 +0000692 while (Path.size() > 0 && is_separator(Path[0], style))
Douglas Katzmana26be4a2015-09-02 21:02:10 +0000693 Path = Path.substr(1);
694 }
695 return Path;
Michael J. Spencera72df5f2010-12-01 06:21:53 +0000696}
697
Zachary Turner5c5091f2017-03-16 22:28:04 +0000698static SmallString<256> remove_dots(StringRef path, bool remove_dot_dot,
699 Style style) {
Mike Aizatsky662b4fd2015-11-09 18:56:31 +0000700 SmallVector<StringRef, 16> components;
701
702 // Skip the root path, then look for traversal in the components.
Zachary Turner5c5091f2017-03-16 22:28:04 +0000703 StringRef rel = path::relative_path(path, style);
704 for (StringRef C :
705 llvm::make_range(path::begin(rel, style), path::end(rel))) {
Mike Aizatsky662b4fd2015-11-09 18:56:31 +0000706 if (C == ".")
707 continue;
Benjamin Kramer937dd7a2016-10-17 13:28:21 +0000708 // Leading ".." will remain in the path unless it's at the root.
709 if (remove_dot_dot && C == "..") {
710 if (!components.empty() && components.back() != "..") {
711 components.pop_back();
712 continue;
713 }
Zachary Turner5c5091f2017-03-16 22:28:04 +0000714 if (path::is_absolute(path, style))
Benjamin Kramer937dd7a2016-10-17 13:28:21 +0000715 continue;
Mike Aizatsky662b4fd2015-11-09 18:56:31 +0000716 }
717 components.push_back(C);
718 }
719
Zachary Turner5c5091f2017-03-16 22:28:04 +0000720 SmallString<256> buffer = path::root_path(path, style);
Mike Aizatsky662b4fd2015-11-09 18:56:31 +0000721 for (StringRef C : components)
Zachary Turner5c5091f2017-03-16 22:28:04 +0000722 path::append(buffer, style, C);
Mike Aizatsky662b4fd2015-11-09 18:56:31 +0000723 return buffer;
724}
725
Zachary Turner5c5091f2017-03-16 22:28:04 +0000726bool remove_dots(SmallVectorImpl<char> &path, bool remove_dot_dot,
727 Style style) {
Mike Aizatsky662b4fd2015-11-09 18:56:31 +0000728 StringRef p(path.data(), path.size());
729
Zachary Turner5c5091f2017-03-16 22:28:04 +0000730 SmallString<256> result = remove_dots(p, remove_dot_dot, style);
Mike Aizatsky662b4fd2015-11-09 18:56:31 +0000731 if (result == path)
732 return false;
733
734 path.swap(result);
735 return true;
736}
737
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +0000738} // end namespace path
739
740namespace fs {
741
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000742std::error_code getUniqueID(const Twine Path, UniqueID &Result) {
Rafael Espindola7f822a92013-07-29 21:26:49 +0000743 file_status Status;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000744 std::error_code EC = status(Path, Status);
Rafael Espindola7f822a92013-07-29 21:26:49 +0000745 if (EC)
746 return EC;
747 Result = Status.getUniqueID();
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000748 return std::error_code();
Rafael Espindola7f822a92013-07-29 21:26:49 +0000749}
750
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000751std::error_code createUniqueFile(const Twine &Model, int &ResultFd,
752 SmallVectorImpl<char> &ResultPath,
753 unsigned Mode) {
Rafael Espindolac9d2e5b2013-07-05 21:01:08 +0000754 return createUniqueEntity(Model, ResultFd, ResultPath, false, Mode, FS_File);
755}
756
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000757std::error_code createUniqueFile(const Twine &Model,
758 SmallVectorImpl<char> &ResultPath) {
Rafael Espindolac9d2e5b2013-07-05 21:01:08 +0000759 int Dummy;
760 return createUniqueEntity(Model, Dummy, ResultPath, false, 0, FS_Name);
761}
762
Rafael Espindola58fe67a2017-11-13 18:33:44 +0000763TempFile::TempFile(StringRef Name, int FD) : TmpName(Name), FD(FD) {}
Rafael Espindolae4115192017-11-14 00:31:28 +0000764TempFile::TempFile(TempFile &&Other) { *this = std::move(Other); }
765TempFile &TempFile::operator=(TempFile &&Other) {
Rafael Espindola58fe67a2017-11-13 18:33:44 +0000766 TmpName = std::move(Other.TmpName);
767 FD = Other.FD;
768 Other.Done = true;
Rafael Espindolae4115192017-11-14 00:31:28 +0000769 return *this;
Rafael Espindola58fe67a2017-11-13 18:33:44 +0000770}
771
772TempFile::~TempFile() { assert(Done); }
773
774Error TempFile::discard() {
775 if (Done)
776 return Error::success();
777 Done = true;
778 // Always try to close and remove.
779 std::error_code RemoveEC = fs::remove(TmpName);
780 sys::DontRemoveFileOnSignal(TmpName);
781 if (close(FD) == -1) {
782 std::error_code EC = std::error_code(errno, std::generic_category());
783 return errorCodeToError(EC);
784 }
785 return errorCodeToError(RemoveEC);
786}
787
788Error TempFile::keep(const Twine &Name) {
789 assert(!Done);
790 Done = true;
791 // Always try to close and rename.
792 std::error_code RenameEC = fs::rename(TmpName, Name);
793 sys::DontRemoveFileOnSignal(TmpName);
794 if (close(FD) == -1) {
795 std::error_code EC(errno, std::generic_category());
796 return errorCodeToError(EC);
797 }
798 return errorCodeToError(RenameEC);
799}
800
801Expected<TempFile> TempFile::create(const Twine &Model, unsigned Mode) {
802 int FD;
803 SmallString<128> ResultPath;
804 if (std::error_code EC = createUniqueFile(Model, FD, ResultPath, Mode))
805 return errorCodeToError(EC);
806
807 // Make sure we delete the file when RemoveFileOnSignal fails.
808 TempFile Ret(ResultPath, FD);
809 if (sys::RemoveFileOnSignal(ResultPath)) {
810 consumeError(Ret.discard());
811 std::error_code EC(errc::operation_not_permitted);
812 return errorCodeToError(EC);
813 }
814 return std::move(Ret);
815}
816
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000817static std::error_code
818createTemporaryFile(const Twine &Model, int &ResultFD,
819 llvm::SmallVectorImpl<char> &ResultPath, FSEntity Type) {
Rafael Espindola325fa0f2013-07-05 19:56:49 +0000820 SmallString<128> Storage;
821 StringRef P = Model.toNullTerminatedStringRef(Storage);
Zachary Turner5c5091f2017-03-16 22:28:04 +0000822 assert(P.find_first_of(separators(Style::native)) == StringRef::npos &&
Rafael Espindola325fa0f2013-07-05 19:56:49 +0000823 "Model must be a simple filename.");
824 // Use P.begin() so that createUniqueEntity doesn't need to recreate Storage.
825 return createUniqueEntity(P.begin(), ResultFD, ResultPath,
826 true, owner_read | owner_write, Type);
827}
828
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000829static std::error_code
Rafael Espindola325fa0f2013-07-05 19:56:49 +0000830createTemporaryFile(const Twine &Prefix, StringRef Suffix, int &ResultFD,
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000831 llvm::SmallVectorImpl<char> &ResultPath, FSEntity Type) {
Rafael Espindolad3c89042013-07-25 15:00:17 +0000832 const char *Middle = Suffix.empty() ? "-%%%%%%" : "-%%%%%%.";
833 return createTemporaryFile(Prefix + Middle + Suffix, ResultFD, ResultPath,
Rafael Espindola325fa0f2013-07-05 19:56:49 +0000834 Type);
835}
836
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000837std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
838 int &ResultFD,
839 SmallVectorImpl<char> &ResultPath) {
Rafael Espindola325fa0f2013-07-05 19:56:49 +0000840 return createTemporaryFile(Prefix, Suffix, ResultFD, ResultPath, FS_File);
841}
842
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000843std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
844 SmallVectorImpl<char> &ResultPath) {
Rafael Espindola325fa0f2013-07-05 19:56:49 +0000845 int Dummy;
846 return createTemporaryFile(Prefix, Suffix, Dummy, ResultPath, FS_Name);
847}
848
849
Rafael Espindolae79a8722013-06-28 03:48:47 +0000850// This is a mkdtemp with a different pattern. We use createUniqueEntity mostly
Rafael Espindola31a24432013-06-28 10:55:41 +0000851// for consistency. We should try using mkdtemp.
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000852std::error_code createUniqueDirectory(const Twine &Prefix,
853 SmallVectorImpl<char> &ResultPath) {
Rafael Espindolae79a8722013-06-28 03:48:47 +0000854 int Dummy;
855 return createUniqueEntity(Prefix + "-%%%%%%", Dummy, ResultPath,
856 true, 0, FS_Dir);
Rafael Espindola7ffacc42013-06-27 03:45:31 +0000857}
858
Benjamin Kramerae1d5992015-10-05 13:02:43 +0000859static std::error_code make_absolute(const Twine &current_directory,
860 SmallVectorImpl<char> &path,
861 bool use_current_directory) {
Michael J. Spencer92903a32010-12-07 03:57:17 +0000862 StringRef p(path.data(), path.size());
863
Zachary Turner5c5091f2017-03-16 22:28:04 +0000864 bool rootDirectory = path::has_root_directory(p);
865 bool rootName =
866 (real_style(Style::native) != Style::windows) || path::has_root_name(p);
Michael J. Spencer92903a32010-12-07 03:57:17 +0000867
868 // Already absolute.
869 if (rootName && rootDirectory)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000870 return std::error_code();
Michael J. Spencer92903a32010-12-07 03:57:17 +0000871
872 // All of the following conditions will need the current directory.
873 SmallString<128> current_dir;
Benjamin Kramerae1d5992015-10-05 13:02:43 +0000874 if (use_current_directory)
875 current_directory.toVector(current_dir);
876 else if (std::error_code ec = current_path(current_dir))
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000877 return ec;
Michael J. Spencer92903a32010-12-07 03:57:17 +0000878
879 // Relative path. Prepend the current directory.
880 if (!rootName && !rootDirectory) {
881 // Append path to the current directory.
Michael J. Spencer1e090f02010-12-07 03:57:37 +0000882 path::append(current_dir, p);
Michael J. Spencer92903a32010-12-07 03:57:17 +0000883 // Set path to the result.
884 path.swap(current_dir);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000885 return std::error_code();
Michael J. Spencer92903a32010-12-07 03:57:17 +0000886 }
887
888 if (!rootName && rootDirectory) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000889 StringRef cdrn = path::root_name(current_dir);
Michael J. Spencer92903a32010-12-07 03:57:17 +0000890 SmallString<128> curDirRootName(cdrn.begin(), cdrn.end());
Michael J. Spencer1e090f02010-12-07 03:57:37 +0000891 path::append(curDirRootName, p);
Michael J. Spencer92903a32010-12-07 03:57:17 +0000892 // Set path to the result.
893 path.swap(curDirRootName);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000894 return std::error_code();
Michael J. Spencer92903a32010-12-07 03:57:17 +0000895 }
896
897 if (rootName && !rootDirectory) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000898 StringRef pRootName = path::root_name(p);
899 StringRef bRootDirectory = path::root_directory(current_dir);
900 StringRef bRelativePath = path::relative_path(current_dir);
901 StringRef pRelativePath = path::relative_path(p);
Michael J. Spencer92903a32010-12-07 03:57:17 +0000902
903 SmallString<128> res;
Michael J. Spencer1e090f02010-12-07 03:57:37 +0000904 path::append(res, pRootName, bRootDirectory, bRelativePath, pRelativePath);
Michael J. Spencer92903a32010-12-07 03:57:17 +0000905 path.swap(res);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000906 return std::error_code();
Michael J. Spencer92903a32010-12-07 03:57:17 +0000907 }
908
909 llvm_unreachable("All rootName and rootDirectory combinations should have "
910 "occurred above!");
911}
912
Benjamin Kramerae1d5992015-10-05 13:02:43 +0000913std::error_code make_absolute(const Twine &current_directory,
914 SmallVectorImpl<char> &path) {
915 return make_absolute(current_directory, path, true);
916}
917
918std::error_code make_absolute(SmallVectorImpl<char> &path) {
919 return make_absolute(Twine(), path, false);
920}
921
Frederic Riss6b9396c2015-08-06 21:04:55 +0000922std::error_code create_directories(const Twine &Path, bool IgnoreExisting,
923 perms Perms) {
Rafael Espindolab6f72b22014-02-13 16:58:19 +0000924 SmallString<128> PathStorage;
925 StringRef P = Path.toStringRef(PathStorage);
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000926
Rafael Espindolab6f72b22014-02-13 16:58:19 +0000927 // Be optimistic and try to create the directory
Frederic Riss6b9396c2015-08-06 21:04:55 +0000928 std::error_code EC = create_directory(P, IgnoreExisting, Perms);
Rafael Espindolab6f72b22014-02-13 16:58:19 +0000929 // If we succeeded, or had any error other than the parent not existing, just
930 // return it.
Rafael Espindola2a826e42014-06-13 17:20:48 +0000931 if (EC != errc::no_such_file_or_directory)
Rafael Espindolab6f72b22014-02-13 16:58:19 +0000932 return EC;
Michael J. Spencerf616b212010-12-07 17:04:04 +0000933
Rafael Espindolab6f72b22014-02-13 16:58:19 +0000934 // We failed because of a no_such_file_or_directory, try to create the
935 // parent.
936 StringRef Parent = path::parent_path(P);
937 if (Parent.empty())
938 return EC;
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000939
Frederic Riss6b9396c2015-08-06 21:04:55 +0000940 if ((EC = create_directories(Parent, IgnoreExisting, Perms)))
Rafael Espindolab6f72b22014-02-13 16:58:19 +0000941 return EC;
942
Frederic Riss6b9396c2015-08-06 21:04:55 +0000943 return create_directory(P, IgnoreExisting, Perms);
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000944}
945
Justin Bognercd45f962014-06-19 19:35:39 +0000946std::error_code copy_file(const Twine &From, const Twine &To) {
947 int ReadFD, WriteFD;
948 if (std::error_code EC = openFileForRead(From, ReadFD))
949 return EC;
950 if (std::error_code EC = openFileForWrite(To, WriteFD, F_None)) {
951 close(ReadFD);
952 return EC;
953 }
954
955 const size_t BufSize = 4096;
Dylan Noblesmith42836d92014-08-26 02:03:30 +0000956 char *Buf = new char[BufSize];
Justin Bognercd45f962014-06-19 19:35:39 +0000957 int BytesRead = 0, BytesWritten = 0;
958 for (;;) {
959 BytesRead = read(ReadFD, Buf, BufSize);
960 if (BytesRead <= 0)
961 break;
962 while (BytesRead) {
963 BytesWritten = write(WriteFD, Buf, BytesRead);
964 if (BytesWritten < 0)
965 break;
966 BytesRead -= BytesWritten;
967 }
968 if (BytesWritten < 0)
969 break;
970 }
971 close(ReadFD);
972 close(WriteFD);
Dylan Noblesmith42836d92014-08-26 02:03:30 +0000973 delete[] Buf;
Justin Bognercd45f962014-06-19 19:35:39 +0000974
975 if (BytesRead < 0 || BytesWritten < 0)
976 return std::error_code(errno, std::generic_category());
977 return std::error_code();
978}
979
Zachary Turner82a0c972017-03-20 23:33:18 +0000980ErrorOr<MD5::MD5Result> md5_contents(int FD) {
981 MD5 Hash;
982
983 constexpr size_t BufSize = 4096;
984 std::vector<uint8_t> Buf(BufSize);
985 int BytesRead = 0;
986 for (;;) {
987 BytesRead = read(FD, Buf.data(), BufSize);
988 if (BytesRead <= 0)
989 break;
990 Hash.update(makeArrayRef(Buf.data(), BytesRead));
991 }
992
993 if (BytesRead < 0)
994 return std::error_code(errno, std::generic_category());
995 MD5::MD5Result Result;
996 Hash.final(Result);
997 return Result;
998}
999
1000ErrorOr<MD5::MD5Result> md5_contents(const Twine &Path) {
1001 int FD;
1002 if (auto EC = openFileForRead(Path, FD))
1003 return EC;
1004
1005 auto Result = md5_contents(FD);
1006 close(FD);
1007 return Result;
1008}
1009
Peter Collingbourne0dfdb442017-10-10 22:19:46 +00001010bool exists(const basic_file_status &status) {
Michael J. Spencer730f51a2010-12-09 17:37:02 +00001011 return status_known(status) && status.type() != file_type::file_not_found;
1012}
1013
Peter Collingbourne0dfdb442017-10-10 22:19:46 +00001014bool status_known(const basic_file_status &s) {
Michael J. Spencer730f51a2010-12-09 17:37:02 +00001015 return s.type() != file_type::status_error;
1016}
1017
Zachary Turner82dd5422017-03-07 16:10:10 +00001018file_type get_file_type(const Twine &Path, bool Follow) {
Zachary Turner990e3cd2017-03-07 03:43:17 +00001019 file_status st;
Zachary Turner82dd5422017-03-07 16:10:10 +00001020 if (status(Path, st, Follow))
Zachary Turner990e3cd2017-03-07 03:43:17 +00001021 return file_type::status_error;
1022 return st.type();
1023}
1024
Peter Collingbourne0dfdb442017-10-10 22:19:46 +00001025bool is_directory(const basic_file_status &status) {
Michael J. Spencer730f51a2010-12-09 17:37:02 +00001026 return status.type() == file_type::directory_file;
1027}
1028
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001029std::error_code is_directory(const Twine &path, bool &result) {
Michael J. Spencer0d771ed2011-01-11 01:21:55 +00001030 file_status st;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001031 if (std::error_code ec = status(path, st))
Michael J. Spencer0d771ed2011-01-11 01:21:55 +00001032 return ec;
1033 result = is_directory(st);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001034 return std::error_code();
Michael J. Spencer0d771ed2011-01-11 01:21:55 +00001035}
1036
Peter Collingbourne0dfdb442017-10-10 22:19:46 +00001037bool is_regular_file(const basic_file_status &status) {
Michael J. Spencer730f51a2010-12-09 17:37:02 +00001038 return status.type() == file_type::regular_file;
1039}
1040
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001041std::error_code is_regular_file(const Twine &path, bool &result) {
Michael J. Spencer0d771ed2011-01-11 01:21:55 +00001042 file_status st;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001043 if (std::error_code ec = status(path, st))
Michael J. Spencer0d771ed2011-01-11 01:21:55 +00001044 return ec;
1045 result = is_regular_file(st);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001046 return std::error_code();
Michael J. Spencer0d771ed2011-01-11 01:21:55 +00001047}
1048
Peter Collingbourne0dfdb442017-10-10 22:19:46 +00001049bool is_symlink_file(const basic_file_status &status) {
Zachary Turner7d86ee52017-03-08 17:56:08 +00001050 return status.type() == file_type::symlink_file;
1051}
1052
1053std::error_code is_symlink_file(const Twine &path, bool &result) {
1054 file_status st;
1055 if (std::error_code ec = status(path, st, false))
1056 return ec;
1057 result = is_symlink_file(st);
1058 return std::error_code();
1059}
1060
Peter Collingbourne0dfdb442017-10-10 22:19:46 +00001061bool is_other(const basic_file_status &status) {
Michael J. Spencer730f51a2010-12-09 17:37:02 +00001062 return exists(status) &&
1063 !is_regular_file(status) &&
Rafael Espindola20063062014-03-20 17:39:04 +00001064 !is_directory(status);
Michael J. Spencer730f51a2010-12-09 17:37:02 +00001065}
1066
Juergen Ributzka84ba3422014-12-18 18:19:47 +00001067std::error_code is_other(const Twine &Path, bool &Result) {
1068 file_status FileStatus;
1069 if (std::error_code EC = status(Path, FileStatus))
1070 return EC;
1071 Result = is_other(FileStatus);
1072 return std::error_code();
1073}
1074
Peter Collingbourne0dfdb442017-10-10 22:19:46 +00001075void directory_entry::replace_filename(const Twine &filename,
1076 basic_file_status st) {
Rafael Espindolaf662e002015-07-15 21:24:07 +00001077 SmallString<128> path = path::parent_path(Path);
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +00001078 path::append(path, filename);
1079 Path = path.str();
1080 Status = st;
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +00001081}
1082
James Henderson566fdf42017-03-16 11:22:09 +00001083ErrorOr<perms> getPermissions(const Twine &Path) {
1084 file_status Status;
1085 if (std::error_code EC = status(Path, Status))
1086 return EC;
1087
1088 return Status.permissions();
1089}
1090
Aaron Ballman345012d2017-03-13 12:24:51 +00001091} // end namespace fs
1092} // end namespace sys
1093} // end namespace llvm
Michael J. Spencerebad2f92010-11-29 22:28:51 +00001094
1095// Include the truly platform-specific parts.
1096#if defined(LLVM_ON_UNIX)
Rafael Espindolaf1fc3822013-06-26 19:33:03 +00001097#include "Unix/Path.inc"
Michael J. Spencerebad2f92010-11-29 22:28:51 +00001098#endif
1099#if defined(LLVM_ON_WIN32)
Rafael Espindolaf1fc3822013-06-26 19:33:03 +00001100#include "Windows/Path.inc"
Michael J. Spencerebad2f92010-11-29 22:28:51 +00001101#endif
Pawel Bylica0e97e5c2015-11-02 09:49:17 +00001102
1103namespace llvm {
1104namespace sys {
1105namespace path {
1106
1107bool user_cache_directory(SmallVectorImpl<char> &Result, const Twine &Path1,
1108 const Twine &Path2, const Twine &Path3) {
1109 if (getUserCacheDir(Result)) {
1110 append(Result, Path1, Path2, Path3);
1111 return true;
1112 }
1113 return false;
1114}
1115
1116} // end namespace path
1117} // end namsspace sys
1118} // end namespace llvm