blob: 5ce2f50ebdaa9dffd06275b7869b233be9f880f8 [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"
Nico Weber432a3882018-04-30 14:59:11 +000016#include "llvm/Config/llvm-config.h"
Rui Ueyama5c69ff52014-09-11 22:34:32 +000017#include "llvm/Support/Endian.h"
Rafael Espindola2a826e42014-06-13 17:20:48 +000018#include "llvm/Support/Errc.h"
Michael J. Spencerebad2f92010-11-29 22:28:51 +000019#include "llvm/Support/ErrorHandling.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000020#include "llvm/Support/FileSystem.h"
Aaron Ballman07e76182014-02-11 03:40:14 +000021#include "llvm/Support/Process.h"
Rafael Espindola58fe67a2017-11-13 18:33:44 +000022#include "llvm/Support/Signals.h"
Michael J. Spencerebad2f92010-11-29 22:28:51 +000023#include <cctype>
Michael J. Spencer848f46b2010-12-28 01:49:01 +000024#include <cstring>
Rafael Espindola4526b1d2013-06-18 17:01:00 +000025
26#if !defined(_MSC_VER) && !defined(__MINGW32__)
Douglas Gregora86ddf02013-03-21 21:46:10 +000027#include <unistd.h>
Rafael Espindola4526b1d2013-06-18 17:01:00 +000028#else
29#include <io.h>
Douglas Gregora86ddf02013-03-21 21:46:10 +000030#endif
Michael J. Spencerebad2f92010-11-29 22:28:51 +000031
Rafael Espindola7a0b6402014-02-24 03:07:41 +000032using namespace llvm;
Rui Ueyama3206b792015-03-02 21:19:12 +000033using namespace llvm::support::endian;
Rafael Espindola7a0b6402014-02-24 03:07:41 +000034
Michael J. Spencerebad2f92010-11-29 22:28:51 +000035namespace {
36 using llvm::StringRef;
Zhanyong Wan606bb1a2011-02-11 21:24:40 +000037 using llvm::sys::path::is_separator;
Zachary Turner5c5091f2017-03-16 22:28:04 +000038 using llvm::sys::path::Style;
Michael J. Spencerebad2f92010-11-29 22:28:51 +000039
Zachary Turner5c5091f2017-03-16 22:28:04 +000040 inline Style real_style(Style style) {
Nico Weber712e8d22018-04-29 00:45:03 +000041#ifdef _WIN32
Zachary Turner5c5091f2017-03-16 22:28:04 +000042 return (style == Style::posix) ? Style::posix : Style::windows;
Michael J. Spencerebad2f92010-11-29 22:28:51 +000043#else
Zachary Turner5c5091f2017-03-16 22:28:04 +000044 return (style == Style::windows) ? Style::windows : Style::posix;
Michael J. Spencerebad2f92010-11-29 22:28:51 +000045#endif
Zachary Turner5c5091f2017-03-16 22:28:04 +000046 }
Michael J. Spencerebad2f92010-11-29 22:28:51 +000047
Zachary Turner5c5091f2017-03-16 22:28:04 +000048 inline const char *separators(Style style) {
49 if (real_style(style) == Style::windows)
50 return "\\/";
51 return "/";
52 }
53
54 inline char preferred_separator(Style style) {
55 if (real_style(style) == Style::windows)
56 return '\\';
57 return '/';
58 }
59
60 StringRef find_first_component(StringRef path, Style style) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +000061 // Look for this first component in the following order.
62 // * empty (in this case we return an empty string)
63 // * either C: or {//,\\}net.
64 // * {/,\}
Michael J. Spencerebad2f92010-11-29 22:28:51 +000065 // * {file,directory}name
66
67 if (path.empty())
68 return path;
69
Zachary Turner5c5091f2017-03-16 22:28:04 +000070 if (real_style(style) == Style::windows) {
71 // C:
72 if (path.size() >= 2 &&
73 std::isalpha(static_cast<unsigned char>(path[0])) && path[1] == ':')
74 return path.substr(0, 2);
75 }
Michael J. Spencerebad2f92010-11-29 22:28:51 +000076
77 // //net
Zachary Turner5c5091f2017-03-16 22:28:04 +000078 if ((path.size() > 2) && is_separator(path[0], style) &&
79 path[0] == path[1] && !is_separator(path[2], style)) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +000080 // Find the next directory separator.
Zachary Turner5c5091f2017-03-16 22:28:04 +000081 size_t end = path.find_first_of(separators(style), 2);
Benjamin Kramerffa42ce2010-12-17 20:27:37 +000082 return path.substr(0, end);
Michael J. Spencerebad2f92010-11-29 22:28:51 +000083 }
84
85 // {/,\}
Zachary Turner5c5091f2017-03-16 22:28:04 +000086 if (is_separator(path[0], style))
Benjamin Kramerffa42ce2010-12-17 20:27:37 +000087 return path.substr(0, 1);
Michael J. Spencerebad2f92010-11-29 22:28:51 +000088
Michael J. Spencerebad2f92010-11-29 22:28:51 +000089 // * {file,directory}name
Zachary Turner5c5091f2017-03-16 22:28:04 +000090 size_t end = path.find_first_of(separators(style));
Benjamin Kramerffa42ce2010-12-17 20:27:37 +000091 return path.substr(0, end);
Michael J. Spencerebad2f92010-11-29 22:28:51 +000092 }
Michael J. Spencer545cbdf2010-11-30 23:28:07 +000093
Pavel Labathd20289b2018-05-09 13:21:16 +000094 // Returns the first character of the filename in str. For paths ending in
95 // '/', it returns the position of the '/'.
Zachary Turner5c5091f2017-03-16 22:28:04 +000096 size_t filename_pos(StringRef str, Style style) {
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
Pavel Labathd20289b2018-05-09 13:21:16 +0000113 // Returns the position of the root directory in str. If there is no root
114 // directory in str, it returns StringRef::npos.
Zachary Turner5c5091f2017-03-16 22:28:04 +0000115 size_t root_dir_start(StringRef str, Style style) {
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000116 // case "c:/"
Zachary Turner5c5091f2017-03-16 22:28:04 +0000117 if (real_style(style) == Style::windows) {
118 if (str.size() > 2 && str[1] == ':' && is_separator(str[2], style))
119 return 2;
120 }
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000121
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000122 // case "//net"
Zachary Turner5c5091f2017-03-16 22:28:04 +0000123 if (str.size() > 3 && is_separator(str[0], style) && str[0] == str[1] &&
124 !is_separator(str[2], style)) {
125 return str.find_first_of(separators(style), 2);
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000126 }
127
128 // case "/"
Zachary Turner5c5091f2017-03-16 22:28:04 +0000129 if (str.size() > 0 && is_separator(str[0], style))
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000130 return 0;
131
132 return StringRef::npos;
133 }
134
Pavel Labathd20289b2018-05-09 13:21:16 +0000135 // Returns the position past the end of the "parent path" of path. The parent
136 // path will not end in '/', unless the parent is the root directory. If the
137 // path has no parent, 0 is returned.
Zachary Turner5c5091f2017-03-16 22:28:04 +0000138 size_t parent_path_end(StringRef path, Style style) {
139 size_t end_pos = filename_pos(path, style);
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000140
Zachary Turner5c5091f2017-03-16 22:28:04 +0000141 bool filename_was_sep =
142 path.size() > 0 && is_separator(path[end_pos], style);
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000143
Pavel Labathd20289b2018-05-09 13:21:16 +0000144 // Skip separators until we reach root dir (or the start of the string).
145 size_t root_dir_pos = root_dir_start(path, style);
146 while (end_pos > 0 &&
147 (root_dir_pos == StringRef::npos || end_pos > root_dir_pos) &&
Zachary Turner5c5091f2017-03-16 22:28:04 +0000148 is_separator(path[end_pos - 1], style))
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000149 --end_pos;
150
Pavel Labathd20289b2018-05-09 13:21:16 +0000151 if (end_pos == root_dir_pos && !filename_was_sep) {
152 // We've reached the root dir and the input path was *not* ending in a
153 // sequence of slashes. Include the root dir in the parent path.
154 return root_dir_pos + 1;
155 }
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000156
Pavel Labathd20289b2018-05-09 13:21:16 +0000157 // Otherwise, just include before the last slash.
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000158 return end_pos;
159 }
Zhanyong Wan606bb1a2011-02-11 21:24:40 +0000160} // end unnamed namespace
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000161
Rafael Espindolae79a8722013-06-28 03:48:47 +0000162enum FSEntity {
163 FS_Dir,
164 FS_File,
165 FS_Name
166};
167
Rafael Espindolad19c2e82017-11-27 23:44:11 +0000168static std::error_code
169createUniqueEntity(const Twine &Model, int &ResultFD,
170 SmallVectorImpl<char> &ResultPath, bool MakeAbsolute,
171 unsigned Mode, FSEntity Type,
Zachary Turner1f67a3c2018-06-07 19:58:58 +0000172 sys::fs::OpenFlags Flags = sys::fs::OF_None) {
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000173 SmallString<128> ModelStorage;
174 Model.toVector(ModelStorage);
175
176 if (MakeAbsolute) {
177 // Make model absolute by prepending a temp directory if it's not already.
178 if (!sys::path::is_absolute(Twine(ModelStorage))) {
179 SmallString<128> TDir;
Rafael Espindola016a6d52014-08-26 14:47:52 +0000180 sys::path::system_temp_directory(true, TDir);
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000181 sys::path::append(TDir, Twine(ModelStorage));
182 ModelStorage.swap(TDir);
183 }
184 }
185
186 // From here on, DO NOT modify model. It may be needed if the randomly chosen
187 // path already exists.
188 ResultPath = ModelStorage;
189 // Null terminate.
190 ResultPath.push_back(0);
191 ResultPath.pop_back();
192
Bob Haarman112ebb62018-08-02 18:27:21 +0000193 // Limit the number of attempts we make, so that we don't infinite loop. E.g.
194 // "permission denied" could be for a specific file (so we retry with a
195 // different name) or for the whole directory (retry would always fail).
196 // Checking which is racy, so we try a number of times, then give up.
Bob Haarman9b36f512018-08-02 17:41:38 +0000197 std::error_code EC;
198 for (int Retries = 128; Retries > 0; --Retries) {
199 // Replace '%' with random chars.
200 for (unsigned i = 0, e = ModelStorage.size(); i != e; ++i) {
201 if (ModelStorage[i] == '%')
202 ResultPath[i] =
203 "0123456789abcdef"[sys::Process::GetRandomNumber() & 15];
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000204 }
205
Bob Haarman9b36f512018-08-02 17:41:38 +0000206 // Try to open + create the file.
207 switch (Type) {
208 case FS_File: {
209 EC = sys::fs::openFileForReadWrite(Twine(ResultPath.begin()), ResultFD,
210 sys::fs::CD_CreateNew, Flags, Mode);
211 if (EC) {
212 // errc::permission_denied happens on Windows when we try to open a file
213 // that has been marked for deletion.
214 if (EC == errc::file_exists || EC == errc::permission_denied)
215 continue;
216 return EC;
217 }
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000218
Rafael Espindola281f23a2014-09-11 20:30:02 +0000219 return std::error_code();
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000220 }
Bob Haarman9b36f512018-08-02 17:41:38 +0000221
222 case FS_Name: {
223 EC = sys::fs::access(ResultPath.begin(), sys::fs::AccessMode::Exist);
224 if (EC == errc::no_such_file_or_directory)
225 return std::error_code();
226 if (EC)
227 return EC;
228 continue;
229 }
230
231 case FS_Dir: {
232 EC = sys::fs::create_directory(ResultPath.begin(), false);
233 if (EC) {
234 if (EC == errc::file_exists)
235 continue;
236 return EC;
237 }
238 return std::error_code();
239 }
240 }
241 llvm_unreachable("Invalid Type");
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000242 }
Bob Haarman9b36f512018-08-02 17:41:38 +0000243 return EC;
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000244}
Rafael Espindolae79a8722013-06-28 03:48:47 +0000245
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000246namespace llvm {
247namespace sys {
248namespace path {
249
Zachary Turner5c5091f2017-03-16 22:28:04 +0000250const_iterator begin(StringRef path, Style style) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000251 const_iterator i;
252 i.Path = path;
Zachary Turner5c5091f2017-03-16 22:28:04 +0000253 i.Component = find_first_component(path, style);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000254 i.Position = 0;
Zachary Turner5c5091f2017-03-16 22:28:04 +0000255 i.S = style;
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000256 return i;
257}
258
Benjamin Kramer292b44b2010-12-17 18:19:06 +0000259const_iterator end(StringRef path) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000260 const_iterator i;
261 i.Path = path;
262 i.Position = path.size();
263 return i;
264}
265
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000266const_iterator &const_iterator::operator++() {
267 assert(Position < Path.size() && "Tried to increment past end!");
268
269 // Increment Position to past the current component
270 Position += Component.size();
271
272 // Check for end.
273 if (Position == Path.size()) {
274 Component = StringRef();
275 return *this;
276 }
277
278 // Both POSIX and Windows treat paths that begin with exactly two separators
279 // specially.
Zachary Turner5c5091f2017-03-16 22:28:04 +0000280 bool was_net = Component.size() > 2 && is_separator(Component[0], S) &&
281 Component[1] == Component[0] && !is_separator(Component[2], S);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000282
283 // Handle separators.
Zachary Turner5c5091f2017-03-16 22:28:04 +0000284 if (is_separator(Path[Position], S)) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000285 // Root dir.
Zachary Turner5c5091f2017-03-16 22:28:04 +0000286 if (was_net ||
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000287 // c:/
Zachary Turner5c5091f2017-03-16 22:28:04 +0000288 (real_style(S) == Style::windows && Component.endswith(":"))) {
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000289 Component = Path.substr(Position, 1);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000290 return *this;
291 }
292
293 // Skip extra separators.
Zachary Turner5c5091f2017-03-16 22:28:04 +0000294 while (Position != Path.size() && is_separator(Path[Position], S)) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000295 ++Position;
296 }
297
Pavel Labathd20289b2018-05-09 13:21:16 +0000298 // Treat trailing '/' as a '.', unless it is the root dir.
299 if (Position == Path.size() && Component != "/") {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000300 --Position;
301 Component = ".";
302 return *this;
303 }
304 }
305
306 // Find next component.
Zachary Turner5c5091f2017-03-16 22:28:04 +0000307 size_t end_pos = Path.find_first_of(separators(S), Position);
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000308 Component = Path.slice(Position, end_pos);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000309
310 return *this;
311}
312
Justin Bogner487e7642014-08-04 17:36:41 +0000313bool const_iterator::operator==(const const_iterator &RHS) const {
314 return Path.begin() == RHS.Path.begin() && Position == RHS.Position;
315}
316
317ptrdiff_t const_iterator::operator-(const const_iterator &RHS) const {
318 return Position - RHS.Position;
319}
320
Zachary Turner5c5091f2017-03-16 22:28:04 +0000321reverse_iterator rbegin(StringRef Path, Style style) {
Justin Bogner487e7642014-08-04 17:36:41 +0000322 reverse_iterator I;
323 I.Path = Path;
324 I.Position = Path.size();
Zachary Turner5c5091f2017-03-16 22:28:04 +0000325 I.S = style;
Justin Bogner487e7642014-08-04 17:36:41 +0000326 return ++I;
327}
328
329reverse_iterator rend(StringRef Path) {
330 reverse_iterator I;
331 I.Path = Path;
332 I.Component = Path.substr(0, 0);
333 I.Position = 0;
334 return I;
335}
336
337reverse_iterator &reverse_iterator::operator++() {
Zachary Turner5c5091f2017-03-16 22:28:04 +0000338 size_t root_dir_pos = root_dir_start(Path, S);
Pavel Labathd20289b2018-05-09 13:21:16 +0000339
340 // Skip separators unless it's the root directory.
341 size_t end_pos = Position;
342 while (end_pos > 0 && (end_pos - 1) != root_dir_pos &&
343 is_separator(Path[end_pos - 1], S))
344 --end_pos;
345
346 // Treat trailing '/' as a '.', unless it is the root dir.
347 if (Position == Path.size() && !Path.empty() &&
348 is_separator(Path.back(), S) &&
349 (root_dir_pos == StringRef::npos || end_pos - 1 > root_dir_pos)) {
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000350 --Position;
351 Component = ".";
352 return *this;
353 }
354
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000355 // Find next separator.
Zachary Turner5c5091f2017-03-16 22:28:04 +0000356 size_t start_pos = filename_pos(Path.substr(0, end_pos), S);
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000357 Component = Path.slice(start_pos, end_pos);
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000358 Position = start_pos;
359 return *this;
360}
361
Justin Bogner487e7642014-08-04 17:36:41 +0000362bool reverse_iterator::operator==(const reverse_iterator &RHS) const {
363 return Path.begin() == RHS.Path.begin() && Component == RHS.Component &&
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000364 Position == RHS.Position;
365}
366
Filipe Cabecinhas78949382016-04-29 16:48:07 +0000367ptrdiff_t reverse_iterator::operator-(const reverse_iterator &RHS) const {
368 return Position - RHS.Position;
369}
370
Zachary Turner5c5091f2017-03-16 22:28:04 +0000371StringRef root_path(StringRef path, Style style) {
372 const_iterator b = begin(path, style), pos = b, e = end(path);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000373 if (b != e) {
Zachary Turner5c5091f2017-03-16 22:28:04 +0000374 bool has_net =
375 b->size() > 2 && is_separator((*b)[0], style) && (*b)[1] == (*b)[0];
376 bool has_drive = (real_style(style) == Style::windows) && b->endswith(":");
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000377
378 if (has_net || has_drive) {
Zachary Turner5c5091f2017-03-16 22:28:04 +0000379 if ((++pos != e) && is_separator((*pos)[0], style)) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000380 // {C:/,//net/}, so get the first two components.
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000381 return path.substr(0, b->size() + pos->size());
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000382 } else {
383 // just {C:,//net}, return the first component.
Michael J. Spencerf616b212010-12-07 17:04:04 +0000384 return *b;
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000385 }
386 }
387
388 // POSIX style root directory.
Zachary Turner5c5091f2017-03-16 22:28:04 +0000389 if (is_separator((*b)[0], style)) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000390 return *b;
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000391 }
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000392 }
393
Michael J. Spencerf616b212010-12-07 17:04:04 +0000394 return StringRef();
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000395}
396
Zachary Turner5c5091f2017-03-16 22:28:04 +0000397StringRef root_name(StringRef path, Style style) {
398 const_iterator b = begin(path, style), e = end(path);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000399 if (b != e) {
Zachary Turner5c5091f2017-03-16 22:28:04 +0000400 bool has_net =
401 b->size() > 2 && is_separator((*b)[0], style) && (*b)[1] == (*b)[0];
402 bool has_drive = (real_style(style) == Style::windows) && b->endswith(":");
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000403
404 if (has_net || has_drive) {
405 // just {C:,//net}, return the first component.
Michael J. Spencerf616b212010-12-07 17:04:04 +0000406 return *b;
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000407 }
408 }
409
410 // No path or no name.
Michael J. Spencerf616b212010-12-07 17:04:04 +0000411 return StringRef();
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000412}
413
Zachary Turner5c5091f2017-03-16 22:28:04 +0000414StringRef root_directory(StringRef path, Style style) {
415 const_iterator b = begin(path, style), pos = b, e = end(path);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000416 if (b != e) {
Zachary Turner5c5091f2017-03-16 22:28:04 +0000417 bool has_net =
418 b->size() > 2 && is_separator((*b)[0], style) && (*b)[1] == (*b)[0];
419 bool has_drive = (real_style(style) == Style::windows) && b->endswith(":");
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000420
421 if ((has_net || has_drive) &&
422 // {C:,//net}, skip to the next component.
Zachary Turner5c5091f2017-03-16 22:28:04 +0000423 (++pos != e) && is_separator((*pos)[0], style)) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000424 return *pos;
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000425 }
426
427 // POSIX style root directory.
Zachary Turner5c5091f2017-03-16 22:28:04 +0000428 if (!has_net && is_separator((*b)[0], style)) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000429 return *b;
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000430 }
431 }
432
433 // No path or no root.
Michael J. Spencerf616b212010-12-07 17:04:04 +0000434 return StringRef();
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000435}
436
Zachary Turner5c5091f2017-03-16 22:28:04 +0000437StringRef relative_path(StringRef path, Style style) {
438 StringRef root = root_path(path, style);
Michael J. Spencere6462392012-02-29 00:06:24 +0000439 return path.substr(root.size());
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000440}
441
Zachary Turner5c5091f2017-03-16 22:28:04 +0000442void append(SmallVectorImpl<char> &path, Style style, const Twine &a,
443 const Twine &b, const Twine &c, const Twine &d) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000444 SmallString<32> a_storage;
445 SmallString<32> b_storage;
446 SmallString<32> c_storage;
447 SmallString<32> d_storage;
448
449 SmallVector<StringRef, 4> components;
450 if (!a.isTriviallyEmpty()) components.push_back(a.toStringRef(a_storage));
451 if (!b.isTriviallyEmpty()) components.push_back(b.toStringRef(b_storage));
452 if (!c.isTriviallyEmpty()) components.push_back(c.toStringRef(c_storage));
453 if (!d.isTriviallyEmpty()) components.push_back(d.toStringRef(d_storage));
454
Pawel Bylica64d08ff2015-10-22 08:12:15 +0000455 for (auto &component : components) {
Zachary Turner5c5091f2017-03-16 22:28:04 +0000456 bool path_has_sep =
457 !path.empty() && is_separator(path[path.size() - 1], style);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000458 if (path_has_sep) {
459 // Strip separators from beginning of component.
Zachary Turner5c5091f2017-03-16 22:28:04 +0000460 size_t loc = component.find_first_not_of(separators(style));
Pawel Bylica64d08ff2015-10-22 08:12:15 +0000461 StringRef c = component.substr(loc);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000462
463 // Append it.
464 path.append(c.begin(), c.end());
465 continue;
466 }
467
Benjamin Kramer324d96b2017-08-09 22:06:32 +0000468 bool component_has_sep =
469 !component.empty() && is_separator(component[0], style);
470 if (!component_has_sep &&
471 !(path.empty() || has_root_name(component, style))) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000472 // Add a separator.
Zachary Turner5c5091f2017-03-16 22:28:04 +0000473 path.push_back(preferred_separator(style));
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000474 }
475
Pawel Bylica64d08ff2015-10-22 08:12:15 +0000476 path.append(component.begin(), component.end());
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000477 }
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000478}
479
Zachary Turner5c5091f2017-03-16 22:28:04 +0000480void append(SmallVectorImpl<char> &path, const Twine &a, const Twine &b,
481 const Twine &c, const Twine &d) {
482 append(path, Style::native, a, b, c, d);
Argyrios Kyrtzidisa61736f2011-02-15 17:51:19 +0000483}
484
Zachary Turner5c5091f2017-03-16 22:28:04 +0000485void append(SmallVectorImpl<char> &path, const_iterator begin,
486 const_iterator end, Style style) {
487 for (; begin != end; ++begin)
488 path::append(path, style, *begin);
489}
490
491StringRef parent_path(StringRef path, Style style) {
492 size_t end_pos = parent_path_end(path, style);
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000493 if (end_pos == StringRef::npos)
Michael J. Spencerf616b212010-12-07 17:04:04 +0000494 return StringRef();
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000495 else
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000496 return path.substr(0, end_pos);
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000497}
498
Zachary Turner5c5091f2017-03-16 22:28:04 +0000499void remove_filename(SmallVectorImpl<char> &path, Style style) {
500 size_t end_pos = parent_path_end(StringRef(path.begin(), path.size()), style);
Michael J. Spencer1e090f02010-12-07 03:57:37 +0000501 if (end_pos != StringRef::npos)
502 path.set_size(end_pos);
Michael J. Spencer9c594092010-12-01 00:52:28 +0000503}
504
Zachary Turner5c5091f2017-03-16 22:28:04 +0000505void replace_extension(SmallVectorImpl<char> &path, const Twine &extension,
506 Style style) {
Michael J. Spencerfb3a95d2010-12-01 00:52:55 +0000507 StringRef p(path.begin(), path.size());
508 SmallString<32> ext_storage;
509 StringRef ext = extension.toStringRef(ext_storage);
510
511 // Erase existing extension.
512 size_t pos = p.find_last_of('.');
Zachary Turner5c5091f2017-03-16 22:28:04 +0000513 if (pos != StringRef::npos && pos >= filename_pos(p, style))
Michael J. Spencerfb3a95d2010-12-01 00:52:55 +0000514 path.set_size(pos);
515
516 // Append '.' if needed.
517 if (ext.size() > 0 && ext[0] != '.')
518 path.push_back('.');
519
520 // Append extension.
521 path.append(ext.begin(), ext.end());
Michael J. Spencerfb3a95d2010-12-01 00:52:55 +0000522}
523
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000524void replace_path_prefix(SmallVectorImpl<char> &Path,
Zachary Turner5c5091f2017-03-16 22:28:04 +0000525 const StringRef &OldPrefix, const StringRef &NewPrefix,
526 Style style) {
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000527 if (OldPrefix.empty() && NewPrefix.empty())
528 return;
529
530 StringRef OrigPath(Path.begin(), Path.size());
531 if (!OrigPath.startswith(OldPrefix))
532 return;
533
534 // If prefixes have the same size we can simply copy the new one over.
535 if (OldPrefix.size() == NewPrefix.size()) {
Fangrui Song75709322018-11-17 01:44:25 +0000536 llvm::copy(NewPrefix, Path.begin());
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000537 return;
538 }
539
540 StringRef RelPath = OrigPath.substr(OldPrefix.size());
541 SmallString<256> NewPath;
Zachary Turner5c5091f2017-03-16 22:28:04 +0000542 path::append(NewPath, style, NewPrefix);
543 path::append(NewPath, style, RelPath);
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000544 Path.swap(NewPath);
545}
546
Zachary Turner5c5091f2017-03-16 22:28:04 +0000547void native(const Twine &path, SmallVectorImpl<char> &result, Style style) {
Benjamin Kramerbd4ac9b2013-09-11 10:45:21 +0000548 assert((!path.isSingleStringRef() ||
549 path.getSingleStringRef().data() != result.data()) &&
550 "path and result are not allowed to overlap!");
Michael J. Spencer80025002010-12-01 02:48:27 +0000551 // Clear result.
Michael J. Spencer98c7a112010-12-07 01:23:19 +0000552 result.clear();
Michael J. Spencer80025002010-12-01 02:48:27 +0000553 path.toVector(result);
Zachary Turner5c5091f2017-03-16 22:28:04 +0000554 native(result, style);
Benjamin Kramerbd4ac9b2013-09-11 10:45:21 +0000555}
556
Zachary Turner5c5091f2017-03-16 22:28:04 +0000557void native(SmallVectorImpl<char> &Path, Style style) {
Serge Pavlov9c761a32017-03-01 09:38:15 +0000558 if (Path.empty())
559 return;
Zachary Turner5c5091f2017-03-16 22:28:04 +0000560 if (real_style(style) == Style::windows) {
561 std::replace(Path.begin(), Path.end(), '/', '\\');
562 if (Path[0] == '~' && (Path.size() == 1 || is_separator(Path[1], style))) {
563 SmallString<128> PathHome;
564 home_directory(PathHome);
565 PathHome.append(Path.begin() + 1, Path.end());
566 Path = PathHome;
567 }
568 } else {
569 for (auto PI = Path.begin(), PE = Path.end(); PI < PE; ++PI) {
570 if (*PI == '\\') {
571 auto PN = PI + 1;
572 if (PN < PE && *PN == '\\')
573 ++PI; // increment once, the for loop will move over the escaped slash
574 else
575 *PI = '/';
576 }
Rafael Espindolad649b9d2014-08-08 21:29:34 +0000577 }
578 }
Michael J. Spencer80025002010-12-01 02:48:27 +0000579}
580
Zachary Turner5c5091f2017-03-16 22:28:04 +0000581std::string convert_to_slash(StringRef path, Style style) {
582 if (real_style(style) != Style::windows)
583 return path;
584
Rui Ueyama3e649032017-01-09 01:47:15 +0000585 std::string s = path.str();
586 std::replace(s.begin(), s.end(), '\\', '/');
587 return s;
Rui Ueyama3e649032017-01-09 01:47:15 +0000588}
589
Zachary Turner5c5091f2017-03-16 22:28:04 +0000590StringRef filename(StringRef path, Style style) { return *rbegin(path, style); }
Michael J. Spencer14269202010-12-01 03:18:17 +0000591
Zachary Turner5c5091f2017-03-16 22:28:04 +0000592StringRef stem(StringRef path, Style style) {
593 StringRef fname = filename(path, style);
Michael J. Spencer956955e2010-12-01 03:18:33 +0000594 size_t pos = fname.find_last_of('.');
595 if (pos == StringRef::npos)
Michael J. Spencerf616b212010-12-07 17:04:04 +0000596 return fname;
Michael J. Spencer956955e2010-12-01 03:18:33 +0000597 else
598 if ((fname.size() == 1 && fname == ".") ||
599 (fname.size() == 2 && fname == ".."))
Michael J. Spencerf616b212010-12-07 17:04:04 +0000600 return fname;
Michael J. Spencer956955e2010-12-01 03:18:33 +0000601 else
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000602 return fname.substr(0, pos);
Michael J. Spencer956955e2010-12-01 03:18:33 +0000603}
604
Zachary Turner5c5091f2017-03-16 22:28:04 +0000605StringRef extension(StringRef path, Style style) {
606 StringRef fname = filename(path, style);
Michael J. Spencer87106c52010-12-01 03:37:41 +0000607 size_t pos = fname.find_last_of('.');
608 if (pos == StringRef::npos)
Michael J. Spencerf616b212010-12-07 17:04:04 +0000609 return StringRef();
Michael J. Spencer87106c52010-12-01 03:37:41 +0000610 else
611 if ((fname.size() == 1 && fname == ".") ||
612 (fname.size() == 2 && fname == ".."))
Michael J. Spencerf616b212010-12-07 17:04:04 +0000613 return StringRef();
Michael J. Spencer87106c52010-12-01 03:37:41 +0000614 else
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000615 return fname.substr(pos);
Michael J. Spencer87106c52010-12-01 03:37:41 +0000616}
617
Zachary Turner5c5091f2017-03-16 22:28:04 +0000618bool is_separator(char value, Style style) {
619 if (value == '/')
620 return true;
621 if (real_style(style) == Style::windows)
622 return value == '\\';
623 return false;
Zhanyong Wan606bb1a2011-02-11 21:24:40 +0000624}
625
Zachary Turner5c5091f2017-03-16 22:28:04 +0000626StringRef get_separator(Style style) {
627 if (real_style(style) == Style::windows)
628 return "\\";
629 return "/";
Yaron Keren15217202014-05-16 13:16:30 +0000630}
631
Zachary Turner5c5091f2017-03-16 22:28:04 +0000632bool has_root_name(const Twine &path, Style style) {
Michael J. Spencer112a7692010-12-01 06:03:50 +0000633 SmallString<128> path_storage;
634 StringRef p = path.toStringRef(path_storage);
635
Zachary Turner5c5091f2017-03-16 22:28:04 +0000636 return !root_name(p, style).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000637}
638
Zachary Turner5c5091f2017-03-16 22:28:04 +0000639bool has_root_directory(const Twine &path, Style style) {
Michael J. Spencer112a7692010-12-01 06:03:50 +0000640 SmallString<128> path_storage;
641 StringRef p = path.toStringRef(path_storage);
642
Zachary Turner5c5091f2017-03-16 22:28:04 +0000643 return !root_directory(p, style).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000644}
645
Zachary Turner5c5091f2017-03-16 22:28:04 +0000646bool has_root_path(const Twine &path, Style style) {
Michael J. Spencer112a7692010-12-01 06:03:50 +0000647 SmallString<128> path_storage;
648 StringRef p = path.toStringRef(path_storage);
649
Zachary Turner5c5091f2017-03-16 22:28:04 +0000650 return !root_path(p, style).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000651}
652
Zachary Turner5c5091f2017-03-16 22:28:04 +0000653bool has_relative_path(const Twine &path, Style style) {
Michael J. Spencer6d4b7e72010-12-20 13:30:28 +0000654 SmallString<128> path_storage;
655 StringRef p = path.toStringRef(path_storage);
656
Zachary Turner5c5091f2017-03-16 22:28:04 +0000657 return !relative_path(p, style).empty();
Michael J. Spencer6d4b7e72010-12-20 13:30:28 +0000658}
659
Zachary Turner5c5091f2017-03-16 22:28:04 +0000660bool has_filename(const Twine &path, Style style) {
Michael J. Spencer112a7692010-12-01 06:03:50 +0000661 SmallString<128> path_storage;
662 StringRef p = path.toStringRef(path_storage);
663
Zachary Turner5c5091f2017-03-16 22:28:04 +0000664 return !filename(p, style).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000665}
666
Zachary Turner5c5091f2017-03-16 22:28:04 +0000667bool has_parent_path(const Twine &path, Style style) {
Michael J. Spencer112a7692010-12-01 06:03:50 +0000668 SmallString<128> path_storage;
669 StringRef p = path.toStringRef(path_storage);
670
Zachary Turner5c5091f2017-03-16 22:28:04 +0000671 return !parent_path(p, style).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000672}
673
Zachary Turner5c5091f2017-03-16 22:28:04 +0000674bool has_stem(const Twine &path, Style style) {
Michael J. Spencer112a7692010-12-01 06:03:50 +0000675 SmallString<128> path_storage;
676 StringRef p = path.toStringRef(path_storage);
677
Zachary Turner5c5091f2017-03-16 22:28:04 +0000678 return !stem(p, style).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000679}
680
Zachary Turner5c5091f2017-03-16 22:28:04 +0000681bool has_extension(const Twine &path, Style style) {
Michael J. Spencer112a7692010-12-01 06:03:50 +0000682 SmallString<128> path_storage;
683 StringRef p = path.toStringRef(path_storage);
684
Zachary Turner5c5091f2017-03-16 22:28:04 +0000685 return !extension(p, style).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000686}
687
Zachary Turner5c5091f2017-03-16 22:28:04 +0000688bool is_absolute(const Twine &path, Style style) {
Michael J. Spencera72df5f2010-12-01 06:21:53 +0000689 SmallString<128> path_storage;
690 StringRef p = path.toStringRef(path_storage);
691
Zachary Turner5c5091f2017-03-16 22:28:04 +0000692 bool rootDir = has_root_directory(p, style);
693 bool rootName =
694 (real_style(style) != Style::windows) || has_root_name(p, style);
Michael J. Spencera72df5f2010-12-01 06:21:53 +0000695
Michael J. Spencerf616b212010-12-07 17:04:04 +0000696 return rootDir && rootName;
Michael J. Spencera72df5f2010-12-01 06:21:53 +0000697}
698
Zachary Turner5c5091f2017-03-16 22:28:04 +0000699bool is_relative(const Twine &path, Style style) {
700 return !is_absolute(path, style);
701}
Douglas Katzmana26be4a2015-09-02 21:02:10 +0000702
Zachary Turner5c5091f2017-03-16 22:28:04 +0000703StringRef remove_leading_dotslash(StringRef Path, Style style) {
Douglas Katzmana26be4a2015-09-02 21:02:10 +0000704 // Remove leading "./" (or ".//" or "././" etc.)
Zachary Turner5c5091f2017-03-16 22:28:04 +0000705 while (Path.size() > 2 && Path[0] == '.' && is_separator(Path[1], style)) {
Douglas Katzmana26be4a2015-09-02 21:02:10 +0000706 Path = Path.substr(2);
Zachary Turner5c5091f2017-03-16 22:28:04 +0000707 while (Path.size() > 0 && is_separator(Path[0], style))
Douglas Katzmana26be4a2015-09-02 21:02:10 +0000708 Path = Path.substr(1);
709 }
710 return Path;
Michael J. Spencera72df5f2010-12-01 06:21:53 +0000711}
712
Zachary Turner5c5091f2017-03-16 22:28:04 +0000713static SmallString<256> remove_dots(StringRef path, bool remove_dot_dot,
714 Style style) {
Mike Aizatsky662b4fd2015-11-09 18:56:31 +0000715 SmallVector<StringRef, 16> components;
716
717 // Skip the root path, then look for traversal in the components.
Zachary Turner5c5091f2017-03-16 22:28:04 +0000718 StringRef rel = path::relative_path(path, style);
719 for (StringRef C :
720 llvm::make_range(path::begin(rel, style), path::end(rel))) {
Mike Aizatsky662b4fd2015-11-09 18:56:31 +0000721 if (C == ".")
722 continue;
Benjamin Kramer937dd7a2016-10-17 13:28:21 +0000723 // Leading ".." will remain in the path unless it's at the root.
724 if (remove_dot_dot && C == "..") {
725 if (!components.empty() && components.back() != "..") {
726 components.pop_back();
727 continue;
728 }
Zachary Turner5c5091f2017-03-16 22:28:04 +0000729 if (path::is_absolute(path, style))
Benjamin Kramer937dd7a2016-10-17 13:28:21 +0000730 continue;
Mike Aizatsky662b4fd2015-11-09 18:56:31 +0000731 }
732 components.push_back(C);
733 }
734
Zachary Turner5c5091f2017-03-16 22:28:04 +0000735 SmallString<256> buffer = path::root_path(path, style);
Mike Aizatsky662b4fd2015-11-09 18:56:31 +0000736 for (StringRef C : components)
Zachary Turner5c5091f2017-03-16 22:28:04 +0000737 path::append(buffer, style, C);
Mike Aizatsky662b4fd2015-11-09 18:56:31 +0000738 return buffer;
739}
740
Zachary Turner5c5091f2017-03-16 22:28:04 +0000741bool remove_dots(SmallVectorImpl<char> &path, bool remove_dot_dot,
742 Style style) {
Mike Aizatsky662b4fd2015-11-09 18:56:31 +0000743 StringRef p(path.data(), path.size());
744
Zachary Turner5c5091f2017-03-16 22:28:04 +0000745 SmallString<256> result = remove_dots(p, remove_dot_dot, style);
Mike Aizatsky662b4fd2015-11-09 18:56:31 +0000746 if (result == path)
747 return false;
748
749 path.swap(result);
750 return true;
751}
752
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +0000753} // end namespace path
754
755namespace fs {
756
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000757std::error_code getUniqueID(const Twine Path, UniqueID &Result) {
Rafael Espindola7f822a92013-07-29 21:26:49 +0000758 file_status Status;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000759 std::error_code EC = status(Path, Status);
Rafael Espindola7f822a92013-07-29 21:26:49 +0000760 if (EC)
761 return EC;
762 Result = Status.getUniqueID();
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000763 return std::error_code();
Rafael Espindola7f822a92013-07-29 21:26:49 +0000764}
765
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000766std::error_code createUniqueFile(const Twine &Model, int &ResultFd,
767 SmallVectorImpl<char> &ResultPath,
Zachary Turner8ac1c382018-06-05 19:58:26 +0000768 unsigned Mode) {
769 return createUniqueEntity(Model, ResultFd, ResultPath, false, Mode, FS_File);
770}
771
772static std::error_code createUniqueFile(const Twine &Model, int &ResultFd,
773 SmallVectorImpl<char> &ResultPath,
774 unsigned Mode, OpenFlags Flags) {
Rafael Espindolad19c2e82017-11-27 23:44:11 +0000775 return createUniqueEntity(Model, ResultFd, ResultPath, false, Mode, FS_File,
776 Flags);
Rafael Espindolac9d2e5b2013-07-05 21:01:08 +0000777}
778
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000779std::error_code createUniqueFile(const Twine &Model,
Ilya Biryukov84185762018-03-19 14:19:58 +0000780 SmallVectorImpl<char> &ResultPath,
781 unsigned Mode) {
782 int FD;
783 auto EC = createUniqueFile(Model, FD, ResultPath, Mode);
784 if (EC)
785 return EC;
786 // FD is only needed to avoid race conditions. Close it right away.
787 close(FD);
788 return EC;
Rafael Espindolac9d2e5b2013-07-05 21:01:08 +0000789}
790
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000791static std::error_code
792createTemporaryFile(const Twine &Model, int &ResultFD,
Zachary Turner8ac1c382018-06-05 19:58:26 +0000793 llvm::SmallVectorImpl<char> &ResultPath, FSEntity Type) {
Rafael Espindola325fa0f2013-07-05 19:56:49 +0000794 SmallString<128> Storage;
795 StringRef P = Model.toNullTerminatedStringRef(Storage);
Zachary Turner5c5091f2017-03-16 22:28:04 +0000796 assert(P.find_first_of(separators(Style::native)) == StringRef::npos &&
Rafael Espindola325fa0f2013-07-05 19:56:49 +0000797 "Model must be a simple filename.");
798 // Use P.begin() so that createUniqueEntity doesn't need to recreate Storage.
Rafael Espindolad19c2e82017-11-27 23:44:11 +0000799 return createUniqueEntity(P.begin(), ResultFD, ResultPath, true,
Zachary Turner8ac1c382018-06-05 19:58:26 +0000800 owner_read | owner_write, Type);
Rafael Espindola325fa0f2013-07-05 19:56:49 +0000801}
802
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000803static std::error_code
Rafael Espindola325fa0f2013-07-05 19:56:49 +0000804createTemporaryFile(const Twine &Prefix, StringRef Suffix, int &ResultFD,
Zachary Turner8ac1c382018-06-05 19:58:26 +0000805 llvm::SmallVectorImpl<char> &ResultPath, FSEntity Type) {
Rafael Espindolad3c89042013-07-25 15:00:17 +0000806 const char *Middle = Suffix.empty() ? "-%%%%%%" : "-%%%%%%.";
807 return createTemporaryFile(Prefix + Middle + Suffix, ResultFD, ResultPath,
Zachary Turner8ac1c382018-06-05 19:58:26 +0000808 Type);
Rafael Espindola325fa0f2013-07-05 19:56:49 +0000809}
810
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000811std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
812 int &ResultFD,
Zachary Turner8ac1c382018-06-05 19:58:26 +0000813 SmallVectorImpl<char> &ResultPath) {
814 return createTemporaryFile(Prefix, Suffix, ResultFD, ResultPath, FS_File);
Rafael Espindola325fa0f2013-07-05 19:56:49 +0000815}
816
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000817std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
818 SmallVectorImpl<char> &ResultPath) {
Ilya Biryukov84185762018-03-19 14:19:58 +0000819 int FD;
820 auto EC = createTemporaryFile(Prefix, Suffix, FD, ResultPath);
821 if (EC)
822 return EC;
823 // FD is only needed to avoid race conditions. Close it right away.
824 close(FD);
825 return EC;
Rafael Espindola325fa0f2013-07-05 19:56:49 +0000826}
827
828
Rafael Espindolae79a8722013-06-28 03:48:47 +0000829// This is a mkdtemp with a different pattern. We use createUniqueEntity mostly
Rafael Espindola31a24432013-06-28 10:55:41 +0000830// for consistency. We should try using mkdtemp.
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000831std::error_code createUniqueDirectory(const Twine &Prefix,
832 SmallVectorImpl<char> &ResultPath) {
Rafael Espindolae79a8722013-06-28 03:48:47 +0000833 int Dummy;
Ilya Biryukov84185762018-03-19 14:19:58 +0000834 return createUniqueEntity(Prefix + "-%%%%%%", Dummy, ResultPath, true, 0,
835 FS_Dir);
836}
837
838std::error_code
839getPotentiallyUniqueFileName(const Twine &Model,
840 SmallVectorImpl<char> &ResultPath) {
841 int Dummy;
842 return createUniqueEntity(Model, Dummy, ResultPath, false, 0, FS_Name);
843}
844
845std::error_code
846getPotentiallyUniqueTempFileName(const Twine &Prefix, StringRef Suffix,
847 SmallVectorImpl<char> &ResultPath) {
848 int Dummy;
849 return createTemporaryFile(Prefix, Suffix, Dummy, ResultPath, FS_Name);
Rafael Espindola7ffacc42013-06-27 03:45:31 +0000850}
851
Pavel Labath1ad53ca2019-01-16 09:55:32 +0000852void make_absolute(const Twine &current_directory,
853 SmallVectorImpl<char> &path) {
Michael J. Spencer92903a32010-12-07 03:57:17 +0000854 StringRef p(path.data(), path.size());
855
Zachary Turner5c5091f2017-03-16 22:28:04 +0000856 bool rootDirectory = path::has_root_directory(p);
857 bool rootName =
858 (real_style(Style::native) != Style::windows) || path::has_root_name(p);
Michael J. Spencer92903a32010-12-07 03:57:17 +0000859
860 // Already absolute.
861 if (rootName && rootDirectory)
Pavel Labath1ad53ca2019-01-16 09:55:32 +0000862 return;
Michael J. Spencer92903a32010-12-07 03:57:17 +0000863
864 // All of the following conditions will need the current directory.
865 SmallString<128> current_dir;
Pavel Labath1ad53ca2019-01-16 09:55:32 +0000866 current_directory.toVector(current_dir);
Michael J. Spencer92903a32010-12-07 03:57:17 +0000867
868 // Relative path. Prepend the current directory.
869 if (!rootName && !rootDirectory) {
870 // Append path to the current directory.
Michael J. Spencer1e090f02010-12-07 03:57:37 +0000871 path::append(current_dir, p);
Michael J. Spencer92903a32010-12-07 03:57:17 +0000872 // Set path to the result.
873 path.swap(current_dir);
Pavel Labath1ad53ca2019-01-16 09:55:32 +0000874 return;
Michael J. Spencer92903a32010-12-07 03:57:17 +0000875 }
876
877 if (!rootName && rootDirectory) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000878 StringRef cdrn = path::root_name(current_dir);
Michael J. Spencer92903a32010-12-07 03:57:17 +0000879 SmallString<128> curDirRootName(cdrn.begin(), cdrn.end());
Michael J. Spencer1e090f02010-12-07 03:57:37 +0000880 path::append(curDirRootName, p);
Michael J. Spencer92903a32010-12-07 03:57:17 +0000881 // Set path to the result.
882 path.swap(curDirRootName);
Pavel Labath1ad53ca2019-01-16 09:55:32 +0000883 return;
Michael J. Spencer92903a32010-12-07 03:57:17 +0000884 }
885
886 if (rootName && !rootDirectory) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000887 StringRef pRootName = path::root_name(p);
888 StringRef bRootDirectory = path::root_directory(current_dir);
889 StringRef bRelativePath = path::relative_path(current_dir);
890 StringRef pRelativePath = path::relative_path(p);
Michael J. Spencer92903a32010-12-07 03:57:17 +0000891
892 SmallString<128> res;
Michael J. Spencer1e090f02010-12-07 03:57:37 +0000893 path::append(res, pRootName, bRootDirectory, bRelativePath, pRelativePath);
Michael J. Spencer92903a32010-12-07 03:57:17 +0000894 path.swap(res);
Pavel Labath1ad53ca2019-01-16 09:55:32 +0000895 return;
Michael J. Spencer92903a32010-12-07 03:57:17 +0000896 }
897
898 llvm_unreachable("All rootName and rootDirectory combinations should have "
899 "occurred above!");
900}
901
Benjamin Kramerae1d5992015-10-05 13:02:43 +0000902std::error_code make_absolute(SmallVectorImpl<char> &path) {
Pavel Labath1ad53ca2019-01-16 09:55:32 +0000903 if (path::is_absolute(path))
904 return {};
905
906 SmallString<128> current_dir;
907 if (std::error_code ec = current_path(current_dir))
908 return ec;
909
910 make_absolute(current_dir, path);
911 return {};
Benjamin Kramerae1d5992015-10-05 13:02:43 +0000912}
913
Frederic Riss6b9396c2015-08-06 21:04:55 +0000914std::error_code create_directories(const Twine &Path, bool IgnoreExisting,
915 perms Perms) {
Rafael Espindolab6f72b22014-02-13 16:58:19 +0000916 SmallString<128> PathStorage;
917 StringRef P = Path.toStringRef(PathStorage);
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000918
Rafael Espindolab6f72b22014-02-13 16:58:19 +0000919 // Be optimistic and try to create the directory
Frederic Riss6b9396c2015-08-06 21:04:55 +0000920 std::error_code EC = create_directory(P, IgnoreExisting, Perms);
Rafael Espindolab6f72b22014-02-13 16:58:19 +0000921 // If we succeeded, or had any error other than the parent not existing, just
922 // return it.
Rafael Espindola2a826e42014-06-13 17:20:48 +0000923 if (EC != errc::no_such_file_or_directory)
Rafael Espindolab6f72b22014-02-13 16:58:19 +0000924 return EC;
Michael J. Spencerf616b212010-12-07 17:04:04 +0000925
Rafael Espindolab6f72b22014-02-13 16:58:19 +0000926 // We failed because of a no_such_file_or_directory, try to create the
927 // parent.
928 StringRef Parent = path::parent_path(P);
929 if (Parent.empty())
930 return EC;
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000931
Frederic Riss6b9396c2015-08-06 21:04:55 +0000932 if ((EC = create_directories(Parent, IgnoreExisting, Perms)))
Rafael Espindolab6f72b22014-02-13 16:58:19 +0000933 return EC;
934
Frederic Riss6b9396c2015-08-06 21:04:55 +0000935 return create_directory(P, IgnoreExisting, Perms);
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000936}
937
Zachary Turner1adca7c2018-06-28 18:49:09 +0000938static std::error_code copy_file_internal(int ReadFD, int WriteFD) {
Justin Bognercd45f962014-06-19 19:35:39 +0000939 const size_t BufSize = 4096;
Dylan Noblesmith42836d92014-08-26 02:03:30 +0000940 char *Buf = new char[BufSize];
Justin Bognercd45f962014-06-19 19:35:39 +0000941 int BytesRead = 0, BytesWritten = 0;
942 for (;;) {
943 BytesRead = read(ReadFD, Buf, BufSize);
944 if (BytesRead <= 0)
945 break;
946 while (BytesRead) {
947 BytesWritten = write(WriteFD, Buf, BytesRead);
948 if (BytesWritten < 0)
949 break;
950 BytesRead -= BytesWritten;
951 }
952 if (BytesWritten < 0)
953 break;
954 }
Dylan Noblesmith42836d92014-08-26 02:03:30 +0000955 delete[] Buf;
Justin Bognercd45f962014-06-19 19:35:39 +0000956
957 if (BytesRead < 0 || BytesWritten < 0)
958 return std::error_code(errno, std::generic_category());
959 return std::error_code();
960}
961
Zachary Turner1adca7c2018-06-28 18:49:09 +0000962std::error_code copy_file(const Twine &From, const Twine &To) {
963 int ReadFD, WriteFD;
964 if (std::error_code EC = openFileForRead(From, ReadFD, OF_None))
965 return EC;
966 if (std::error_code EC =
967 openFileForWrite(To, WriteFD, CD_CreateAlways, OF_None)) {
968 close(ReadFD);
969 return EC;
970 }
971
972 std::error_code EC = copy_file_internal(ReadFD, WriteFD);
973
974 close(ReadFD);
975 close(WriteFD);
976
977 return EC;
978}
979
980std::error_code copy_file(const Twine &From, int ToFD) {
981 int ReadFD;
982 if (std::error_code EC = openFileForRead(From, ReadFD, OF_None))
983 return EC;
984
985 std::error_code EC = copy_file_internal(ReadFD, ToFD);
986
987 close(ReadFD);
988
989 return EC;
990}
991
Zachary Turner82a0c972017-03-20 23:33:18 +0000992ErrorOr<MD5::MD5Result> md5_contents(int FD) {
993 MD5 Hash;
994
995 constexpr size_t BufSize = 4096;
996 std::vector<uint8_t> Buf(BufSize);
997 int BytesRead = 0;
998 for (;;) {
999 BytesRead = read(FD, Buf.data(), BufSize);
1000 if (BytesRead <= 0)
1001 break;
1002 Hash.update(makeArrayRef(Buf.data(), BytesRead));
1003 }
1004
1005 if (BytesRead < 0)
1006 return std::error_code(errno, std::generic_category());
1007 MD5::MD5Result Result;
1008 Hash.final(Result);
1009 return Result;
1010}
1011
1012ErrorOr<MD5::MD5Result> md5_contents(const Twine &Path) {
1013 int FD;
Zachary Turner1f67a3c2018-06-07 19:58:58 +00001014 if (auto EC = openFileForRead(Path, FD, OF_None))
Zachary Turner82a0c972017-03-20 23:33:18 +00001015 return EC;
1016
1017 auto Result = md5_contents(FD);
1018 close(FD);
1019 return Result;
1020}
1021
Peter Collingbourne0dfdb442017-10-10 22:19:46 +00001022bool exists(const basic_file_status &status) {
Michael J. Spencer730f51a2010-12-09 17:37:02 +00001023 return status_known(status) && status.type() != file_type::file_not_found;
1024}
1025
Peter Collingbourne0dfdb442017-10-10 22:19:46 +00001026bool status_known(const basic_file_status &s) {
Michael J. Spencer730f51a2010-12-09 17:37:02 +00001027 return s.type() != file_type::status_error;
1028}
1029
Zachary Turner82dd5422017-03-07 16:10:10 +00001030file_type get_file_type(const Twine &Path, bool Follow) {
Zachary Turner990e3cd2017-03-07 03:43:17 +00001031 file_status st;
Zachary Turner82dd5422017-03-07 16:10:10 +00001032 if (status(Path, st, Follow))
Zachary Turner990e3cd2017-03-07 03:43:17 +00001033 return file_type::status_error;
1034 return st.type();
1035}
1036
Peter Collingbourne0dfdb442017-10-10 22:19:46 +00001037bool is_directory(const basic_file_status &status) {
Michael J. Spencer730f51a2010-12-09 17:37:02 +00001038 return status.type() == file_type::directory_file;
1039}
1040
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001041std::error_code is_directory(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_directory(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_regular_file(const basic_file_status &status) {
Michael J. Spencer730f51a2010-12-09 17:37:02 +00001050 return status.type() == file_type::regular_file;
1051}
1052
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001053std::error_code is_regular_file(const Twine &path, bool &result) {
Michael J. Spencer0d771ed2011-01-11 01:21:55 +00001054 file_status st;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001055 if (std::error_code ec = status(path, st))
Michael J. Spencer0d771ed2011-01-11 01:21:55 +00001056 return ec;
1057 result = is_regular_file(st);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001058 return std::error_code();
Michael J. Spencer0d771ed2011-01-11 01:21:55 +00001059}
1060
Peter Collingbourne0dfdb442017-10-10 22:19:46 +00001061bool is_symlink_file(const basic_file_status &status) {
Zachary Turner7d86ee52017-03-08 17:56:08 +00001062 return status.type() == file_type::symlink_file;
1063}
1064
1065std::error_code is_symlink_file(const Twine &path, bool &result) {
1066 file_status st;
1067 if (std::error_code ec = status(path, st, false))
1068 return ec;
1069 result = is_symlink_file(st);
1070 return std::error_code();
1071}
1072
Peter Collingbourne0dfdb442017-10-10 22:19:46 +00001073bool is_other(const basic_file_status &status) {
Michael J. Spencer730f51a2010-12-09 17:37:02 +00001074 return exists(status) &&
1075 !is_regular_file(status) &&
Rafael Espindola20063062014-03-20 17:39:04 +00001076 !is_directory(status);
Michael J. Spencer730f51a2010-12-09 17:37:02 +00001077}
1078
Juergen Ributzka84ba3422014-12-18 18:19:47 +00001079std::error_code is_other(const Twine &Path, bool &Result) {
1080 file_status FileStatus;
1081 if (std::error_code EC = status(Path, FileStatus))
1082 return EC;
1083 Result = is_other(FileStatus);
1084 return std::error_code();
1085}
1086
Kristina Brooks3a55d1e2018-09-12 22:08:10 +00001087void directory_entry::replace_filename(const Twine &Filename, file_type Type,
1088 basic_file_status Status) {
1089 SmallString<128> PathStr = path::parent_path(Path);
1090 path::append(PathStr, Filename);
1091 this->Path = PathStr.str();
1092 this->Type = Type;
1093 this->Status = Status;
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +00001094}
1095
James Henderson566fdf42017-03-16 11:22:09 +00001096ErrorOr<perms> getPermissions(const Twine &Path) {
1097 file_status Status;
1098 if (std::error_code EC = status(Path, Status))
1099 return EC;
1100
1101 return Status.permissions();
1102}
1103
Aaron Ballman345012d2017-03-13 12:24:51 +00001104} // end namespace fs
1105} // end namespace sys
1106} // end namespace llvm
Michael J. Spencerebad2f92010-11-29 22:28:51 +00001107
1108// Include the truly platform-specific parts.
1109#if defined(LLVM_ON_UNIX)
Rafael Espindolaf1fc3822013-06-26 19:33:03 +00001110#include "Unix/Path.inc"
Michael J. Spencerebad2f92010-11-29 22:28:51 +00001111#endif
Nico Weber712e8d22018-04-29 00:45:03 +00001112#if defined(_WIN32)
Rafael Espindolaf1fc3822013-06-26 19:33:03 +00001113#include "Windows/Path.inc"
Michael J. Spencerebad2f92010-11-29 22:28:51 +00001114#endif
Pawel Bylica0e97e5c2015-11-02 09:49:17 +00001115
1116namespace llvm {
1117namespace sys {
Rafael Espindola2c4e9202017-11-28 01:34:20 +00001118namespace fs {
1119TempFile::TempFile(StringRef Name, int FD) : TmpName(Name), FD(FD) {}
1120TempFile::TempFile(TempFile &&Other) { *this = std::move(Other); }
1121TempFile &TempFile::operator=(TempFile &&Other) {
1122 TmpName = std::move(Other.TmpName);
1123 FD = Other.FD;
1124 Other.Done = true;
1125 return *this;
1126}
1127
1128TempFile::~TempFile() { assert(Done); }
1129
1130Error TempFile::discard() {
1131 Done = true;
Rafael Espindola2c4e9202017-11-28 01:34:20 +00001132 std::error_code RemoveEC;
Rafael Espindola3ecd2042017-11-28 01:41:22 +00001133// On windows closing will remove the file.
Nico Weber712e8d22018-04-29 00:45:03 +00001134#ifndef _WIN32
Rafael Espindola3ecd2042017-11-28 01:41:22 +00001135 // Always try to close and remove.
Rafael Espindola2c4e9202017-11-28 01:34:20 +00001136 if (!TmpName.empty()) {
1137 RemoveEC = fs::remove(TmpName);
1138 sys::DontRemoveFileOnSignal(TmpName);
1139 }
Rafael Espindola3ecd2042017-11-28 01:41:22 +00001140#endif
Rafael Espindola2c4e9202017-11-28 01:34:20 +00001141
1142 if (!RemoveEC)
1143 TmpName = "";
1144
1145 if (FD != -1 && close(FD) == -1) {
1146 std::error_code EC = std::error_code(errno, std::generic_category());
1147 return errorCodeToError(EC);
1148 }
1149 FD = -1;
1150
1151 return errorCodeToError(RemoveEC);
1152}
1153
1154Error TempFile::keep(const Twine &Name) {
1155 assert(!Done);
1156 Done = true;
1157 // Always try to close and rename.
Nico Weber712e8d22018-04-29 00:45:03 +00001158#ifdef _WIN32
Vladimir Stefanovicbeb9d972018-07-03 17:26:43 +00001159 // If we can't cancel the delete don't rename.
Peter Collingbourne881ba102018-06-13 18:03:14 +00001160 auto H = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
1161 std::error_code RenameEC = setDeleteDisposition(H, false);
Jeremy Morse01940652018-08-03 10:13:35 +00001162 if (!RenameEC) {
Rafael Espindola3ecd2042017-11-28 01:41:22 +00001163 RenameEC = rename_fd(FD, Name);
Jeremy Morse01940652018-08-03 10:13:35 +00001164 // If rename failed because it's cross-device, copy instead
1165 if (RenameEC ==
1166 std::error_code(ERROR_NOT_SAME_DEVICE, std::system_category())) {
1167 RenameEC = copy_file(TmpName, Name);
1168 setDeleteDisposition(H, true);
1169 }
1170 }
1171
Rafael Espindola20569e92017-12-05 16:40:56 +00001172 // If we can't rename, discard the temporary file.
1173 if (RenameEC)
Peter Collingbourne881ba102018-06-13 18:03:14 +00001174 setDeleteDisposition(H, true);
Rafael Espindola3ecd2042017-11-28 01:41:22 +00001175#else
Rafael Espindola2c4e9202017-11-28 01:34:20 +00001176 std::error_code RenameEC = fs::rename(TmpName, Name);
Jonas Devlieghereae1727e2018-07-29 14:56:15 +00001177 if (RenameEC) {
1178 // If we can't rename, try to copy to work around cross-device link issues.
1179 RenameEC = sys::fs::copy_file(TmpName, Name);
1180 // If we can't rename or copy, discard the temporary file.
1181 if (RenameEC)
1182 remove(TmpName);
1183 }
Rafael Espindola2c4e9202017-11-28 01:34:20 +00001184 sys::DontRemoveFileOnSignal(TmpName);
Rafael Espindola3ecd2042017-11-28 01:41:22 +00001185#endif
Rafael Espindola2c4e9202017-11-28 01:34:20 +00001186
1187 if (!RenameEC)
1188 TmpName = "";
1189
1190 if (close(FD) == -1) {
1191 std::error_code EC(errno, std::generic_category());
1192 return errorCodeToError(EC);
1193 }
1194 FD = -1;
1195
1196 return errorCodeToError(RenameEC);
1197}
1198
1199Error TempFile::keep() {
1200 assert(!Done);
1201 Done = true;
1202
Nico Weber712e8d22018-04-29 00:45:03 +00001203#ifdef _WIN32
Peter Collingbourne881ba102018-06-13 18:03:14 +00001204 auto H = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
1205 if (std::error_code EC = setDeleteDisposition(H, false))
Rafael Espindola3ecd2042017-11-28 01:41:22 +00001206 return errorCodeToError(EC);
1207#else
Rafael Espindola2c4e9202017-11-28 01:34:20 +00001208 sys::DontRemoveFileOnSignal(TmpName);
Rafael Espindola3ecd2042017-11-28 01:41:22 +00001209#endif
1210
Rafael Espindola2c4e9202017-11-28 01:34:20 +00001211 TmpName = "";
1212
1213 if (close(FD) == -1) {
1214 std::error_code EC(errno, std::generic_category());
1215 return errorCodeToError(EC);
1216 }
1217 FD = -1;
1218
1219 return Error::success();
1220}
1221
1222Expected<TempFile> TempFile::create(const Twine &Model, unsigned Mode) {
1223 int FD;
1224 SmallString<128> ResultPath;
Zachary Turner8ac1c382018-06-05 19:58:26 +00001225 if (std::error_code EC =
Zachary Turner1f67a3c2018-06-07 19:58:58 +00001226 createUniqueFile(Model, FD, ResultPath, Mode, OF_Delete))
Rafael Espindola2c4e9202017-11-28 01:34:20 +00001227 return errorCodeToError(EC);
1228
Rafael Espindola2c4e9202017-11-28 01:34:20 +00001229 TempFile Ret(ResultPath, FD);
Nico Weber712e8d22018-04-29 00:45:03 +00001230#ifndef _WIN32
Rafael Espindola2c4e9202017-11-28 01:34:20 +00001231 if (sys::RemoveFileOnSignal(ResultPath)) {
Rafael Espindola3ecd2042017-11-28 01:41:22 +00001232 // Make sure we delete the file when RemoveFileOnSignal fails.
Rafael Espindola2c4e9202017-11-28 01:34:20 +00001233 consumeError(Ret.discard());
1234 std::error_code EC(errc::operation_not_permitted);
1235 return errorCodeToError(EC);
1236 }
Rafael Espindola3ecd2042017-11-28 01:41:22 +00001237#endif
Rafael Espindola2c4e9202017-11-28 01:34:20 +00001238 return std::move(Ret);
1239}
1240}
1241
Pawel Bylica0e97e5c2015-11-02 09:49:17 +00001242} // end namsspace sys
1243} // end namespace llvm