blob: f229f23a4f84afb850154a1eb0ba28366b724b68 [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 Espindolad19c2e82017-11-27 23:44:11 +0000163static std::error_code
164createUniqueEntity(const Twine &Model, int &ResultFD,
165 SmallVectorImpl<char> &ResultPath, bool MakeAbsolute,
166 unsigned Mode, FSEntity Type,
167 sys::fs::OpenFlags Flags = sys::fs::F_None) {
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000168 SmallString<128> ModelStorage;
169 Model.toVector(ModelStorage);
170
171 if (MakeAbsolute) {
172 // Make model absolute by prepending a temp directory if it's not already.
173 if (!sys::path::is_absolute(Twine(ModelStorage))) {
174 SmallString<128> TDir;
Rafael Espindola016a6d52014-08-26 14:47:52 +0000175 sys::path::system_temp_directory(true, TDir);
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000176 sys::path::append(TDir, Twine(ModelStorage));
177 ModelStorage.swap(TDir);
178 }
179 }
180
181 // From here on, DO NOT modify model. It may be needed if the randomly chosen
182 // path already exists.
183 ResultPath = ModelStorage;
184 // Null terminate.
185 ResultPath.push_back(0);
186 ResultPath.pop_back();
187
188retry_random_path:
189 // Replace '%' with random chars.
190 for (unsigned i = 0, e = ModelStorage.size(); i != e; ++i) {
191 if (ModelStorage[i] == '%')
192 ResultPath[i] = "0123456789abcdef"[sys::Process::GetRandomNumber() & 15];
193 }
194
195 // Try to open + create the file.
196 switch (Type) {
197 case FS_File: {
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000198 if (std::error_code EC =
Rafael Espindola90c7f1c2014-02-24 18:20:12 +0000199 sys::fs::openFileForWrite(Twine(ResultPath.begin()), ResultFD,
Rafael Espindolad19c2e82017-11-27 23:44:11 +0000200 Flags | sys::fs::F_Excl, Mode)) {
Rafael Espindola2a826e42014-06-13 17:20:48 +0000201 if (EC == errc::file_exists)
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000202 goto retry_random_path;
203 return EC;
204 }
205
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000206 return std::error_code();
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000207 }
208
209 case FS_Name: {
Rafael Espindola281f23a2014-09-11 20:30:02 +0000210 std::error_code EC =
211 sys::fs::access(ResultPath.begin(), sys::fs::AccessMode::Exist);
212 if (EC == errc::no_such_file_or_directory)
213 return std::error_code();
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000214 if (EC)
215 return EC;
Rafael Espindola281f23a2014-09-11 20:30:02 +0000216 goto retry_random_path;
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000217 }
218
219 case FS_Dir: {
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000220 if (std::error_code EC =
221 sys::fs::create_directory(ResultPath.begin(), false)) {
Rafael Espindola2a826e42014-06-13 17:20:48 +0000222 if (EC == errc::file_exists)
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000223 goto retry_random_path;
224 return EC;
225 }
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000226 return std::error_code();
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000227 }
228 }
229 llvm_unreachable("Invalid Type");
230}
Rafael Espindolae79a8722013-06-28 03:48:47 +0000231
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000232namespace llvm {
233namespace sys {
234namespace path {
235
Zachary Turner5c5091f2017-03-16 22:28:04 +0000236const_iterator begin(StringRef path, Style style) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000237 const_iterator i;
238 i.Path = path;
Zachary Turner5c5091f2017-03-16 22:28:04 +0000239 i.Component = find_first_component(path, style);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000240 i.Position = 0;
Zachary Turner5c5091f2017-03-16 22:28:04 +0000241 i.S = style;
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000242 return i;
243}
244
Benjamin Kramer292b44b2010-12-17 18:19:06 +0000245const_iterator end(StringRef path) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000246 const_iterator i;
247 i.Path = path;
248 i.Position = path.size();
249 return i;
250}
251
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000252const_iterator &const_iterator::operator++() {
253 assert(Position < Path.size() && "Tried to increment past end!");
254
255 // Increment Position to past the current component
256 Position += Component.size();
257
258 // Check for end.
259 if (Position == Path.size()) {
260 Component = StringRef();
261 return *this;
262 }
263
264 // Both POSIX and Windows treat paths that begin with exactly two separators
265 // specially.
Zachary Turner5c5091f2017-03-16 22:28:04 +0000266 bool was_net = Component.size() > 2 && is_separator(Component[0], S) &&
267 Component[1] == Component[0] && !is_separator(Component[2], S);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000268
269 // Handle separators.
Zachary Turner5c5091f2017-03-16 22:28:04 +0000270 if (is_separator(Path[Position], S)) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000271 // Root dir.
Zachary Turner5c5091f2017-03-16 22:28:04 +0000272 if (was_net ||
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000273 // c:/
Zachary Turner5c5091f2017-03-16 22:28:04 +0000274 (real_style(S) == Style::windows && Component.endswith(":"))) {
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000275 Component = Path.substr(Position, 1);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000276 return *this;
277 }
278
279 // Skip extra separators.
Zachary Turner5c5091f2017-03-16 22:28:04 +0000280 while (Position != Path.size() && is_separator(Path[Position], S)) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000281 ++Position;
282 }
283
284 // Treat trailing '/' as a '.'.
285 if (Position == Path.size()) {
286 --Position;
287 Component = ".";
288 return *this;
289 }
290 }
291
292 // Find next component.
Zachary Turner5c5091f2017-03-16 22:28:04 +0000293 size_t end_pos = Path.find_first_of(separators(S), Position);
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000294 Component = Path.slice(Position, end_pos);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000295
296 return *this;
297}
298
Justin Bogner487e7642014-08-04 17:36:41 +0000299bool const_iterator::operator==(const const_iterator &RHS) const {
300 return Path.begin() == RHS.Path.begin() && Position == RHS.Position;
301}
302
303ptrdiff_t const_iterator::operator-(const const_iterator &RHS) const {
304 return Position - RHS.Position;
305}
306
Zachary Turner5c5091f2017-03-16 22:28:04 +0000307reverse_iterator rbegin(StringRef Path, Style style) {
Justin Bogner487e7642014-08-04 17:36:41 +0000308 reverse_iterator I;
309 I.Path = Path;
310 I.Position = Path.size();
Zachary Turner5c5091f2017-03-16 22:28:04 +0000311 I.S = style;
Justin Bogner487e7642014-08-04 17:36:41 +0000312 return ++I;
313}
314
315reverse_iterator rend(StringRef Path) {
316 reverse_iterator I;
317 I.Path = Path;
318 I.Component = Path.substr(0, 0);
319 I.Position = 0;
320 return I;
321}
322
323reverse_iterator &reverse_iterator::operator++() {
Ben Langmuir8d116392014-03-05 19:56:30 +0000324 // If we're at the end and the previous char was a '/', return '.' unless
325 // we are the root path.
Zachary Turner5c5091f2017-03-16 22:28:04 +0000326 size_t root_dir_pos = root_dir_start(Path, S);
327 if (Position == Path.size() && Path.size() > root_dir_pos + 1 &&
328 is_separator(Path[Position - 1], S)) {
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000329 --Position;
330 Component = ".";
331 return *this;
332 }
333
334 // Skip separators unless it's the root directory.
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000335 size_t end_pos = Position;
336
Zachary Turner5c5091f2017-03-16 22:28:04 +0000337 while (end_pos > 0 && (end_pos - 1) != root_dir_pos &&
338 is_separator(Path[end_pos - 1], S))
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000339 --end_pos;
340
341 // Find next separator.
Zachary Turner5c5091f2017-03-16 22:28:04 +0000342 size_t start_pos = filename_pos(Path.substr(0, end_pos), S);
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000343 Component = Path.slice(start_pos, end_pos);
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000344 Position = start_pos;
345 return *this;
346}
347
Justin Bogner487e7642014-08-04 17:36:41 +0000348bool reverse_iterator::operator==(const reverse_iterator &RHS) const {
349 return Path.begin() == RHS.Path.begin() && Component == RHS.Component &&
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000350 Position == RHS.Position;
351}
352
Filipe Cabecinhas78949382016-04-29 16:48:07 +0000353ptrdiff_t reverse_iterator::operator-(const reverse_iterator &RHS) const {
354 return Position - RHS.Position;
355}
356
Zachary Turner5c5091f2017-03-16 22:28:04 +0000357StringRef root_path(StringRef path, Style style) {
358 const_iterator b = begin(path, style), pos = b, e = end(path);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000359 if (b != e) {
Zachary Turner5c5091f2017-03-16 22:28:04 +0000360 bool has_net =
361 b->size() > 2 && is_separator((*b)[0], style) && (*b)[1] == (*b)[0];
362 bool has_drive = (real_style(style) == Style::windows) && b->endswith(":");
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000363
364 if (has_net || has_drive) {
Zachary Turner5c5091f2017-03-16 22:28:04 +0000365 if ((++pos != e) && is_separator((*pos)[0], style)) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000366 // {C:/,//net/}, so get the first two components.
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000367 return path.substr(0, b->size() + pos->size());
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000368 } else {
369 // just {C:,//net}, return the first component.
Michael J. Spencerf616b212010-12-07 17:04:04 +0000370 return *b;
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000371 }
372 }
373
374 // POSIX style root directory.
Zachary Turner5c5091f2017-03-16 22:28:04 +0000375 if (is_separator((*b)[0], style)) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000376 return *b;
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000377 }
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000378 }
379
Michael J. Spencerf616b212010-12-07 17:04:04 +0000380 return StringRef();
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000381}
382
Zachary Turner5c5091f2017-03-16 22:28:04 +0000383StringRef root_name(StringRef path, Style style) {
384 const_iterator b = begin(path, style), e = end(path);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000385 if (b != e) {
Zachary Turner5c5091f2017-03-16 22:28:04 +0000386 bool has_net =
387 b->size() > 2 && is_separator((*b)[0], style) && (*b)[1] == (*b)[0];
388 bool has_drive = (real_style(style) == Style::windows) && b->endswith(":");
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000389
390 if (has_net || has_drive) {
391 // just {C:,//net}, return the first component.
Michael J. Spencerf616b212010-12-07 17:04:04 +0000392 return *b;
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000393 }
394 }
395
396 // No path or no name.
Michael J. Spencerf616b212010-12-07 17:04:04 +0000397 return StringRef();
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000398}
399
Zachary Turner5c5091f2017-03-16 22:28:04 +0000400StringRef root_directory(StringRef path, Style style) {
401 const_iterator b = begin(path, style), pos = b, e = end(path);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000402 if (b != e) {
Zachary Turner5c5091f2017-03-16 22:28:04 +0000403 bool has_net =
404 b->size() > 2 && is_separator((*b)[0], style) && (*b)[1] == (*b)[0];
405 bool has_drive = (real_style(style) == Style::windows) && b->endswith(":");
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000406
407 if ((has_net || has_drive) &&
408 // {C:,//net}, skip to the next component.
Zachary Turner5c5091f2017-03-16 22:28:04 +0000409 (++pos != e) && is_separator((*pos)[0], style)) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000410 return *pos;
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000411 }
412
413 // POSIX style root directory.
Zachary Turner5c5091f2017-03-16 22:28:04 +0000414 if (!has_net && is_separator((*b)[0], style)) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000415 return *b;
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000416 }
417 }
418
419 // No path or no root.
Michael J. Spencerf616b212010-12-07 17:04:04 +0000420 return StringRef();
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000421}
422
Zachary Turner5c5091f2017-03-16 22:28:04 +0000423StringRef relative_path(StringRef path, Style style) {
424 StringRef root = root_path(path, style);
Michael J. Spencere6462392012-02-29 00:06:24 +0000425 return path.substr(root.size());
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000426}
427
Zachary Turner5c5091f2017-03-16 22:28:04 +0000428void append(SmallVectorImpl<char> &path, Style style, const Twine &a,
429 const Twine &b, const Twine &c, const Twine &d) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000430 SmallString<32> a_storage;
431 SmallString<32> b_storage;
432 SmallString<32> c_storage;
433 SmallString<32> d_storage;
434
435 SmallVector<StringRef, 4> components;
436 if (!a.isTriviallyEmpty()) components.push_back(a.toStringRef(a_storage));
437 if (!b.isTriviallyEmpty()) components.push_back(b.toStringRef(b_storage));
438 if (!c.isTriviallyEmpty()) components.push_back(c.toStringRef(c_storage));
439 if (!d.isTriviallyEmpty()) components.push_back(d.toStringRef(d_storage));
440
Pawel Bylica64d08ff2015-10-22 08:12:15 +0000441 for (auto &component : components) {
Zachary Turner5c5091f2017-03-16 22:28:04 +0000442 bool path_has_sep =
443 !path.empty() && is_separator(path[path.size() - 1], style);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000444 if (path_has_sep) {
445 // Strip separators from beginning of component.
Zachary Turner5c5091f2017-03-16 22:28:04 +0000446 size_t loc = component.find_first_not_of(separators(style));
Pawel Bylica64d08ff2015-10-22 08:12:15 +0000447 StringRef c = component.substr(loc);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000448
449 // Append it.
450 path.append(c.begin(), c.end());
451 continue;
452 }
453
Benjamin Kramer324d96b2017-08-09 22:06:32 +0000454 bool component_has_sep =
455 !component.empty() && is_separator(component[0], style);
456 if (!component_has_sep &&
457 !(path.empty() || has_root_name(component, style))) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000458 // Add a separator.
Zachary Turner5c5091f2017-03-16 22:28:04 +0000459 path.push_back(preferred_separator(style));
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000460 }
461
Pawel Bylica64d08ff2015-10-22 08:12:15 +0000462 path.append(component.begin(), component.end());
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000463 }
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000464}
465
Zachary Turner5c5091f2017-03-16 22:28:04 +0000466void append(SmallVectorImpl<char> &path, const Twine &a, const Twine &b,
467 const Twine &c, const Twine &d) {
468 append(path, Style::native, a, b, c, d);
Argyrios Kyrtzidisa61736f2011-02-15 17:51:19 +0000469}
470
Zachary Turner5c5091f2017-03-16 22:28:04 +0000471void append(SmallVectorImpl<char> &path, const_iterator begin,
472 const_iterator end, Style style) {
473 for (; begin != end; ++begin)
474 path::append(path, style, *begin);
475}
476
477StringRef parent_path(StringRef path, Style style) {
478 size_t end_pos = parent_path_end(path, style);
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000479 if (end_pos == StringRef::npos)
Michael J. Spencerf616b212010-12-07 17:04:04 +0000480 return StringRef();
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000481 else
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000482 return path.substr(0, end_pos);
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000483}
484
Zachary Turner5c5091f2017-03-16 22:28:04 +0000485void remove_filename(SmallVectorImpl<char> &path, Style style) {
486 size_t end_pos = parent_path_end(StringRef(path.begin(), path.size()), style);
Michael J. Spencer1e090f02010-12-07 03:57:37 +0000487 if (end_pos != StringRef::npos)
488 path.set_size(end_pos);
Michael J. Spencer9c594092010-12-01 00:52:28 +0000489}
490
Zachary Turner5c5091f2017-03-16 22:28:04 +0000491void replace_extension(SmallVectorImpl<char> &path, const Twine &extension,
492 Style style) {
Michael J. Spencerfb3a95d2010-12-01 00:52:55 +0000493 StringRef p(path.begin(), path.size());
494 SmallString<32> ext_storage;
495 StringRef ext = extension.toStringRef(ext_storage);
496
497 // Erase existing extension.
498 size_t pos = p.find_last_of('.');
Zachary Turner5c5091f2017-03-16 22:28:04 +0000499 if (pos != StringRef::npos && pos >= filename_pos(p, style))
Michael J. Spencerfb3a95d2010-12-01 00:52:55 +0000500 path.set_size(pos);
501
502 // Append '.' if needed.
503 if (ext.size() > 0 && ext[0] != '.')
504 path.push_back('.');
505
506 // Append extension.
507 path.append(ext.begin(), ext.end());
Michael J. Spencerfb3a95d2010-12-01 00:52:55 +0000508}
509
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000510void replace_path_prefix(SmallVectorImpl<char> &Path,
Zachary Turner5c5091f2017-03-16 22:28:04 +0000511 const StringRef &OldPrefix, const StringRef &NewPrefix,
512 Style style) {
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000513 if (OldPrefix.empty() && NewPrefix.empty())
514 return;
515
516 StringRef OrigPath(Path.begin(), Path.size());
517 if (!OrigPath.startswith(OldPrefix))
518 return;
519
520 // If prefixes have the same size we can simply copy the new one over.
521 if (OldPrefix.size() == NewPrefix.size()) {
522 std::copy(NewPrefix.begin(), NewPrefix.end(), Path.begin());
523 return;
524 }
525
526 StringRef RelPath = OrigPath.substr(OldPrefix.size());
527 SmallString<256> NewPath;
Zachary Turner5c5091f2017-03-16 22:28:04 +0000528 path::append(NewPath, style, NewPrefix);
529 path::append(NewPath, style, RelPath);
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000530 Path.swap(NewPath);
531}
532
Zachary Turner5c5091f2017-03-16 22:28:04 +0000533void native(const Twine &path, SmallVectorImpl<char> &result, Style style) {
Benjamin Kramerbd4ac9b2013-09-11 10:45:21 +0000534 assert((!path.isSingleStringRef() ||
535 path.getSingleStringRef().data() != result.data()) &&
536 "path and result are not allowed to overlap!");
Michael J. Spencer80025002010-12-01 02:48:27 +0000537 // Clear result.
Michael J. Spencer98c7a112010-12-07 01:23:19 +0000538 result.clear();
Michael J. Spencer80025002010-12-01 02:48:27 +0000539 path.toVector(result);
Zachary Turner5c5091f2017-03-16 22:28:04 +0000540 native(result, style);
Benjamin Kramerbd4ac9b2013-09-11 10:45:21 +0000541}
542
Zachary Turner5c5091f2017-03-16 22:28:04 +0000543void native(SmallVectorImpl<char> &Path, Style style) {
Serge Pavlov9c761a32017-03-01 09:38:15 +0000544 if (Path.empty())
545 return;
Zachary Turner5c5091f2017-03-16 22:28:04 +0000546 if (real_style(style) == Style::windows) {
547 std::replace(Path.begin(), Path.end(), '/', '\\');
548 if (Path[0] == '~' && (Path.size() == 1 || is_separator(Path[1], style))) {
549 SmallString<128> PathHome;
550 home_directory(PathHome);
551 PathHome.append(Path.begin() + 1, Path.end());
552 Path = PathHome;
553 }
554 } else {
555 for (auto PI = Path.begin(), PE = Path.end(); PI < PE; ++PI) {
556 if (*PI == '\\') {
557 auto PN = PI + 1;
558 if (PN < PE && *PN == '\\')
559 ++PI; // increment once, the for loop will move over the escaped slash
560 else
561 *PI = '/';
562 }
Rafael Espindolad649b9d2014-08-08 21:29:34 +0000563 }
564 }
Michael J. Spencer80025002010-12-01 02:48:27 +0000565}
566
Zachary Turner5c5091f2017-03-16 22:28:04 +0000567std::string convert_to_slash(StringRef path, Style style) {
568 if (real_style(style) != Style::windows)
569 return path;
570
Rui Ueyama3e649032017-01-09 01:47:15 +0000571 std::string s = path.str();
572 std::replace(s.begin(), s.end(), '\\', '/');
573 return s;
Rui Ueyama3e649032017-01-09 01:47:15 +0000574}
575
Zachary Turner5c5091f2017-03-16 22:28:04 +0000576StringRef filename(StringRef path, Style style) { return *rbegin(path, style); }
Michael J. Spencer14269202010-12-01 03:18:17 +0000577
Zachary Turner5c5091f2017-03-16 22:28:04 +0000578StringRef stem(StringRef path, Style style) {
579 StringRef fname = filename(path, style);
Michael J. Spencer956955e2010-12-01 03:18:33 +0000580 size_t pos = fname.find_last_of('.');
581 if (pos == StringRef::npos)
Michael J. Spencerf616b212010-12-07 17:04:04 +0000582 return fname;
Michael J. Spencer956955e2010-12-01 03:18:33 +0000583 else
584 if ((fname.size() == 1 && fname == ".") ||
585 (fname.size() == 2 && fname == ".."))
Michael J. Spencerf616b212010-12-07 17:04:04 +0000586 return fname;
Michael J. Spencer956955e2010-12-01 03:18:33 +0000587 else
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000588 return fname.substr(0, pos);
Michael J. Spencer956955e2010-12-01 03:18:33 +0000589}
590
Zachary Turner5c5091f2017-03-16 22:28:04 +0000591StringRef extension(StringRef path, Style style) {
592 StringRef fname = filename(path, style);
Michael J. Spencer87106c52010-12-01 03:37:41 +0000593 size_t pos = fname.find_last_of('.');
594 if (pos == StringRef::npos)
Michael J. Spencerf616b212010-12-07 17:04:04 +0000595 return StringRef();
Michael J. Spencer87106c52010-12-01 03:37:41 +0000596 else
597 if ((fname.size() == 1 && fname == ".") ||
598 (fname.size() == 2 && fname == ".."))
Michael J. Spencerf616b212010-12-07 17:04:04 +0000599 return StringRef();
Michael J. Spencer87106c52010-12-01 03:37:41 +0000600 else
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000601 return fname.substr(pos);
Michael J. Spencer87106c52010-12-01 03:37:41 +0000602}
603
Zachary Turner5c5091f2017-03-16 22:28:04 +0000604bool is_separator(char value, Style style) {
605 if (value == '/')
606 return true;
607 if (real_style(style) == Style::windows)
608 return value == '\\';
609 return false;
Zhanyong Wan606bb1a2011-02-11 21:24:40 +0000610}
611
Zachary Turner5c5091f2017-03-16 22:28:04 +0000612StringRef get_separator(Style style) {
613 if (real_style(style) == Style::windows)
614 return "\\";
615 return "/";
Yaron Keren15217202014-05-16 13:16:30 +0000616}
617
Zachary Turner5c5091f2017-03-16 22:28:04 +0000618bool has_root_name(const Twine &path, Style style) {
Michael J. Spencer112a7692010-12-01 06:03:50 +0000619 SmallString<128> path_storage;
620 StringRef p = path.toStringRef(path_storage);
621
Zachary Turner5c5091f2017-03-16 22:28:04 +0000622 return !root_name(p, style).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000623}
624
Zachary Turner5c5091f2017-03-16 22:28:04 +0000625bool has_root_directory(const Twine &path, Style style) {
Michael J. Spencer112a7692010-12-01 06:03:50 +0000626 SmallString<128> path_storage;
627 StringRef p = path.toStringRef(path_storage);
628
Zachary Turner5c5091f2017-03-16 22:28:04 +0000629 return !root_directory(p, style).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000630}
631
Zachary Turner5c5091f2017-03-16 22:28:04 +0000632bool has_root_path(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_path(p, style).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000637}
638
Zachary Turner5c5091f2017-03-16 22:28:04 +0000639bool has_relative_path(const Twine &path, Style style) {
Michael J. Spencer6d4b7e72010-12-20 13:30:28 +0000640 SmallString<128> path_storage;
641 StringRef p = path.toStringRef(path_storage);
642
Zachary Turner5c5091f2017-03-16 22:28:04 +0000643 return !relative_path(p, style).empty();
Michael J. Spencer6d4b7e72010-12-20 13:30:28 +0000644}
645
Zachary Turner5c5091f2017-03-16 22:28:04 +0000646bool has_filename(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 !filename(p, style).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000651}
652
Zachary Turner5c5091f2017-03-16 22:28:04 +0000653bool has_parent_path(const Twine &path, Style style) {
Michael J. Spencer112a7692010-12-01 06:03:50 +0000654 SmallString<128> path_storage;
655 StringRef p = path.toStringRef(path_storage);
656
Zachary Turner5c5091f2017-03-16 22:28:04 +0000657 return !parent_path(p, style).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000658}
659
Zachary Turner5c5091f2017-03-16 22:28:04 +0000660bool has_stem(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 !stem(p, style).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000665}
666
Zachary Turner5c5091f2017-03-16 22:28:04 +0000667bool has_extension(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 !extension(p, style).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000672}
673
Zachary Turner5c5091f2017-03-16 22:28:04 +0000674bool is_absolute(const Twine &path, Style style) {
Michael J. Spencera72df5f2010-12-01 06:21:53 +0000675 SmallString<128> path_storage;
676 StringRef p = path.toStringRef(path_storage);
677
Zachary Turner5c5091f2017-03-16 22:28:04 +0000678 bool rootDir = has_root_directory(p, style);
679 bool rootName =
680 (real_style(style) != Style::windows) || has_root_name(p, style);
Michael J. Spencera72df5f2010-12-01 06:21:53 +0000681
Michael J. Spencerf616b212010-12-07 17:04:04 +0000682 return rootDir && rootName;
Michael J. Spencera72df5f2010-12-01 06:21:53 +0000683}
684
Zachary Turner5c5091f2017-03-16 22:28:04 +0000685bool is_relative(const Twine &path, Style style) {
686 return !is_absolute(path, style);
687}
Douglas Katzmana26be4a2015-09-02 21:02:10 +0000688
Zachary Turner5c5091f2017-03-16 22:28:04 +0000689StringRef remove_leading_dotslash(StringRef Path, Style style) {
Douglas Katzmana26be4a2015-09-02 21:02:10 +0000690 // Remove leading "./" (or ".//" or "././" etc.)
Zachary Turner5c5091f2017-03-16 22:28:04 +0000691 while (Path.size() > 2 && Path[0] == '.' && is_separator(Path[1], style)) {
Douglas Katzmana26be4a2015-09-02 21:02:10 +0000692 Path = Path.substr(2);
Zachary Turner5c5091f2017-03-16 22:28:04 +0000693 while (Path.size() > 0 && is_separator(Path[0], style))
Douglas Katzmana26be4a2015-09-02 21:02:10 +0000694 Path = Path.substr(1);
695 }
696 return Path;
Michael J. Spencera72df5f2010-12-01 06:21:53 +0000697}
698
Zachary Turner5c5091f2017-03-16 22:28:04 +0000699static SmallString<256> remove_dots(StringRef path, bool remove_dot_dot,
700 Style style) {
Mike Aizatsky662b4fd2015-11-09 18:56:31 +0000701 SmallVector<StringRef, 16> components;
702
703 // Skip the root path, then look for traversal in the components.
Zachary Turner5c5091f2017-03-16 22:28:04 +0000704 StringRef rel = path::relative_path(path, style);
705 for (StringRef C :
706 llvm::make_range(path::begin(rel, style), path::end(rel))) {
Mike Aizatsky662b4fd2015-11-09 18:56:31 +0000707 if (C == ".")
708 continue;
Benjamin Kramer937dd7a2016-10-17 13:28:21 +0000709 // Leading ".." will remain in the path unless it's at the root.
710 if (remove_dot_dot && C == "..") {
711 if (!components.empty() && components.back() != "..") {
712 components.pop_back();
713 continue;
714 }
Zachary Turner5c5091f2017-03-16 22:28:04 +0000715 if (path::is_absolute(path, style))
Benjamin Kramer937dd7a2016-10-17 13:28:21 +0000716 continue;
Mike Aizatsky662b4fd2015-11-09 18:56:31 +0000717 }
718 components.push_back(C);
719 }
720
Zachary Turner5c5091f2017-03-16 22:28:04 +0000721 SmallString<256> buffer = path::root_path(path, style);
Mike Aizatsky662b4fd2015-11-09 18:56:31 +0000722 for (StringRef C : components)
Zachary Turner5c5091f2017-03-16 22:28:04 +0000723 path::append(buffer, style, C);
Mike Aizatsky662b4fd2015-11-09 18:56:31 +0000724 return buffer;
725}
726
Zachary Turner5c5091f2017-03-16 22:28:04 +0000727bool remove_dots(SmallVectorImpl<char> &path, bool remove_dot_dot,
728 Style style) {
Mike Aizatsky662b4fd2015-11-09 18:56:31 +0000729 StringRef p(path.data(), path.size());
730
Zachary Turner5c5091f2017-03-16 22:28:04 +0000731 SmallString<256> result = remove_dots(p, remove_dot_dot, style);
Mike Aizatsky662b4fd2015-11-09 18:56:31 +0000732 if (result == path)
733 return false;
734
735 path.swap(result);
736 return true;
737}
738
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +0000739} // end namespace path
740
741namespace fs {
742
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000743std::error_code getUniqueID(const Twine Path, UniqueID &Result) {
Rafael Espindola7f822a92013-07-29 21:26:49 +0000744 file_status Status;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000745 std::error_code EC = status(Path, Status);
Rafael Espindola7f822a92013-07-29 21:26:49 +0000746 if (EC)
747 return EC;
748 Result = Status.getUniqueID();
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000749 return std::error_code();
Rafael Espindola7f822a92013-07-29 21:26:49 +0000750}
751
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000752std::error_code createUniqueFile(const Twine &Model, int &ResultFd,
753 SmallVectorImpl<char> &ResultPath,
Rafael Espindolad19c2e82017-11-27 23:44:11 +0000754 unsigned Mode, sys::fs::OpenFlags Flags) {
755 return createUniqueEntity(Model, ResultFd, ResultPath, false, Mode, FS_File,
756 Flags);
Rafael Espindolac9d2e5b2013-07-05 21:01:08 +0000757}
758
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000759std::error_code createUniqueFile(const Twine &Model,
760 SmallVectorImpl<char> &ResultPath) {
Rafael Espindolac9d2e5b2013-07-05 21:01:08 +0000761 int Dummy;
762 return createUniqueEntity(Model, Dummy, ResultPath, false, 0, FS_Name);
763}
764
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000765static std::error_code
766createTemporaryFile(const Twine &Model, int &ResultFD,
Rafael Espindolad19c2e82017-11-27 23:44:11 +0000767 llvm::SmallVectorImpl<char> &ResultPath, FSEntity Type,
768 sys::fs::OpenFlags Flags) {
Rafael Espindola325fa0f2013-07-05 19:56:49 +0000769 SmallString<128> Storage;
770 StringRef P = Model.toNullTerminatedStringRef(Storage);
Zachary Turner5c5091f2017-03-16 22:28:04 +0000771 assert(P.find_first_of(separators(Style::native)) == StringRef::npos &&
Rafael Espindola325fa0f2013-07-05 19:56:49 +0000772 "Model must be a simple filename.");
773 // Use P.begin() so that createUniqueEntity doesn't need to recreate Storage.
Rafael Espindolad19c2e82017-11-27 23:44:11 +0000774 return createUniqueEntity(P.begin(), ResultFD, ResultPath, true,
775 owner_read | owner_write, Type, Flags);
Rafael Espindola325fa0f2013-07-05 19:56:49 +0000776}
777
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000778static std::error_code
Rafael Espindola325fa0f2013-07-05 19:56:49 +0000779createTemporaryFile(const Twine &Prefix, StringRef Suffix, int &ResultFD,
Rafael Espindolad19c2e82017-11-27 23:44:11 +0000780 llvm::SmallVectorImpl<char> &ResultPath, FSEntity Type,
781 sys::fs::OpenFlags Flags = sys::fs::F_None) {
Rafael Espindolad3c89042013-07-25 15:00:17 +0000782 const char *Middle = Suffix.empty() ? "-%%%%%%" : "-%%%%%%.";
783 return createTemporaryFile(Prefix + Middle + Suffix, ResultFD, ResultPath,
Rafael Espindolad19c2e82017-11-27 23:44:11 +0000784 Type, Flags);
Rafael Espindola325fa0f2013-07-05 19:56:49 +0000785}
786
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000787std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
788 int &ResultFD,
Rafael Espindolad19c2e82017-11-27 23:44:11 +0000789 SmallVectorImpl<char> &ResultPath,
790 sys::fs::OpenFlags Flags) {
791 return createTemporaryFile(Prefix, Suffix, ResultFD, ResultPath, FS_File,
792 Flags);
Rafael Espindola325fa0f2013-07-05 19:56:49 +0000793}
794
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000795std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
796 SmallVectorImpl<char> &ResultPath) {
Rafael Espindola325fa0f2013-07-05 19:56:49 +0000797 int Dummy;
798 return createTemporaryFile(Prefix, Suffix, Dummy, ResultPath, FS_Name);
799}
800
801
Rafael Espindolae79a8722013-06-28 03:48:47 +0000802// This is a mkdtemp with a different pattern. We use createUniqueEntity mostly
Rafael Espindola31a24432013-06-28 10:55:41 +0000803// for consistency. We should try using mkdtemp.
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000804std::error_code createUniqueDirectory(const Twine &Prefix,
805 SmallVectorImpl<char> &ResultPath) {
Rafael Espindolae79a8722013-06-28 03:48:47 +0000806 int Dummy;
807 return createUniqueEntity(Prefix + "-%%%%%%", Dummy, ResultPath,
808 true, 0, FS_Dir);
Rafael Espindola7ffacc42013-06-27 03:45:31 +0000809}
810
Benjamin Kramerae1d5992015-10-05 13:02:43 +0000811static std::error_code make_absolute(const Twine &current_directory,
812 SmallVectorImpl<char> &path,
813 bool use_current_directory) {
Michael J. Spencer92903a32010-12-07 03:57:17 +0000814 StringRef p(path.data(), path.size());
815
Zachary Turner5c5091f2017-03-16 22:28:04 +0000816 bool rootDirectory = path::has_root_directory(p);
817 bool rootName =
818 (real_style(Style::native) != Style::windows) || path::has_root_name(p);
Michael J. Spencer92903a32010-12-07 03:57:17 +0000819
820 // Already absolute.
821 if (rootName && rootDirectory)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000822 return std::error_code();
Michael J. Spencer92903a32010-12-07 03:57:17 +0000823
824 // All of the following conditions will need the current directory.
825 SmallString<128> current_dir;
Benjamin Kramerae1d5992015-10-05 13:02:43 +0000826 if (use_current_directory)
827 current_directory.toVector(current_dir);
828 else if (std::error_code ec = current_path(current_dir))
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000829 return ec;
Michael J. Spencer92903a32010-12-07 03:57:17 +0000830
831 // Relative path. Prepend the current directory.
832 if (!rootName && !rootDirectory) {
833 // Append path to the current directory.
Michael J. Spencer1e090f02010-12-07 03:57:37 +0000834 path::append(current_dir, p);
Michael J. Spencer92903a32010-12-07 03:57:17 +0000835 // Set path to the result.
836 path.swap(current_dir);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000837 return std::error_code();
Michael J. Spencer92903a32010-12-07 03:57:17 +0000838 }
839
840 if (!rootName && rootDirectory) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000841 StringRef cdrn = path::root_name(current_dir);
Michael J. Spencer92903a32010-12-07 03:57:17 +0000842 SmallString<128> curDirRootName(cdrn.begin(), cdrn.end());
Michael J. Spencer1e090f02010-12-07 03:57:37 +0000843 path::append(curDirRootName, p);
Michael J. Spencer92903a32010-12-07 03:57:17 +0000844 // Set path to the result.
845 path.swap(curDirRootName);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000846 return std::error_code();
Michael J. Spencer92903a32010-12-07 03:57:17 +0000847 }
848
849 if (rootName && !rootDirectory) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000850 StringRef pRootName = path::root_name(p);
851 StringRef bRootDirectory = path::root_directory(current_dir);
852 StringRef bRelativePath = path::relative_path(current_dir);
853 StringRef pRelativePath = path::relative_path(p);
Michael J. Spencer92903a32010-12-07 03:57:17 +0000854
855 SmallString<128> res;
Michael J. Spencer1e090f02010-12-07 03:57:37 +0000856 path::append(res, pRootName, bRootDirectory, bRelativePath, pRelativePath);
Michael J. Spencer92903a32010-12-07 03:57:17 +0000857 path.swap(res);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000858 return std::error_code();
Michael J. Spencer92903a32010-12-07 03:57:17 +0000859 }
860
861 llvm_unreachable("All rootName and rootDirectory combinations should have "
862 "occurred above!");
863}
864
Benjamin Kramerae1d5992015-10-05 13:02:43 +0000865std::error_code make_absolute(const Twine &current_directory,
866 SmallVectorImpl<char> &path) {
867 return make_absolute(current_directory, path, true);
868}
869
870std::error_code make_absolute(SmallVectorImpl<char> &path) {
871 return make_absolute(Twine(), path, false);
872}
873
Frederic Riss6b9396c2015-08-06 21:04:55 +0000874std::error_code create_directories(const Twine &Path, bool IgnoreExisting,
875 perms Perms) {
Rafael Espindolab6f72b22014-02-13 16:58:19 +0000876 SmallString<128> PathStorage;
877 StringRef P = Path.toStringRef(PathStorage);
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000878
Rafael Espindolab6f72b22014-02-13 16:58:19 +0000879 // Be optimistic and try to create the directory
Frederic Riss6b9396c2015-08-06 21:04:55 +0000880 std::error_code EC = create_directory(P, IgnoreExisting, Perms);
Rafael Espindolab6f72b22014-02-13 16:58:19 +0000881 // If we succeeded, or had any error other than the parent not existing, just
882 // return it.
Rafael Espindola2a826e42014-06-13 17:20:48 +0000883 if (EC != errc::no_such_file_or_directory)
Rafael Espindolab6f72b22014-02-13 16:58:19 +0000884 return EC;
Michael J. Spencerf616b212010-12-07 17:04:04 +0000885
Rafael Espindolab6f72b22014-02-13 16:58:19 +0000886 // We failed because of a no_such_file_or_directory, try to create the
887 // parent.
888 StringRef Parent = path::parent_path(P);
889 if (Parent.empty())
890 return EC;
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000891
Frederic Riss6b9396c2015-08-06 21:04:55 +0000892 if ((EC = create_directories(Parent, IgnoreExisting, Perms)))
Rafael Espindolab6f72b22014-02-13 16:58:19 +0000893 return EC;
894
Frederic Riss6b9396c2015-08-06 21:04:55 +0000895 return create_directory(P, IgnoreExisting, Perms);
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000896}
897
Justin Bognercd45f962014-06-19 19:35:39 +0000898std::error_code copy_file(const Twine &From, const Twine &To) {
899 int ReadFD, WriteFD;
900 if (std::error_code EC = openFileForRead(From, ReadFD))
901 return EC;
902 if (std::error_code EC = openFileForWrite(To, WriteFD, F_None)) {
903 close(ReadFD);
904 return EC;
905 }
906
907 const size_t BufSize = 4096;
Dylan Noblesmith42836d92014-08-26 02:03:30 +0000908 char *Buf = new char[BufSize];
Justin Bognercd45f962014-06-19 19:35:39 +0000909 int BytesRead = 0, BytesWritten = 0;
910 for (;;) {
911 BytesRead = read(ReadFD, Buf, BufSize);
912 if (BytesRead <= 0)
913 break;
914 while (BytesRead) {
915 BytesWritten = write(WriteFD, Buf, BytesRead);
916 if (BytesWritten < 0)
917 break;
918 BytesRead -= BytesWritten;
919 }
920 if (BytesWritten < 0)
921 break;
922 }
923 close(ReadFD);
924 close(WriteFD);
Dylan Noblesmith42836d92014-08-26 02:03:30 +0000925 delete[] Buf;
Justin Bognercd45f962014-06-19 19:35:39 +0000926
927 if (BytesRead < 0 || BytesWritten < 0)
928 return std::error_code(errno, std::generic_category());
929 return std::error_code();
930}
931
Zachary Turner82a0c972017-03-20 23:33:18 +0000932ErrorOr<MD5::MD5Result> md5_contents(int FD) {
933 MD5 Hash;
934
935 constexpr size_t BufSize = 4096;
936 std::vector<uint8_t> Buf(BufSize);
937 int BytesRead = 0;
938 for (;;) {
939 BytesRead = read(FD, Buf.data(), BufSize);
940 if (BytesRead <= 0)
941 break;
942 Hash.update(makeArrayRef(Buf.data(), BytesRead));
943 }
944
945 if (BytesRead < 0)
946 return std::error_code(errno, std::generic_category());
947 MD5::MD5Result Result;
948 Hash.final(Result);
949 return Result;
950}
951
952ErrorOr<MD5::MD5Result> md5_contents(const Twine &Path) {
953 int FD;
954 if (auto EC = openFileForRead(Path, FD))
955 return EC;
956
957 auto Result = md5_contents(FD);
958 close(FD);
959 return Result;
960}
961
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000962bool exists(const basic_file_status &status) {
Michael J. Spencer730f51a2010-12-09 17:37:02 +0000963 return status_known(status) && status.type() != file_type::file_not_found;
964}
965
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000966bool status_known(const basic_file_status &s) {
Michael J. Spencer730f51a2010-12-09 17:37:02 +0000967 return s.type() != file_type::status_error;
968}
969
Zachary Turner82dd5422017-03-07 16:10:10 +0000970file_type get_file_type(const Twine &Path, bool Follow) {
Zachary Turner990e3cd2017-03-07 03:43:17 +0000971 file_status st;
Zachary Turner82dd5422017-03-07 16:10:10 +0000972 if (status(Path, st, Follow))
Zachary Turner990e3cd2017-03-07 03:43:17 +0000973 return file_type::status_error;
974 return st.type();
975}
976
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000977bool is_directory(const basic_file_status &status) {
Michael J. Spencer730f51a2010-12-09 17:37:02 +0000978 return status.type() == file_type::directory_file;
979}
980
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000981std::error_code is_directory(const Twine &path, bool &result) {
Michael J. Spencer0d771ed2011-01-11 01:21:55 +0000982 file_status st;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000983 if (std::error_code ec = status(path, st))
Michael J. Spencer0d771ed2011-01-11 01:21:55 +0000984 return ec;
985 result = is_directory(st);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000986 return std::error_code();
Michael J. Spencer0d771ed2011-01-11 01:21:55 +0000987}
988
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000989bool is_regular_file(const basic_file_status &status) {
Michael J. Spencer730f51a2010-12-09 17:37:02 +0000990 return status.type() == file_type::regular_file;
991}
992
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000993std::error_code is_regular_file(const Twine &path, bool &result) {
Michael J. Spencer0d771ed2011-01-11 01:21:55 +0000994 file_status st;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000995 if (std::error_code ec = status(path, st))
Michael J. Spencer0d771ed2011-01-11 01:21:55 +0000996 return ec;
997 result = is_regular_file(st);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000998 return std::error_code();
Michael J. Spencer0d771ed2011-01-11 01:21:55 +0000999}
1000
Peter Collingbourne0dfdb442017-10-10 22:19:46 +00001001bool is_symlink_file(const basic_file_status &status) {
Zachary Turner7d86ee52017-03-08 17:56:08 +00001002 return status.type() == file_type::symlink_file;
1003}
1004
1005std::error_code is_symlink_file(const Twine &path, bool &result) {
1006 file_status st;
1007 if (std::error_code ec = status(path, st, false))
1008 return ec;
1009 result = is_symlink_file(st);
1010 return std::error_code();
1011}
1012
Peter Collingbourne0dfdb442017-10-10 22:19:46 +00001013bool is_other(const basic_file_status &status) {
Michael J. Spencer730f51a2010-12-09 17:37:02 +00001014 return exists(status) &&
1015 !is_regular_file(status) &&
Rafael Espindola20063062014-03-20 17:39:04 +00001016 !is_directory(status);
Michael J. Spencer730f51a2010-12-09 17:37:02 +00001017}
1018
Juergen Ributzka84ba3422014-12-18 18:19:47 +00001019std::error_code is_other(const Twine &Path, bool &Result) {
1020 file_status FileStatus;
1021 if (std::error_code EC = status(Path, FileStatus))
1022 return EC;
1023 Result = is_other(FileStatus);
1024 return std::error_code();
1025}
1026
Peter Collingbourne0dfdb442017-10-10 22:19:46 +00001027void directory_entry::replace_filename(const Twine &filename,
1028 basic_file_status st) {
Rafael Espindolaf662e002015-07-15 21:24:07 +00001029 SmallString<128> path = path::parent_path(Path);
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +00001030 path::append(path, filename);
1031 Path = path.str();
1032 Status = st;
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +00001033}
1034
James Henderson566fdf42017-03-16 11:22:09 +00001035ErrorOr<perms> getPermissions(const Twine &Path) {
1036 file_status Status;
1037 if (std::error_code EC = status(Path, Status))
1038 return EC;
1039
1040 return Status.permissions();
1041}
1042
Aaron Ballman345012d2017-03-13 12:24:51 +00001043} // end namespace fs
1044} // end namespace sys
1045} // end namespace llvm
Michael J. Spencerebad2f92010-11-29 22:28:51 +00001046
1047// Include the truly platform-specific parts.
1048#if defined(LLVM_ON_UNIX)
Rafael Espindolaf1fc3822013-06-26 19:33:03 +00001049#include "Unix/Path.inc"
Michael J. Spencerebad2f92010-11-29 22:28:51 +00001050#endif
1051#if defined(LLVM_ON_WIN32)
Rafael Espindolaf1fc3822013-06-26 19:33:03 +00001052#include "Windows/Path.inc"
Michael J. Spencerebad2f92010-11-29 22:28:51 +00001053#endif
Pawel Bylica0e97e5c2015-11-02 09:49:17 +00001054
1055namespace llvm {
1056namespace sys {
Rafael Espindola2c4e9202017-11-28 01:34:20 +00001057namespace fs {
1058TempFile::TempFile(StringRef Name, int FD) : TmpName(Name), FD(FD) {}
1059TempFile::TempFile(TempFile &&Other) { *this = std::move(Other); }
1060TempFile &TempFile::operator=(TempFile &&Other) {
1061 TmpName = std::move(Other.TmpName);
1062 FD = Other.FD;
1063 Other.Done = true;
1064 return *this;
1065}
1066
1067TempFile::~TempFile() { assert(Done); }
1068
1069Error TempFile::discard() {
1070 Done = true;
Rafael Espindola2c4e9202017-11-28 01:34:20 +00001071 std::error_code RemoveEC;
Rafael Espindola3ecd2042017-11-28 01:41:22 +00001072// On windows closing will remove the file.
1073#ifndef LLVM_ON_WIN32
1074 // Always try to close and remove.
Rafael Espindola2c4e9202017-11-28 01:34:20 +00001075 if (!TmpName.empty()) {
1076 RemoveEC = fs::remove(TmpName);
1077 sys::DontRemoveFileOnSignal(TmpName);
1078 }
Rafael Espindola3ecd2042017-11-28 01:41:22 +00001079#endif
Rafael Espindola2c4e9202017-11-28 01:34:20 +00001080
1081 if (!RemoveEC)
1082 TmpName = "";
1083
1084 if (FD != -1 && close(FD) == -1) {
1085 std::error_code EC = std::error_code(errno, std::generic_category());
1086 return errorCodeToError(EC);
1087 }
1088 FD = -1;
1089
1090 return errorCodeToError(RemoveEC);
1091}
1092
1093Error TempFile::keep(const Twine &Name) {
1094 assert(!Done);
1095 Done = true;
1096 // Always try to close and rename.
Rafael Espindola3ecd2042017-11-28 01:41:22 +00001097#ifdef LLVM_ON_WIN32
1098 // If we cant't cancel the delete don't rename.
1099 std::error_code RenameEC = cancelDeleteOnClose(FD);
1100 if (!RenameEC)
1101 RenameEC = rename_fd(FD, Name);
Rafael Espindola20569e92017-12-05 16:40:56 +00001102 // If we can't rename, discard the temporary file.
1103 if (RenameEC)
1104 removeFD(FD);
Rafael Espindola3ecd2042017-11-28 01:41:22 +00001105#else
Rafael Espindola2c4e9202017-11-28 01:34:20 +00001106 std::error_code RenameEC = fs::rename(TmpName, Name);
Rafael Espindola20569e92017-12-05 16:40:56 +00001107 // If we can't rename, discard the temporary file.
1108 if (RenameEC)
1109 remove(TmpName);
Rafael Espindola2c4e9202017-11-28 01:34:20 +00001110 sys::DontRemoveFileOnSignal(TmpName);
Rafael Espindola3ecd2042017-11-28 01:41:22 +00001111#endif
Rafael Espindola2c4e9202017-11-28 01:34:20 +00001112
1113 if (!RenameEC)
1114 TmpName = "";
1115
1116 if (close(FD) == -1) {
1117 std::error_code EC(errno, std::generic_category());
1118 return errorCodeToError(EC);
1119 }
1120 FD = -1;
1121
1122 return errorCodeToError(RenameEC);
1123}
1124
1125Error TempFile::keep() {
1126 assert(!Done);
1127 Done = true;
1128
Rafael Espindola3ecd2042017-11-28 01:41:22 +00001129#ifdef LLVM_ON_WIN32
1130 if (std::error_code EC = cancelDeleteOnClose(FD))
1131 return errorCodeToError(EC);
1132#else
Rafael Espindola2c4e9202017-11-28 01:34:20 +00001133 sys::DontRemoveFileOnSignal(TmpName);
Rafael Espindola3ecd2042017-11-28 01:41:22 +00001134#endif
1135
Rafael Espindola2c4e9202017-11-28 01:34:20 +00001136 TmpName = "";
1137
1138 if (close(FD) == -1) {
1139 std::error_code EC(errno, std::generic_category());
1140 return errorCodeToError(EC);
1141 }
1142 FD = -1;
1143
1144 return Error::success();
1145}
1146
1147Expected<TempFile> TempFile::create(const Twine &Model, unsigned Mode) {
1148 int FD;
1149 SmallString<128> ResultPath;
Rafael Espindola3ecd2042017-11-28 01:41:22 +00001150 if (std::error_code EC = createUniqueFile(Model, FD, ResultPath, Mode,
1151 sys::fs::F_RW | sys::fs::F_Delete))
Rafael Espindola2c4e9202017-11-28 01:34:20 +00001152 return errorCodeToError(EC);
1153
Rafael Espindola2c4e9202017-11-28 01:34:20 +00001154 TempFile Ret(ResultPath, FD);
Rafael Espindola3ecd2042017-11-28 01:41:22 +00001155#ifndef LLVM_ON_WIN32
Rafael Espindola2c4e9202017-11-28 01:34:20 +00001156 if (sys::RemoveFileOnSignal(ResultPath)) {
Rafael Espindola3ecd2042017-11-28 01:41:22 +00001157 // Make sure we delete the file when RemoveFileOnSignal fails.
Rafael Espindola2c4e9202017-11-28 01:34:20 +00001158 consumeError(Ret.discard());
1159 std::error_code EC(errc::operation_not_permitted);
1160 return errorCodeToError(EC);
1161 }
Rafael Espindola3ecd2042017-11-28 01:41:22 +00001162#endif
Rafael Espindola2c4e9202017-11-28 01:34:20 +00001163 return std::move(Ret);
1164}
1165}
1166
Pawel Bylica0e97e5c2015-11-02 09:49:17 +00001167namespace path {
1168
1169bool user_cache_directory(SmallVectorImpl<char> &Result, const Twine &Path1,
1170 const Twine &Path2, const Twine &Path3) {
1171 if (getUserCacheDir(Result)) {
1172 append(Result, Path1, Path2, Path3);
1173 return true;
1174 }
1175 return false;
1176}
1177
1178} // end namespace path
1179} // end namsspace sys
1180} // end namespace llvm