blob: ec8a5ca98e556766c539b50f07526febd0f16414 [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,
Ilya Biryukov84185762018-03-19 14:19:58 +0000760 SmallVectorImpl<char> &ResultPath,
761 unsigned Mode) {
762 int FD;
763 auto EC = createUniqueFile(Model, FD, ResultPath, Mode);
764 if (EC)
765 return EC;
766 // FD is only needed to avoid race conditions. Close it right away.
767 close(FD);
768 return EC;
Rafael Espindolac9d2e5b2013-07-05 21:01:08 +0000769}
770
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000771static std::error_code
772createTemporaryFile(const Twine &Model, int &ResultFD,
Rafael Espindolad19c2e82017-11-27 23:44:11 +0000773 llvm::SmallVectorImpl<char> &ResultPath, FSEntity Type,
774 sys::fs::OpenFlags Flags) {
Rafael Espindola325fa0f2013-07-05 19:56:49 +0000775 SmallString<128> Storage;
776 StringRef P = Model.toNullTerminatedStringRef(Storage);
Zachary Turner5c5091f2017-03-16 22:28:04 +0000777 assert(P.find_first_of(separators(Style::native)) == StringRef::npos &&
Rafael Espindola325fa0f2013-07-05 19:56:49 +0000778 "Model must be a simple filename.");
779 // Use P.begin() so that createUniqueEntity doesn't need to recreate Storage.
Rafael Espindolad19c2e82017-11-27 23:44:11 +0000780 return createUniqueEntity(P.begin(), ResultFD, ResultPath, true,
781 owner_read | owner_write, Type, Flags);
Rafael Espindola325fa0f2013-07-05 19:56:49 +0000782}
783
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000784static std::error_code
Rafael Espindola325fa0f2013-07-05 19:56:49 +0000785createTemporaryFile(const Twine &Prefix, StringRef Suffix, int &ResultFD,
Rafael Espindolad19c2e82017-11-27 23:44:11 +0000786 llvm::SmallVectorImpl<char> &ResultPath, FSEntity Type,
787 sys::fs::OpenFlags Flags = sys::fs::F_None) {
Rafael Espindolad3c89042013-07-25 15:00:17 +0000788 const char *Middle = Suffix.empty() ? "-%%%%%%" : "-%%%%%%.";
789 return createTemporaryFile(Prefix + Middle + Suffix, ResultFD, ResultPath,
Rafael Espindolad19c2e82017-11-27 23:44:11 +0000790 Type, Flags);
Rafael Espindola325fa0f2013-07-05 19:56:49 +0000791}
792
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000793std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
794 int &ResultFD,
Rafael Espindolad19c2e82017-11-27 23:44:11 +0000795 SmallVectorImpl<char> &ResultPath,
796 sys::fs::OpenFlags Flags) {
797 return createTemporaryFile(Prefix, Suffix, ResultFD, ResultPath, FS_File,
798 Flags);
Rafael Espindola325fa0f2013-07-05 19:56:49 +0000799}
800
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000801std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
802 SmallVectorImpl<char> &ResultPath) {
Ilya Biryukov84185762018-03-19 14:19:58 +0000803 int FD;
804 auto EC = createTemporaryFile(Prefix, Suffix, FD, ResultPath);
805 if (EC)
806 return EC;
807 // FD is only needed to avoid race conditions. Close it right away.
808 close(FD);
809 return EC;
Rafael Espindola325fa0f2013-07-05 19:56:49 +0000810}
811
812
Rafael Espindolae79a8722013-06-28 03:48:47 +0000813// This is a mkdtemp with a different pattern. We use createUniqueEntity mostly
Rafael Espindola31a24432013-06-28 10:55:41 +0000814// for consistency. We should try using mkdtemp.
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000815std::error_code createUniqueDirectory(const Twine &Prefix,
816 SmallVectorImpl<char> &ResultPath) {
Rafael Espindolae79a8722013-06-28 03:48:47 +0000817 int Dummy;
Ilya Biryukov84185762018-03-19 14:19:58 +0000818 return createUniqueEntity(Prefix + "-%%%%%%", Dummy, ResultPath, true, 0,
819 FS_Dir);
820}
821
822std::error_code
823getPotentiallyUniqueFileName(const Twine &Model,
824 SmallVectorImpl<char> &ResultPath) {
825 int Dummy;
826 return createUniqueEntity(Model, Dummy, ResultPath, false, 0, FS_Name);
827}
828
829std::error_code
830getPotentiallyUniqueTempFileName(const Twine &Prefix, StringRef Suffix,
831 SmallVectorImpl<char> &ResultPath) {
832 int Dummy;
833 return createTemporaryFile(Prefix, Suffix, Dummy, ResultPath, FS_Name);
Rafael Espindola7ffacc42013-06-27 03:45:31 +0000834}
835
Benjamin Kramerae1d5992015-10-05 13:02:43 +0000836static std::error_code make_absolute(const Twine &current_directory,
837 SmallVectorImpl<char> &path,
838 bool use_current_directory) {
Michael J. Spencer92903a32010-12-07 03:57:17 +0000839 StringRef p(path.data(), path.size());
840
Zachary Turner5c5091f2017-03-16 22:28:04 +0000841 bool rootDirectory = path::has_root_directory(p);
842 bool rootName =
843 (real_style(Style::native) != Style::windows) || path::has_root_name(p);
Michael J. Spencer92903a32010-12-07 03:57:17 +0000844
845 // Already absolute.
846 if (rootName && rootDirectory)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000847 return std::error_code();
Michael J. Spencer92903a32010-12-07 03:57:17 +0000848
849 // All of the following conditions will need the current directory.
850 SmallString<128> current_dir;
Benjamin Kramerae1d5992015-10-05 13:02:43 +0000851 if (use_current_directory)
852 current_directory.toVector(current_dir);
853 else if (std::error_code ec = current_path(current_dir))
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000854 return ec;
Michael J. Spencer92903a32010-12-07 03:57:17 +0000855
856 // Relative path. Prepend the current directory.
857 if (!rootName && !rootDirectory) {
858 // Append path to the current directory.
Michael J. Spencer1e090f02010-12-07 03:57:37 +0000859 path::append(current_dir, p);
Michael J. Spencer92903a32010-12-07 03:57:17 +0000860 // Set path to the result.
861 path.swap(current_dir);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000862 return std::error_code();
Michael J. Spencer92903a32010-12-07 03:57:17 +0000863 }
864
865 if (!rootName && rootDirectory) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000866 StringRef cdrn = path::root_name(current_dir);
Michael J. Spencer92903a32010-12-07 03:57:17 +0000867 SmallString<128> curDirRootName(cdrn.begin(), cdrn.end());
Michael J. Spencer1e090f02010-12-07 03:57:37 +0000868 path::append(curDirRootName, p);
Michael J. Spencer92903a32010-12-07 03:57:17 +0000869 // Set path to the result.
870 path.swap(curDirRootName);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000871 return std::error_code();
Michael J. Spencer92903a32010-12-07 03:57:17 +0000872 }
873
874 if (rootName && !rootDirectory) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000875 StringRef pRootName = path::root_name(p);
876 StringRef bRootDirectory = path::root_directory(current_dir);
877 StringRef bRelativePath = path::relative_path(current_dir);
878 StringRef pRelativePath = path::relative_path(p);
Michael J. Spencer92903a32010-12-07 03:57:17 +0000879
880 SmallString<128> res;
Michael J. Spencer1e090f02010-12-07 03:57:37 +0000881 path::append(res, pRootName, bRootDirectory, bRelativePath, pRelativePath);
Michael J. Spencer92903a32010-12-07 03:57:17 +0000882 path.swap(res);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000883 return std::error_code();
Michael J. Spencer92903a32010-12-07 03:57:17 +0000884 }
885
886 llvm_unreachable("All rootName and rootDirectory combinations should have "
887 "occurred above!");
888}
889
Benjamin Kramerae1d5992015-10-05 13:02:43 +0000890std::error_code make_absolute(const Twine &current_directory,
891 SmallVectorImpl<char> &path) {
892 return make_absolute(current_directory, path, true);
893}
894
895std::error_code make_absolute(SmallVectorImpl<char> &path) {
896 return make_absolute(Twine(), path, false);
897}
898
Frederic Riss6b9396c2015-08-06 21:04:55 +0000899std::error_code create_directories(const Twine &Path, bool IgnoreExisting,
900 perms Perms) {
Rafael Espindolab6f72b22014-02-13 16:58:19 +0000901 SmallString<128> PathStorage;
902 StringRef P = Path.toStringRef(PathStorage);
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000903
Rafael Espindolab6f72b22014-02-13 16:58:19 +0000904 // Be optimistic and try to create the directory
Frederic Riss6b9396c2015-08-06 21:04:55 +0000905 std::error_code EC = create_directory(P, IgnoreExisting, Perms);
Rafael Espindolab6f72b22014-02-13 16:58:19 +0000906 // If we succeeded, or had any error other than the parent not existing, just
907 // return it.
Rafael Espindola2a826e42014-06-13 17:20:48 +0000908 if (EC != errc::no_such_file_or_directory)
Rafael Espindolab6f72b22014-02-13 16:58:19 +0000909 return EC;
Michael J. Spencerf616b212010-12-07 17:04:04 +0000910
Rafael Espindolab6f72b22014-02-13 16:58:19 +0000911 // We failed because of a no_such_file_or_directory, try to create the
912 // parent.
913 StringRef Parent = path::parent_path(P);
914 if (Parent.empty())
915 return EC;
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000916
Frederic Riss6b9396c2015-08-06 21:04:55 +0000917 if ((EC = create_directories(Parent, IgnoreExisting, Perms)))
Rafael Espindolab6f72b22014-02-13 16:58:19 +0000918 return EC;
919
Frederic Riss6b9396c2015-08-06 21:04:55 +0000920 return create_directory(P, IgnoreExisting, Perms);
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000921}
922
Justin Bognercd45f962014-06-19 19:35:39 +0000923std::error_code copy_file(const Twine &From, const Twine &To) {
924 int ReadFD, WriteFD;
925 if (std::error_code EC = openFileForRead(From, ReadFD))
926 return EC;
927 if (std::error_code EC = openFileForWrite(To, WriteFD, F_None)) {
928 close(ReadFD);
929 return EC;
930 }
931
932 const size_t BufSize = 4096;
Dylan Noblesmith42836d92014-08-26 02:03:30 +0000933 char *Buf = new char[BufSize];
Justin Bognercd45f962014-06-19 19:35:39 +0000934 int BytesRead = 0, BytesWritten = 0;
935 for (;;) {
936 BytesRead = read(ReadFD, Buf, BufSize);
937 if (BytesRead <= 0)
938 break;
939 while (BytesRead) {
940 BytesWritten = write(WriteFD, Buf, BytesRead);
941 if (BytesWritten < 0)
942 break;
943 BytesRead -= BytesWritten;
944 }
945 if (BytesWritten < 0)
946 break;
947 }
948 close(ReadFD);
949 close(WriteFD);
Dylan Noblesmith42836d92014-08-26 02:03:30 +0000950 delete[] Buf;
Justin Bognercd45f962014-06-19 19:35:39 +0000951
952 if (BytesRead < 0 || BytesWritten < 0)
953 return std::error_code(errno, std::generic_category());
954 return std::error_code();
955}
956
Zachary Turner82a0c972017-03-20 23:33:18 +0000957ErrorOr<MD5::MD5Result> md5_contents(int FD) {
958 MD5 Hash;
959
960 constexpr size_t BufSize = 4096;
961 std::vector<uint8_t> Buf(BufSize);
962 int BytesRead = 0;
963 for (;;) {
964 BytesRead = read(FD, Buf.data(), BufSize);
965 if (BytesRead <= 0)
966 break;
967 Hash.update(makeArrayRef(Buf.data(), BytesRead));
968 }
969
970 if (BytesRead < 0)
971 return std::error_code(errno, std::generic_category());
972 MD5::MD5Result Result;
973 Hash.final(Result);
974 return Result;
975}
976
977ErrorOr<MD5::MD5Result> md5_contents(const Twine &Path) {
978 int FD;
979 if (auto EC = openFileForRead(Path, FD))
980 return EC;
981
982 auto Result = md5_contents(FD);
983 close(FD);
984 return Result;
985}
986
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000987bool exists(const basic_file_status &status) {
Michael J. Spencer730f51a2010-12-09 17:37:02 +0000988 return status_known(status) && status.type() != file_type::file_not_found;
989}
990
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000991bool status_known(const basic_file_status &s) {
Michael J. Spencer730f51a2010-12-09 17:37:02 +0000992 return s.type() != file_type::status_error;
993}
994
Zachary Turner82dd5422017-03-07 16:10:10 +0000995file_type get_file_type(const Twine &Path, bool Follow) {
Zachary Turner990e3cd2017-03-07 03:43:17 +0000996 file_status st;
Zachary Turner82dd5422017-03-07 16:10:10 +0000997 if (status(Path, st, Follow))
Zachary Turner990e3cd2017-03-07 03:43:17 +0000998 return file_type::status_error;
999 return st.type();
1000}
1001
Peter Collingbourne0dfdb442017-10-10 22:19:46 +00001002bool is_directory(const basic_file_status &status) {
Michael J. Spencer730f51a2010-12-09 17:37:02 +00001003 return status.type() == file_type::directory_file;
1004}
1005
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001006std::error_code is_directory(const Twine &path, bool &result) {
Michael J. Spencer0d771ed2011-01-11 01:21:55 +00001007 file_status st;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001008 if (std::error_code ec = status(path, st))
Michael J. Spencer0d771ed2011-01-11 01:21:55 +00001009 return ec;
1010 result = is_directory(st);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001011 return std::error_code();
Michael J. Spencer0d771ed2011-01-11 01:21:55 +00001012}
1013
Peter Collingbourne0dfdb442017-10-10 22:19:46 +00001014bool is_regular_file(const basic_file_status &status) {
Michael J. Spencer730f51a2010-12-09 17:37:02 +00001015 return status.type() == file_type::regular_file;
1016}
1017
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001018std::error_code is_regular_file(const Twine &path, bool &result) {
Michael J. Spencer0d771ed2011-01-11 01:21:55 +00001019 file_status st;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001020 if (std::error_code ec = status(path, st))
Michael J. Spencer0d771ed2011-01-11 01:21:55 +00001021 return ec;
1022 result = is_regular_file(st);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001023 return std::error_code();
Michael J. Spencer0d771ed2011-01-11 01:21:55 +00001024}
1025
Peter Collingbourne0dfdb442017-10-10 22:19:46 +00001026bool is_symlink_file(const basic_file_status &status) {
Zachary Turner7d86ee52017-03-08 17:56:08 +00001027 return status.type() == file_type::symlink_file;
1028}
1029
1030std::error_code is_symlink_file(const Twine &path, bool &result) {
1031 file_status st;
1032 if (std::error_code ec = status(path, st, false))
1033 return ec;
1034 result = is_symlink_file(st);
1035 return std::error_code();
1036}
1037
Peter Collingbourne0dfdb442017-10-10 22:19:46 +00001038bool is_other(const basic_file_status &status) {
Michael J. Spencer730f51a2010-12-09 17:37:02 +00001039 return exists(status) &&
1040 !is_regular_file(status) &&
Rafael Espindola20063062014-03-20 17:39:04 +00001041 !is_directory(status);
Michael J. Spencer730f51a2010-12-09 17:37:02 +00001042}
1043
Juergen Ributzka84ba3422014-12-18 18:19:47 +00001044std::error_code is_other(const Twine &Path, bool &Result) {
1045 file_status FileStatus;
1046 if (std::error_code EC = status(Path, FileStatus))
1047 return EC;
1048 Result = is_other(FileStatus);
1049 return std::error_code();
1050}
1051
Peter Collingbourne0dfdb442017-10-10 22:19:46 +00001052void directory_entry::replace_filename(const Twine &filename,
1053 basic_file_status st) {
Rafael Espindolaf662e002015-07-15 21:24:07 +00001054 SmallString<128> path = path::parent_path(Path);
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +00001055 path::append(path, filename);
1056 Path = path.str();
1057 Status = st;
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +00001058}
1059
James Henderson566fdf42017-03-16 11:22:09 +00001060ErrorOr<perms> getPermissions(const Twine &Path) {
1061 file_status Status;
1062 if (std::error_code EC = status(Path, Status))
1063 return EC;
1064
1065 return Status.permissions();
1066}
1067
Aaron Ballman345012d2017-03-13 12:24:51 +00001068} // end namespace fs
1069} // end namespace sys
1070} // end namespace llvm
Michael J. Spencerebad2f92010-11-29 22:28:51 +00001071
1072// Include the truly platform-specific parts.
1073#if defined(LLVM_ON_UNIX)
Rafael Espindolaf1fc3822013-06-26 19:33:03 +00001074#include "Unix/Path.inc"
Michael J. Spencerebad2f92010-11-29 22:28:51 +00001075#endif
1076#if defined(LLVM_ON_WIN32)
Rafael Espindolaf1fc3822013-06-26 19:33:03 +00001077#include "Windows/Path.inc"
Michael J. Spencerebad2f92010-11-29 22:28:51 +00001078#endif
Pawel Bylica0e97e5c2015-11-02 09:49:17 +00001079
1080namespace llvm {
1081namespace sys {
Rafael Espindola2c4e9202017-11-28 01:34:20 +00001082namespace fs {
1083TempFile::TempFile(StringRef Name, int FD) : TmpName(Name), FD(FD) {}
1084TempFile::TempFile(TempFile &&Other) { *this = std::move(Other); }
1085TempFile &TempFile::operator=(TempFile &&Other) {
1086 TmpName = std::move(Other.TmpName);
1087 FD = Other.FD;
1088 Other.Done = true;
1089 return *this;
1090}
1091
1092TempFile::~TempFile() { assert(Done); }
1093
1094Error TempFile::discard() {
1095 Done = true;
Rafael Espindola2c4e9202017-11-28 01:34:20 +00001096 std::error_code RemoveEC;
Rafael Espindola3ecd2042017-11-28 01:41:22 +00001097// On windows closing will remove the file.
1098#ifndef LLVM_ON_WIN32
1099 // Always try to close and remove.
Rafael Espindola2c4e9202017-11-28 01:34:20 +00001100 if (!TmpName.empty()) {
1101 RemoveEC = fs::remove(TmpName);
1102 sys::DontRemoveFileOnSignal(TmpName);
1103 }
Rafael Espindola3ecd2042017-11-28 01:41:22 +00001104#endif
Rafael Espindola2c4e9202017-11-28 01:34:20 +00001105
1106 if (!RemoveEC)
1107 TmpName = "";
1108
1109 if (FD != -1 && close(FD) == -1) {
1110 std::error_code EC = std::error_code(errno, std::generic_category());
1111 return errorCodeToError(EC);
1112 }
1113 FD = -1;
1114
1115 return errorCodeToError(RemoveEC);
1116}
1117
1118Error TempFile::keep(const Twine &Name) {
1119 assert(!Done);
1120 Done = true;
1121 // Always try to close and rename.
Rafael Espindola3ecd2042017-11-28 01:41:22 +00001122#ifdef LLVM_ON_WIN32
1123 // If we cant't cancel the delete don't rename.
1124 std::error_code RenameEC = cancelDeleteOnClose(FD);
1125 if (!RenameEC)
1126 RenameEC = rename_fd(FD, Name);
Rafael Espindola20569e92017-12-05 16:40:56 +00001127 // If we can't rename, discard the temporary file.
1128 if (RenameEC)
1129 removeFD(FD);
Rafael Espindola3ecd2042017-11-28 01:41:22 +00001130#else
Rafael Espindola2c4e9202017-11-28 01:34:20 +00001131 std::error_code RenameEC = fs::rename(TmpName, Name);
Rafael Espindola20569e92017-12-05 16:40:56 +00001132 // If we can't rename, discard the temporary file.
1133 if (RenameEC)
1134 remove(TmpName);
Rafael Espindola2c4e9202017-11-28 01:34:20 +00001135 sys::DontRemoveFileOnSignal(TmpName);
Rafael Espindola3ecd2042017-11-28 01:41:22 +00001136#endif
Rafael Espindola2c4e9202017-11-28 01:34:20 +00001137
1138 if (!RenameEC)
1139 TmpName = "";
1140
1141 if (close(FD) == -1) {
1142 std::error_code EC(errno, std::generic_category());
1143 return errorCodeToError(EC);
1144 }
1145 FD = -1;
1146
1147 return errorCodeToError(RenameEC);
1148}
1149
1150Error TempFile::keep() {
1151 assert(!Done);
1152 Done = true;
1153
Rafael Espindola3ecd2042017-11-28 01:41:22 +00001154#ifdef LLVM_ON_WIN32
1155 if (std::error_code EC = cancelDeleteOnClose(FD))
1156 return errorCodeToError(EC);
1157#else
Rafael Espindola2c4e9202017-11-28 01:34:20 +00001158 sys::DontRemoveFileOnSignal(TmpName);
Rafael Espindola3ecd2042017-11-28 01:41:22 +00001159#endif
1160
Rafael Espindola2c4e9202017-11-28 01:34:20 +00001161 TmpName = "";
1162
1163 if (close(FD) == -1) {
1164 std::error_code EC(errno, std::generic_category());
1165 return errorCodeToError(EC);
1166 }
1167 FD = -1;
1168
1169 return Error::success();
1170}
1171
1172Expected<TempFile> TempFile::create(const Twine &Model, unsigned Mode) {
1173 int FD;
1174 SmallString<128> ResultPath;
Rafael Espindola3ecd2042017-11-28 01:41:22 +00001175 if (std::error_code EC = createUniqueFile(Model, FD, ResultPath, Mode,
1176 sys::fs::F_RW | sys::fs::F_Delete))
Rafael Espindola2c4e9202017-11-28 01:34:20 +00001177 return errorCodeToError(EC);
1178
Rafael Espindola2c4e9202017-11-28 01:34:20 +00001179 TempFile Ret(ResultPath, FD);
Rafael Espindola3ecd2042017-11-28 01:41:22 +00001180#ifndef LLVM_ON_WIN32
Rafael Espindola2c4e9202017-11-28 01:34:20 +00001181 if (sys::RemoveFileOnSignal(ResultPath)) {
Rafael Espindola3ecd2042017-11-28 01:41:22 +00001182 // Make sure we delete the file when RemoveFileOnSignal fails.
Rafael Espindola2c4e9202017-11-28 01:34:20 +00001183 consumeError(Ret.discard());
1184 std::error_code EC(errc::operation_not_permitted);
1185 return errorCodeToError(EC);
1186 }
Rafael Espindola3ecd2042017-11-28 01:41:22 +00001187#endif
Rafael Espindola2c4e9202017-11-28 01:34:20 +00001188 return std::move(Ret);
1189}
1190}
1191
Pawel Bylica0e97e5c2015-11-02 09:49:17 +00001192namespace path {
1193
1194bool user_cache_directory(SmallVectorImpl<char> &Result, const Twine &Path1,
1195 const Twine &Path2, const Twine &Path3) {
1196 if (getUserCacheDir(Result)) {
1197 append(Result, Path1, Path2, Path3);
1198 return true;
1199 }
1200 return false;
1201}
1202
1203} // end namespace path
1204} // end namsspace sys
1205} // end namespace llvm