blob: cc507874b00b75a0dda9335f5ceb2a8e24fcd1fb [file] [log] [blame]
Rafael Espindolaf1fc3822013-06-26 19:33:03 +00001//===-- Path.cpp - Implement OS Path Concept ------------------------------===//
Michael J. Spencerebad2f92010-11-29 22:28:51 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Rafael Espindolaf1fc3822013-06-26 19:33:03 +000010// This file implements the operating system Path API.
Michael J. Spencerebad2f92010-11-29 22:28:51 +000011//
12//===----------------------------------------------------------------------===//
13
Zachary Turner82a0c972017-03-20 23:33:18 +000014#include "llvm/Support/Path.h"
15#include "llvm/ADT/ArrayRef.h"
Nico Weber432a3882018-04-30 14:59:11 +000016#include "llvm/Config/llvm-config.h"
Rui Ueyama5c69ff52014-09-11 22:34:32 +000017#include "llvm/Support/Endian.h"
Rafael Espindola2a826e42014-06-13 17:20:48 +000018#include "llvm/Support/Errc.h"
Michael J. Spencerebad2f92010-11-29 22:28:51 +000019#include "llvm/Support/ErrorHandling.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000020#include "llvm/Support/FileSystem.h"
Aaron Ballman07e76182014-02-11 03:40:14 +000021#include "llvm/Support/Process.h"
Rafael Espindola58fe67a2017-11-13 18:33:44 +000022#include "llvm/Support/Signals.h"
Michael J. Spencerebad2f92010-11-29 22:28:51 +000023#include <cctype>
Michael J. Spencer848f46b2010-12-28 01:49:01 +000024#include <cstring>
Rafael Espindola4526b1d2013-06-18 17:01:00 +000025
26#if !defined(_MSC_VER) && !defined(__MINGW32__)
Douglas Gregora86ddf02013-03-21 21:46:10 +000027#include <unistd.h>
Rafael Espindola4526b1d2013-06-18 17:01:00 +000028#else
29#include <io.h>
Douglas Gregora86ddf02013-03-21 21:46:10 +000030#endif
Michael J. Spencerebad2f92010-11-29 22:28:51 +000031
Rafael Espindola7a0b6402014-02-24 03:07:41 +000032using namespace llvm;
Rui Ueyama3206b792015-03-02 21:19:12 +000033using namespace llvm::support::endian;
Rafael Espindola7a0b6402014-02-24 03:07:41 +000034
Michael J. Spencerebad2f92010-11-29 22:28:51 +000035namespace {
36 using llvm::StringRef;
Zhanyong Wan606bb1a2011-02-11 21:24:40 +000037 using llvm::sys::path::is_separator;
Zachary Turner5c5091f2017-03-16 22:28:04 +000038 using llvm::sys::path::Style;
Michael J. Spencerebad2f92010-11-29 22:28:51 +000039
Zachary Turner5c5091f2017-03-16 22:28:04 +000040 inline Style real_style(Style style) {
Nico Weber712e8d22018-04-29 00:45:03 +000041#ifdef _WIN32
Zachary Turner5c5091f2017-03-16 22:28:04 +000042 return (style == Style::posix) ? Style::posix : Style::windows;
Michael J. Spencerebad2f92010-11-29 22:28:51 +000043#else
Zachary Turner5c5091f2017-03-16 22:28:04 +000044 return (style == Style::windows) ? Style::windows : Style::posix;
Michael J. Spencerebad2f92010-11-29 22:28:51 +000045#endif
Zachary Turner5c5091f2017-03-16 22:28:04 +000046 }
Michael J. Spencerebad2f92010-11-29 22:28:51 +000047
Zachary Turner5c5091f2017-03-16 22:28:04 +000048 inline const char *separators(Style style) {
49 if (real_style(style) == Style::windows)
50 return "\\/";
51 return "/";
52 }
53
54 inline char preferred_separator(Style style) {
55 if (real_style(style) == Style::windows)
56 return '\\';
57 return '/';
58 }
59
60 StringRef find_first_component(StringRef path, Style style) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +000061 // Look for this first component in the following order.
62 // * empty (in this case we return an empty string)
63 // * either C: or {//,\\}net.
64 // * {/,\}
Michael J. Spencerebad2f92010-11-29 22:28:51 +000065 // * {file,directory}name
66
67 if (path.empty())
68 return path;
69
Zachary Turner5c5091f2017-03-16 22:28:04 +000070 if (real_style(style) == Style::windows) {
71 // C:
72 if (path.size() >= 2 &&
73 std::isalpha(static_cast<unsigned char>(path[0])) && path[1] == ':')
74 return path.substr(0, 2);
75 }
Michael J. Spencerebad2f92010-11-29 22:28:51 +000076
77 // //net
Zachary Turner5c5091f2017-03-16 22:28:04 +000078 if ((path.size() > 2) && is_separator(path[0], style) &&
79 path[0] == path[1] && !is_separator(path[2], style)) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +000080 // Find the next directory separator.
Zachary Turner5c5091f2017-03-16 22:28:04 +000081 size_t end = path.find_first_of(separators(style), 2);
Benjamin Kramerffa42ce2010-12-17 20:27:37 +000082 return path.substr(0, end);
Michael J. Spencerebad2f92010-11-29 22:28:51 +000083 }
84
85 // {/,\}
Zachary Turner5c5091f2017-03-16 22:28:04 +000086 if (is_separator(path[0], style))
Benjamin Kramerffa42ce2010-12-17 20:27:37 +000087 return path.substr(0, 1);
Michael J. Spencerebad2f92010-11-29 22:28:51 +000088
Michael J. Spencerebad2f92010-11-29 22:28:51 +000089 // * {file,directory}name
Zachary Turner5c5091f2017-03-16 22:28:04 +000090 size_t end = path.find_first_of(separators(style));
Benjamin Kramerffa42ce2010-12-17 20:27:37 +000091 return path.substr(0, end);
Michael J. Spencerebad2f92010-11-29 22:28:51 +000092 }
Michael J. Spencer545cbdf2010-11-30 23:28:07 +000093
Pavel Labathd20289b2018-05-09 13:21:16 +000094 // Returns the first character of the filename in str. For paths ending in
95 // '/', it returns the position of the '/'.
Zachary Turner5c5091f2017-03-16 22:28:04 +000096 size_t filename_pos(StringRef str, Style style) {
Zachary Turner5c5091f2017-03-16 22:28:04 +000097 if (str.size() > 0 && is_separator(str[str.size() - 1], style))
Michael J. Spencer545cbdf2010-11-30 23:28:07 +000098 return str.size() - 1;
99
Zachary Turner5c5091f2017-03-16 22:28:04 +0000100 size_t pos = str.find_last_of(separators(style), str.size() - 1);
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000101
Zachary Turner5c5091f2017-03-16 22:28:04 +0000102 if (real_style(style) == Style::windows) {
103 if (pos == StringRef::npos)
104 pos = str.find_last_of(':', str.size() - 2);
105 }
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000106
Zachary Turner5c5091f2017-03-16 22:28:04 +0000107 if (pos == StringRef::npos || (pos == 1 && is_separator(str[0], style)))
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000108 return 0;
109
110 return pos + 1;
111 }
112
Pavel Labathd20289b2018-05-09 13:21:16 +0000113 // Returns the position of the root directory in str. If there is no root
114 // directory in str, it returns StringRef::npos.
Zachary Turner5c5091f2017-03-16 22:28:04 +0000115 size_t root_dir_start(StringRef str, Style style) {
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000116 // case "c:/"
Zachary Turner5c5091f2017-03-16 22:28:04 +0000117 if (real_style(style) == Style::windows) {
118 if (str.size() > 2 && str[1] == ':' && is_separator(str[2], style))
119 return 2;
120 }
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000121
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000122 // case "//net"
Zachary Turner5c5091f2017-03-16 22:28:04 +0000123 if (str.size() > 3 && is_separator(str[0], style) && str[0] == str[1] &&
124 !is_separator(str[2], style)) {
125 return str.find_first_of(separators(style), 2);
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000126 }
127
128 // case "/"
Zachary Turner5c5091f2017-03-16 22:28:04 +0000129 if (str.size() > 0 && is_separator(str[0], style))
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000130 return 0;
131
132 return StringRef::npos;
133 }
134
Pavel Labathd20289b2018-05-09 13:21:16 +0000135 // Returns the position past the end of the "parent path" of path. The parent
136 // path will not end in '/', unless the parent is the root directory. If the
137 // path has no parent, 0 is returned.
Zachary Turner5c5091f2017-03-16 22:28:04 +0000138 size_t parent_path_end(StringRef path, Style style) {
139 size_t end_pos = filename_pos(path, style);
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000140
Zachary Turner5c5091f2017-03-16 22:28:04 +0000141 bool filename_was_sep =
142 path.size() > 0 && is_separator(path[end_pos], style);
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000143
Pavel Labathd20289b2018-05-09 13:21:16 +0000144 // Skip separators until we reach root dir (or the start of the string).
145 size_t root_dir_pos = root_dir_start(path, style);
146 while (end_pos > 0 &&
147 (root_dir_pos == StringRef::npos || end_pos > root_dir_pos) &&
Zachary Turner5c5091f2017-03-16 22:28:04 +0000148 is_separator(path[end_pos - 1], style))
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000149 --end_pos;
150
Pavel Labathd20289b2018-05-09 13:21:16 +0000151 if (end_pos == root_dir_pos && !filename_was_sep) {
152 // We've reached the root dir and the input path was *not* ending in a
153 // sequence of slashes. Include the root dir in the parent path.
154 return root_dir_pos + 1;
155 }
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000156
Pavel Labathd20289b2018-05-09 13:21:16 +0000157 // Otherwise, just include before the last slash.
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000158 return end_pos;
159 }
Zhanyong Wan606bb1a2011-02-11 21:24:40 +0000160} // end unnamed namespace
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000161
Rafael Espindolae79a8722013-06-28 03:48:47 +0000162enum FSEntity {
163 FS_Dir,
164 FS_File,
165 FS_Name
166};
167
Rafael Espindolad19c2e82017-11-27 23:44:11 +0000168static std::error_code
169createUniqueEntity(const Twine &Model, int &ResultFD,
170 SmallVectorImpl<char> &ResultPath, bool MakeAbsolute,
171 unsigned Mode, FSEntity Type,
Zachary Turner1f67a3c2018-06-07 19:58:58 +0000172 sys::fs::OpenFlags Flags = sys::fs::OF_None) {
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000173 SmallString<128> ModelStorage;
174 Model.toVector(ModelStorage);
175
176 if (MakeAbsolute) {
177 // Make model absolute by prepending a temp directory if it's not already.
178 if (!sys::path::is_absolute(Twine(ModelStorage))) {
179 SmallString<128> TDir;
Rafael Espindola016a6d52014-08-26 14:47:52 +0000180 sys::path::system_temp_directory(true, TDir);
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000181 sys::path::append(TDir, Twine(ModelStorage));
182 ModelStorage.swap(TDir);
183 }
184 }
185
186 // From here on, DO NOT modify model. It may be needed if the randomly chosen
187 // path already exists.
188 ResultPath = ModelStorage;
189 // Null terminate.
190 ResultPath.push_back(0);
191 ResultPath.pop_back();
192
193retry_random_path:
194 // Replace '%' with random chars.
195 for (unsigned i = 0, e = ModelStorage.size(); i != e; ++i) {
196 if (ModelStorage[i] == '%')
197 ResultPath[i] = "0123456789abcdef"[sys::Process::GetRandomNumber() & 15];
198 }
199
200 // Try to open + create the file.
201 switch (Type) {
202 case FS_File: {
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000203 if (std::error_code EC =
Zachary Turner1f67a3c2018-06-07 19:58:58 +0000204 sys::fs::openFileForReadWrite(Twine(ResultPath.begin()), ResultFD,
205 sys::fs::CD_CreateNew, Flags, Mode)) {
Rafael Espindola2a826e42014-06-13 17:20:48 +0000206 if (EC == errc::file_exists)
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000207 goto retry_random_path;
208 return EC;
209 }
210
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000211 return std::error_code();
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000212 }
213
214 case FS_Name: {
Rafael Espindola281f23a2014-09-11 20:30:02 +0000215 std::error_code EC =
216 sys::fs::access(ResultPath.begin(), sys::fs::AccessMode::Exist);
217 if (EC == errc::no_such_file_or_directory)
218 return std::error_code();
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000219 if (EC)
220 return EC;
Rafael Espindola281f23a2014-09-11 20:30:02 +0000221 goto retry_random_path;
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000222 }
223
224 case FS_Dir: {
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000225 if (std::error_code EC =
226 sys::fs::create_directory(ResultPath.begin(), false)) {
Rafael Espindola2a826e42014-06-13 17:20:48 +0000227 if (EC == errc::file_exists)
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000228 goto retry_random_path;
229 return EC;
230 }
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000231 return std::error_code();
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000232 }
233 }
234 llvm_unreachable("Invalid Type");
235}
Rafael Espindolae79a8722013-06-28 03:48:47 +0000236
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000237namespace llvm {
238namespace sys {
239namespace path {
240
Zachary Turner5c5091f2017-03-16 22:28:04 +0000241const_iterator begin(StringRef path, Style style) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000242 const_iterator i;
243 i.Path = path;
Zachary Turner5c5091f2017-03-16 22:28:04 +0000244 i.Component = find_first_component(path, style);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000245 i.Position = 0;
Zachary Turner5c5091f2017-03-16 22:28:04 +0000246 i.S = style;
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000247 return i;
248}
249
Benjamin Kramer292b44b2010-12-17 18:19:06 +0000250const_iterator end(StringRef path) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000251 const_iterator i;
252 i.Path = path;
253 i.Position = path.size();
254 return i;
255}
256
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000257const_iterator &const_iterator::operator++() {
258 assert(Position < Path.size() && "Tried to increment past end!");
259
260 // Increment Position to past the current component
261 Position += Component.size();
262
263 // Check for end.
264 if (Position == Path.size()) {
265 Component = StringRef();
266 return *this;
267 }
268
269 // Both POSIX and Windows treat paths that begin with exactly two separators
270 // specially.
Zachary Turner5c5091f2017-03-16 22:28:04 +0000271 bool was_net = Component.size() > 2 && is_separator(Component[0], S) &&
272 Component[1] == Component[0] && !is_separator(Component[2], S);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000273
274 // Handle separators.
Zachary Turner5c5091f2017-03-16 22:28:04 +0000275 if (is_separator(Path[Position], S)) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000276 // Root dir.
Zachary Turner5c5091f2017-03-16 22:28:04 +0000277 if (was_net ||
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000278 // c:/
Zachary Turner5c5091f2017-03-16 22:28:04 +0000279 (real_style(S) == Style::windows && Component.endswith(":"))) {
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000280 Component = Path.substr(Position, 1);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000281 return *this;
282 }
283
284 // Skip extra separators.
Zachary Turner5c5091f2017-03-16 22:28:04 +0000285 while (Position != Path.size() && is_separator(Path[Position], S)) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000286 ++Position;
287 }
288
Pavel Labathd20289b2018-05-09 13:21:16 +0000289 // Treat trailing '/' as a '.', unless it is the root dir.
290 if (Position == Path.size() && Component != "/") {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000291 --Position;
292 Component = ".";
293 return *this;
294 }
295 }
296
297 // Find next component.
Zachary Turner5c5091f2017-03-16 22:28:04 +0000298 size_t end_pos = Path.find_first_of(separators(S), Position);
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000299 Component = Path.slice(Position, end_pos);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000300
301 return *this;
302}
303
Justin Bogner487e7642014-08-04 17:36:41 +0000304bool const_iterator::operator==(const const_iterator &RHS) const {
305 return Path.begin() == RHS.Path.begin() && Position == RHS.Position;
306}
307
308ptrdiff_t const_iterator::operator-(const const_iterator &RHS) const {
309 return Position - RHS.Position;
310}
311
Zachary Turner5c5091f2017-03-16 22:28:04 +0000312reverse_iterator rbegin(StringRef Path, Style style) {
Justin Bogner487e7642014-08-04 17:36:41 +0000313 reverse_iterator I;
314 I.Path = Path;
315 I.Position = Path.size();
Zachary Turner5c5091f2017-03-16 22:28:04 +0000316 I.S = style;
Justin Bogner487e7642014-08-04 17:36:41 +0000317 return ++I;
318}
319
320reverse_iterator rend(StringRef Path) {
321 reverse_iterator I;
322 I.Path = Path;
323 I.Component = Path.substr(0, 0);
324 I.Position = 0;
325 return I;
326}
327
328reverse_iterator &reverse_iterator::operator++() {
Zachary Turner5c5091f2017-03-16 22:28:04 +0000329 size_t root_dir_pos = root_dir_start(Path, S);
Pavel Labathd20289b2018-05-09 13:21:16 +0000330
331 // Skip separators unless it's the root directory.
332 size_t end_pos = Position;
333 while (end_pos > 0 && (end_pos - 1) != root_dir_pos &&
334 is_separator(Path[end_pos - 1], S))
335 --end_pos;
336
337 // Treat trailing '/' as a '.', unless it is the root dir.
338 if (Position == Path.size() && !Path.empty() &&
339 is_separator(Path.back(), S) &&
340 (root_dir_pos == StringRef::npos || end_pos - 1 > root_dir_pos)) {
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000341 --Position;
342 Component = ".";
343 return *this;
344 }
345
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000346 // Find next separator.
Zachary Turner5c5091f2017-03-16 22:28:04 +0000347 size_t start_pos = filename_pos(Path.substr(0, end_pos), S);
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000348 Component = Path.slice(start_pos, end_pos);
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000349 Position = start_pos;
350 return *this;
351}
352
Justin Bogner487e7642014-08-04 17:36:41 +0000353bool reverse_iterator::operator==(const reverse_iterator &RHS) const {
354 return Path.begin() == RHS.Path.begin() && Component == RHS.Component &&
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000355 Position == RHS.Position;
356}
357
Filipe Cabecinhas78949382016-04-29 16:48:07 +0000358ptrdiff_t reverse_iterator::operator-(const reverse_iterator &RHS) const {
359 return Position - RHS.Position;
360}
361
Zachary Turner5c5091f2017-03-16 22:28:04 +0000362StringRef root_path(StringRef path, Style style) {
363 const_iterator b = begin(path, style), pos = b, e = end(path);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000364 if (b != e) {
Zachary Turner5c5091f2017-03-16 22:28:04 +0000365 bool has_net =
366 b->size() > 2 && is_separator((*b)[0], style) && (*b)[1] == (*b)[0];
367 bool has_drive = (real_style(style) == Style::windows) && b->endswith(":");
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000368
369 if (has_net || has_drive) {
Zachary Turner5c5091f2017-03-16 22:28:04 +0000370 if ((++pos != e) && is_separator((*pos)[0], style)) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000371 // {C:/,//net/}, so get the first two components.
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000372 return path.substr(0, b->size() + pos->size());
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000373 } else {
374 // just {C:,//net}, return the first component.
Michael J. Spencerf616b212010-12-07 17:04:04 +0000375 return *b;
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000376 }
377 }
378
379 // POSIX style root directory.
Zachary Turner5c5091f2017-03-16 22:28:04 +0000380 if (is_separator((*b)[0], style)) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000381 return *b;
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000382 }
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000383 }
384
Michael J. Spencerf616b212010-12-07 17:04:04 +0000385 return StringRef();
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000386}
387
Zachary Turner5c5091f2017-03-16 22:28:04 +0000388StringRef root_name(StringRef path, Style style) {
389 const_iterator b = begin(path, style), e = end(path);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000390 if (b != e) {
Zachary Turner5c5091f2017-03-16 22:28:04 +0000391 bool has_net =
392 b->size() > 2 && is_separator((*b)[0], style) && (*b)[1] == (*b)[0];
393 bool has_drive = (real_style(style) == Style::windows) && b->endswith(":");
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000394
395 if (has_net || has_drive) {
396 // just {C:,//net}, return the first component.
Michael J. Spencerf616b212010-12-07 17:04:04 +0000397 return *b;
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000398 }
399 }
400
401 // No path or no name.
Michael J. Spencerf616b212010-12-07 17:04:04 +0000402 return StringRef();
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000403}
404
Zachary Turner5c5091f2017-03-16 22:28:04 +0000405StringRef root_directory(StringRef path, Style style) {
406 const_iterator b = begin(path, style), pos = b, e = end(path);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000407 if (b != e) {
Zachary Turner5c5091f2017-03-16 22:28:04 +0000408 bool has_net =
409 b->size() > 2 && is_separator((*b)[0], style) && (*b)[1] == (*b)[0];
410 bool has_drive = (real_style(style) == Style::windows) && b->endswith(":");
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000411
412 if ((has_net || has_drive) &&
413 // {C:,//net}, skip to the next component.
Zachary Turner5c5091f2017-03-16 22:28:04 +0000414 (++pos != e) && is_separator((*pos)[0], style)) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000415 return *pos;
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000416 }
417
418 // POSIX style root directory.
Zachary Turner5c5091f2017-03-16 22:28:04 +0000419 if (!has_net && is_separator((*b)[0], style)) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000420 return *b;
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000421 }
422 }
423
424 // No path or no root.
Michael J. Spencerf616b212010-12-07 17:04:04 +0000425 return StringRef();
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000426}
427
Zachary Turner5c5091f2017-03-16 22:28:04 +0000428StringRef relative_path(StringRef path, Style style) {
429 StringRef root = root_path(path, style);
Michael J. Spencere6462392012-02-29 00:06:24 +0000430 return path.substr(root.size());
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000431}
432
Zachary Turner5c5091f2017-03-16 22:28:04 +0000433void append(SmallVectorImpl<char> &path, Style style, const Twine &a,
434 const Twine &b, const Twine &c, const Twine &d) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000435 SmallString<32> a_storage;
436 SmallString<32> b_storage;
437 SmallString<32> c_storage;
438 SmallString<32> d_storage;
439
440 SmallVector<StringRef, 4> components;
441 if (!a.isTriviallyEmpty()) components.push_back(a.toStringRef(a_storage));
442 if (!b.isTriviallyEmpty()) components.push_back(b.toStringRef(b_storage));
443 if (!c.isTriviallyEmpty()) components.push_back(c.toStringRef(c_storage));
444 if (!d.isTriviallyEmpty()) components.push_back(d.toStringRef(d_storage));
445
Pawel Bylica64d08ff2015-10-22 08:12:15 +0000446 for (auto &component : components) {
Zachary Turner5c5091f2017-03-16 22:28:04 +0000447 bool path_has_sep =
448 !path.empty() && is_separator(path[path.size() - 1], style);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000449 if (path_has_sep) {
450 // Strip separators from beginning of component.
Zachary Turner5c5091f2017-03-16 22:28:04 +0000451 size_t loc = component.find_first_not_of(separators(style));
Pawel Bylica64d08ff2015-10-22 08:12:15 +0000452 StringRef c = component.substr(loc);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000453
454 // Append it.
455 path.append(c.begin(), c.end());
456 continue;
457 }
458
Benjamin Kramer324d96b2017-08-09 22:06:32 +0000459 bool component_has_sep =
460 !component.empty() && is_separator(component[0], style);
461 if (!component_has_sep &&
462 !(path.empty() || has_root_name(component, style))) {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000463 // Add a separator.
Zachary Turner5c5091f2017-03-16 22:28:04 +0000464 path.push_back(preferred_separator(style));
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000465 }
466
Pawel Bylica64d08ff2015-10-22 08:12:15 +0000467 path.append(component.begin(), component.end());
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000468 }
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000469}
470
Zachary Turner5c5091f2017-03-16 22:28:04 +0000471void append(SmallVectorImpl<char> &path, const Twine &a, const Twine &b,
472 const Twine &c, const Twine &d) {
473 append(path, Style::native, a, b, c, d);
Argyrios Kyrtzidisa61736f2011-02-15 17:51:19 +0000474}
475
Zachary Turner5c5091f2017-03-16 22:28:04 +0000476void append(SmallVectorImpl<char> &path, const_iterator begin,
477 const_iterator end, Style style) {
478 for (; begin != end; ++begin)
479 path::append(path, style, *begin);
480}
481
482StringRef parent_path(StringRef path, Style style) {
483 size_t end_pos = parent_path_end(path, style);
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000484 if (end_pos == StringRef::npos)
Michael J. Spencerf616b212010-12-07 17:04:04 +0000485 return StringRef();
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000486 else
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000487 return path.substr(0, end_pos);
Michael J. Spencer545cbdf2010-11-30 23:28:07 +0000488}
489
Zachary Turner5c5091f2017-03-16 22:28:04 +0000490void remove_filename(SmallVectorImpl<char> &path, Style style) {
491 size_t end_pos = parent_path_end(StringRef(path.begin(), path.size()), style);
Michael J. Spencer1e090f02010-12-07 03:57:37 +0000492 if (end_pos != StringRef::npos)
493 path.set_size(end_pos);
Michael J. Spencer9c594092010-12-01 00:52:28 +0000494}
495
Zachary Turner5c5091f2017-03-16 22:28:04 +0000496void replace_extension(SmallVectorImpl<char> &path, const Twine &extension,
497 Style style) {
Michael J. Spencerfb3a95d2010-12-01 00:52:55 +0000498 StringRef p(path.begin(), path.size());
499 SmallString<32> ext_storage;
500 StringRef ext = extension.toStringRef(ext_storage);
501
502 // Erase existing extension.
503 size_t pos = p.find_last_of('.');
Zachary Turner5c5091f2017-03-16 22:28:04 +0000504 if (pos != StringRef::npos && pos >= filename_pos(p, style))
Michael J. Spencerfb3a95d2010-12-01 00:52:55 +0000505 path.set_size(pos);
506
507 // Append '.' if needed.
508 if (ext.size() > 0 && ext[0] != '.')
509 path.push_back('.');
510
511 // Append extension.
512 path.append(ext.begin(), ext.end());
Michael J. Spencerfb3a95d2010-12-01 00:52:55 +0000513}
514
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000515void replace_path_prefix(SmallVectorImpl<char> &Path,
Zachary Turner5c5091f2017-03-16 22:28:04 +0000516 const StringRef &OldPrefix, const StringRef &NewPrefix,
517 Style style) {
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000518 if (OldPrefix.empty() && NewPrefix.empty())
519 return;
520
521 StringRef OrigPath(Path.begin(), Path.size());
522 if (!OrigPath.startswith(OldPrefix))
523 return;
524
525 // If prefixes have the same size we can simply copy the new one over.
526 if (OldPrefix.size() == NewPrefix.size()) {
527 std::copy(NewPrefix.begin(), NewPrefix.end(), Path.begin());
528 return;
529 }
530
531 StringRef RelPath = OrigPath.substr(OldPrefix.size());
532 SmallString<256> NewPath;
Zachary Turner5c5091f2017-03-16 22:28:04 +0000533 path::append(NewPath, style, NewPrefix);
534 path::append(NewPath, style, RelPath);
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000535 Path.swap(NewPath);
536}
537
Zachary Turner5c5091f2017-03-16 22:28:04 +0000538void native(const Twine &path, SmallVectorImpl<char> &result, Style style) {
Benjamin Kramerbd4ac9b2013-09-11 10:45:21 +0000539 assert((!path.isSingleStringRef() ||
540 path.getSingleStringRef().data() != result.data()) &&
541 "path and result are not allowed to overlap!");
Michael J. Spencer80025002010-12-01 02:48:27 +0000542 // Clear result.
Michael J. Spencer98c7a112010-12-07 01:23:19 +0000543 result.clear();
Michael J. Spencer80025002010-12-01 02:48:27 +0000544 path.toVector(result);
Zachary Turner5c5091f2017-03-16 22:28:04 +0000545 native(result, style);
Benjamin Kramerbd4ac9b2013-09-11 10:45:21 +0000546}
547
Zachary Turner5c5091f2017-03-16 22:28:04 +0000548void native(SmallVectorImpl<char> &Path, Style style) {
Serge Pavlov9c761a32017-03-01 09:38:15 +0000549 if (Path.empty())
550 return;
Zachary Turner5c5091f2017-03-16 22:28:04 +0000551 if (real_style(style) == Style::windows) {
552 std::replace(Path.begin(), Path.end(), '/', '\\');
553 if (Path[0] == '~' && (Path.size() == 1 || is_separator(Path[1], style))) {
554 SmallString<128> PathHome;
555 home_directory(PathHome);
556 PathHome.append(Path.begin() + 1, Path.end());
557 Path = PathHome;
558 }
559 } else {
560 for (auto PI = Path.begin(), PE = Path.end(); PI < PE; ++PI) {
561 if (*PI == '\\') {
562 auto PN = PI + 1;
563 if (PN < PE && *PN == '\\')
564 ++PI; // increment once, the for loop will move over the escaped slash
565 else
566 *PI = '/';
567 }
Rafael Espindolad649b9d2014-08-08 21:29:34 +0000568 }
569 }
Michael J. Spencer80025002010-12-01 02:48:27 +0000570}
571
Zachary Turner5c5091f2017-03-16 22:28:04 +0000572std::string convert_to_slash(StringRef path, Style style) {
573 if (real_style(style) != Style::windows)
574 return path;
575
Rui Ueyama3e649032017-01-09 01:47:15 +0000576 std::string s = path.str();
577 std::replace(s.begin(), s.end(), '\\', '/');
578 return s;
Rui Ueyama3e649032017-01-09 01:47:15 +0000579}
580
Zachary Turner5c5091f2017-03-16 22:28:04 +0000581StringRef filename(StringRef path, Style style) { return *rbegin(path, style); }
Michael J. Spencer14269202010-12-01 03:18:17 +0000582
Zachary Turner5c5091f2017-03-16 22:28:04 +0000583StringRef stem(StringRef path, Style style) {
584 StringRef fname = filename(path, style);
Michael J. Spencer956955e2010-12-01 03:18:33 +0000585 size_t pos = fname.find_last_of('.');
586 if (pos == StringRef::npos)
Michael J. Spencerf616b212010-12-07 17:04:04 +0000587 return fname;
Michael J. Spencer956955e2010-12-01 03:18:33 +0000588 else
589 if ((fname.size() == 1 && fname == ".") ||
590 (fname.size() == 2 && fname == ".."))
Michael J. Spencerf616b212010-12-07 17:04:04 +0000591 return fname;
Michael J. Spencer956955e2010-12-01 03:18:33 +0000592 else
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000593 return fname.substr(0, pos);
Michael J. Spencer956955e2010-12-01 03:18:33 +0000594}
595
Zachary Turner5c5091f2017-03-16 22:28:04 +0000596StringRef extension(StringRef path, Style style) {
597 StringRef fname = filename(path, style);
Michael J. Spencer87106c52010-12-01 03:37:41 +0000598 size_t pos = fname.find_last_of('.');
599 if (pos == StringRef::npos)
Michael J. Spencerf616b212010-12-07 17:04:04 +0000600 return StringRef();
Michael J. Spencer87106c52010-12-01 03:37:41 +0000601 else
602 if ((fname.size() == 1 && fname == ".") ||
603 (fname.size() == 2 && fname == ".."))
Michael J. Spencerf616b212010-12-07 17:04:04 +0000604 return StringRef();
Michael J. Spencer87106c52010-12-01 03:37:41 +0000605 else
Benjamin Kramerffa42ce2010-12-17 20:27:37 +0000606 return fname.substr(pos);
Michael J. Spencer87106c52010-12-01 03:37:41 +0000607}
608
Zachary Turner5c5091f2017-03-16 22:28:04 +0000609bool is_separator(char value, Style style) {
610 if (value == '/')
611 return true;
612 if (real_style(style) == Style::windows)
613 return value == '\\';
614 return false;
Zhanyong Wan606bb1a2011-02-11 21:24:40 +0000615}
616
Zachary Turner5c5091f2017-03-16 22:28:04 +0000617StringRef get_separator(Style style) {
618 if (real_style(style) == Style::windows)
619 return "\\";
620 return "/";
Yaron Keren15217202014-05-16 13:16:30 +0000621}
622
Zachary Turner5c5091f2017-03-16 22:28:04 +0000623bool has_root_name(const Twine &path, Style style) {
Michael J. Spencer112a7692010-12-01 06:03:50 +0000624 SmallString<128> path_storage;
625 StringRef p = path.toStringRef(path_storage);
626
Zachary Turner5c5091f2017-03-16 22:28:04 +0000627 return !root_name(p, style).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000628}
629
Zachary Turner5c5091f2017-03-16 22:28:04 +0000630bool has_root_directory(const Twine &path, Style style) {
Michael J. Spencer112a7692010-12-01 06:03:50 +0000631 SmallString<128> path_storage;
632 StringRef p = path.toStringRef(path_storage);
633
Zachary Turner5c5091f2017-03-16 22:28:04 +0000634 return !root_directory(p, style).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000635}
636
Zachary Turner5c5091f2017-03-16 22:28:04 +0000637bool has_root_path(const Twine &path, Style style) {
Michael J. Spencer112a7692010-12-01 06:03:50 +0000638 SmallString<128> path_storage;
639 StringRef p = path.toStringRef(path_storage);
640
Zachary Turner5c5091f2017-03-16 22:28:04 +0000641 return !root_path(p, style).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000642}
643
Zachary Turner5c5091f2017-03-16 22:28:04 +0000644bool has_relative_path(const Twine &path, Style style) {
Michael J. Spencer6d4b7e72010-12-20 13:30:28 +0000645 SmallString<128> path_storage;
646 StringRef p = path.toStringRef(path_storage);
647
Zachary Turner5c5091f2017-03-16 22:28:04 +0000648 return !relative_path(p, style).empty();
Michael J. Spencer6d4b7e72010-12-20 13:30:28 +0000649}
650
Zachary Turner5c5091f2017-03-16 22:28:04 +0000651bool has_filename(const Twine &path, Style style) {
Michael J. Spencer112a7692010-12-01 06:03:50 +0000652 SmallString<128> path_storage;
653 StringRef p = path.toStringRef(path_storage);
654
Zachary Turner5c5091f2017-03-16 22:28:04 +0000655 return !filename(p, style).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000656}
657
Zachary Turner5c5091f2017-03-16 22:28:04 +0000658bool has_parent_path(const Twine &path, Style style) {
Michael J. Spencer112a7692010-12-01 06:03:50 +0000659 SmallString<128> path_storage;
660 StringRef p = path.toStringRef(path_storage);
661
Zachary Turner5c5091f2017-03-16 22:28:04 +0000662 return !parent_path(p, style).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000663}
664
Zachary Turner5c5091f2017-03-16 22:28:04 +0000665bool has_stem(const Twine &path, Style style) {
Michael J. Spencer112a7692010-12-01 06:03:50 +0000666 SmallString<128> path_storage;
667 StringRef p = path.toStringRef(path_storage);
668
Zachary Turner5c5091f2017-03-16 22:28:04 +0000669 return !stem(p, style).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000670}
671
Zachary Turner5c5091f2017-03-16 22:28:04 +0000672bool has_extension(const Twine &path, Style style) {
Michael J. Spencer112a7692010-12-01 06:03:50 +0000673 SmallString<128> path_storage;
674 StringRef p = path.toStringRef(path_storage);
675
Zachary Turner5c5091f2017-03-16 22:28:04 +0000676 return !extension(p, style).empty();
Michael J. Spencer112a7692010-12-01 06:03:50 +0000677}
678
Zachary Turner5c5091f2017-03-16 22:28:04 +0000679bool is_absolute(const Twine &path, Style style) {
Michael J. Spencera72df5f2010-12-01 06:21:53 +0000680 SmallString<128> path_storage;
681 StringRef p = path.toStringRef(path_storage);
682
Zachary Turner5c5091f2017-03-16 22:28:04 +0000683 bool rootDir = has_root_directory(p, style);
684 bool rootName =
685 (real_style(style) != Style::windows) || has_root_name(p, style);
Michael J. Spencera72df5f2010-12-01 06:21:53 +0000686
Michael J. Spencerf616b212010-12-07 17:04:04 +0000687 return rootDir && rootName;
Michael J. Spencera72df5f2010-12-01 06:21:53 +0000688}
689
Zachary Turner5c5091f2017-03-16 22:28:04 +0000690bool is_relative(const Twine &path, Style style) {
691 return !is_absolute(path, style);
692}
Douglas Katzmana26be4a2015-09-02 21:02:10 +0000693
Zachary Turner5c5091f2017-03-16 22:28:04 +0000694StringRef remove_leading_dotslash(StringRef Path, Style style) {
Douglas Katzmana26be4a2015-09-02 21:02:10 +0000695 // Remove leading "./" (or ".//" or "././" etc.)
Zachary Turner5c5091f2017-03-16 22:28:04 +0000696 while (Path.size() > 2 && Path[0] == '.' && is_separator(Path[1], style)) {
Douglas Katzmana26be4a2015-09-02 21:02:10 +0000697 Path = Path.substr(2);
Zachary Turner5c5091f2017-03-16 22:28:04 +0000698 while (Path.size() > 0 && is_separator(Path[0], style))
Douglas Katzmana26be4a2015-09-02 21:02:10 +0000699 Path = Path.substr(1);
700 }
701 return Path;
Michael J. Spencera72df5f2010-12-01 06:21:53 +0000702}
703
Zachary Turner5c5091f2017-03-16 22:28:04 +0000704static SmallString<256> remove_dots(StringRef path, bool remove_dot_dot,
705 Style style) {
Mike Aizatsky662b4fd2015-11-09 18:56:31 +0000706 SmallVector<StringRef, 16> components;
707
708 // Skip the root path, then look for traversal in the components.
Zachary Turner5c5091f2017-03-16 22:28:04 +0000709 StringRef rel = path::relative_path(path, style);
710 for (StringRef C :
711 llvm::make_range(path::begin(rel, style), path::end(rel))) {
Mike Aizatsky662b4fd2015-11-09 18:56:31 +0000712 if (C == ".")
713 continue;
Benjamin Kramer937dd7a2016-10-17 13:28:21 +0000714 // Leading ".." will remain in the path unless it's at the root.
715 if (remove_dot_dot && C == "..") {
716 if (!components.empty() && components.back() != "..") {
717 components.pop_back();
718 continue;
719 }
Zachary Turner5c5091f2017-03-16 22:28:04 +0000720 if (path::is_absolute(path, style))
Benjamin Kramer937dd7a2016-10-17 13:28:21 +0000721 continue;
Mike Aizatsky662b4fd2015-11-09 18:56:31 +0000722 }
723 components.push_back(C);
724 }
725
Zachary Turner5c5091f2017-03-16 22:28:04 +0000726 SmallString<256> buffer = path::root_path(path, style);
Mike Aizatsky662b4fd2015-11-09 18:56:31 +0000727 for (StringRef C : components)
Zachary Turner5c5091f2017-03-16 22:28:04 +0000728 path::append(buffer, style, C);
Mike Aizatsky662b4fd2015-11-09 18:56:31 +0000729 return buffer;
730}
731
Zachary Turner5c5091f2017-03-16 22:28:04 +0000732bool remove_dots(SmallVectorImpl<char> &path, bool remove_dot_dot,
733 Style style) {
Mike Aizatsky662b4fd2015-11-09 18:56:31 +0000734 StringRef p(path.data(), path.size());
735
Zachary Turner5c5091f2017-03-16 22:28:04 +0000736 SmallString<256> result = remove_dots(p, remove_dot_dot, style);
Mike Aizatsky662b4fd2015-11-09 18:56:31 +0000737 if (result == path)
738 return false;
739
740 path.swap(result);
741 return true;
742}
743
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +0000744} // end namespace path
745
746namespace fs {
747
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000748std::error_code getUniqueID(const Twine Path, UniqueID &Result) {
Rafael Espindola7f822a92013-07-29 21:26:49 +0000749 file_status Status;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000750 std::error_code EC = status(Path, Status);
Rafael Espindola7f822a92013-07-29 21:26:49 +0000751 if (EC)
752 return EC;
753 Result = Status.getUniqueID();
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000754 return std::error_code();
Rafael Espindola7f822a92013-07-29 21:26:49 +0000755}
756
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000757std::error_code createUniqueFile(const Twine &Model, int &ResultFd,
758 SmallVectorImpl<char> &ResultPath,
Zachary Turner8ac1c382018-06-05 19:58:26 +0000759 unsigned Mode) {
760 return createUniqueEntity(Model, ResultFd, ResultPath, false, Mode, FS_File);
761}
762
763static std::error_code createUniqueFile(const Twine &Model, int &ResultFd,
764 SmallVectorImpl<char> &ResultPath,
765 unsigned Mode, OpenFlags Flags) {
Rafael Espindolad19c2e82017-11-27 23:44:11 +0000766 return createUniqueEntity(Model, ResultFd, ResultPath, false, Mode, FS_File,
767 Flags);
Rafael Espindolac9d2e5b2013-07-05 21:01:08 +0000768}
769
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000770std::error_code createUniqueFile(const Twine &Model,
Ilya Biryukov84185762018-03-19 14:19:58 +0000771 SmallVectorImpl<char> &ResultPath,
772 unsigned Mode) {
773 int FD;
774 auto EC = createUniqueFile(Model, FD, ResultPath, Mode);
775 if (EC)
776 return EC;
777 // FD is only needed to avoid race conditions. Close it right away.
778 close(FD);
779 return EC;
Rafael Espindolac9d2e5b2013-07-05 21:01:08 +0000780}
781
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000782static std::error_code
783createTemporaryFile(const Twine &Model, int &ResultFD,
Zachary Turner8ac1c382018-06-05 19:58:26 +0000784 llvm::SmallVectorImpl<char> &ResultPath, FSEntity Type) {
Rafael Espindola325fa0f2013-07-05 19:56:49 +0000785 SmallString<128> Storage;
786 StringRef P = Model.toNullTerminatedStringRef(Storage);
Zachary Turner5c5091f2017-03-16 22:28:04 +0000787 assert(P.find_first_of(separators(Style::native)) == StringRef::npos &&
Rafael Espindola325fa0f2013-07-05 19:56:49 +0000788 "Model must be a simple filename.");
789 // Use P.begin() so that createUniqueEntity doesn't need to recreate Storage.
Rafael Espindolad19c2e82017-11-27 23:44:11 +0000790 return createUniqueEntity(P.begin(), ResultFD, ResultPath, true,
Zachary Turner8ac1c382018-06-05 19:58:26 +0000791 owner_read | owner_write, Type);
Rafael Espindola325fa0f2013-07-05 19:56:49 +0000792}
793
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000794static std::error_code
Rafael Espindola325fa0f2013-07-05 19:56:49 +0000795createTemporaryFile(const Twine &Prefix, StringRef Suffix, int &ResultFD,
Zachary Turner8ac1c382018-06-05 19:58:26 +0000796 llvm::SmallVectorImpl<char> &ResultPath, FSEntity Type) {
Rafael Espindolad3c89042013-07-25 15:00:17 +0000797 const char *Middle = Suffix.empty() ? "-%%%%%%" : "-%%%%%%.";
798 return createTemporaryFile(Prefix + Middle + Suffix, ResultFD, ResultPath,
Zachary Turner8ac1c382018-06-05 19:58:26 +0000799 Type);
Rafael Espindola325fa0f2013-07-05 19:56:49 +0000800}
801
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000802std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
803 int &ResultFD,
Zachary Turner8ac1c382018-06-05 19:58:26 +0000804 SmallVectorImpl<char> &ResultPath) {
805 return createTemporaryFile(Prefix, Suffix, ResultFD, ResultPath, FS_File);
Rafael Espindola325fa0f2013-07-05 19:56:49 +0000806}
807
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000808std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
809 SmallVectorImpl<char> &ResultPath) {
Ilya Biryukov84185762018-03-19 14:19:58 +0000810 int FD;
811 auto EC = createTemporaryFile(Prefix, Suffix, FD, ResultPath);
812 if (EC)
813 return EC;
814 // FD is only needed to avoid race conditions. Close it right away.
815 close(FD);
816 return EC;
Rafael Espindola325fa0f2013-07-05 19:56:49 +0000817}
818
819
Rafael Espindolae79a8722013-06-28 03:48:47 +0000820// This is a mkdtemp with a different pattern. We use createUniqueEntity mostly
Rafael Espindola31a24432013-06-28 10:55:41 +0000821// for consistency. We should try using mkdtemp.
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000822std::error_code createUniqueDirectory(const Twine &Prefix,
823 SmallVectorImpl<char> &ResultPath) {
Rafael Espindolae79a8722013-06-28 03:48:47 +0000824 int Dummy;
Ilya Biryukov84185762018-03-19 14:19:58 +0000825 return createUniqueEntity(Prefix + "-%%%%%%", Dummy, ResultPath, true, 0,
826 FS_Dir);
827}
828
829std::error_code
830getPotentiallyUniqueFileName(const Twine &Model,
831 SmallVectorImpl<char> &ResultPath) {
832 int Dummy;
833 return createUniqueEntity(Model, Dummy, ResultPath, false, 0, FS_Name);
834}
835
836std::error_code
837getPotentiallyUniqueTempFileName(const Twine &Prefix, StringRef Suffix,
838 SmallVectorImpl<char> &ResultPath) {
839 int Dummy;
840 return createTemporaryFile(Prefix, Suffix, Dummy, ResultPath, FS_Name);
Rafael Espindola7ffacc42013-06-27 03:45:31 +0000841}
842
Benjamin Kramerae1d5992015-10-05 13:02:43 +0000843static std::error_code make_absolute(const Twine &current_directory,
844 SmallVectorImpl<char> &path,
845 bool use_current_directory) {
Michael J. Spencer92903a32010-12-07 03:57:17 +0000846 StringRef p(path.data(), path.size());
847
Zachary Turner5c5091f2017-03-16 22:28:04 +0000848 bool rootDirectory = path::has_root_directory(p);
849 bool rootName =
850 (real_style(Style::native) != Style::windows) || path::has_root_name(p);
Michael J. Spencer92903a32010-12-07 03:57:17 +0000851
852 // Already absolute.
853 if (rootName && rootDirectory)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000854 return std::error_code();
Michael J. Spencer92903a32010-12-07 03:57:17 +0000855
856 // All of the following conditions will need the current directory.
857 SmallString<128> current_dir;
Benjamin Kramerae1d5992015-10-05 13:02:43 +0000858 if (use_current_directory)
859 current_directory.toVector(current_dir);
860 else if (std::error_code ec = current_path(current_dir))
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000861 return ec;
Michael J. Spencer92903a32010-12-07 03:57:17 +0000862
863 // Relative path. Prepend the current directory.
864 if (!rootName && !rootDirectory) {
865 // Append path to the current directory.
Michael J. Spencer1e090f02010-12-07 03:57:37 +0000866 path::append(current_dir, p);
Michael J. Spencer92903a32010-12-07 03:57:17 +0000867 // Set path to the result.
868 path.swap(current_dir);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000869 return std::error_code();
Michael J. Spencer92903a32010-12-07 03:57:17 +0000870 }
871
872 if (!rootName && rootDirectory) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000873 StringRef cdrn = path::root_name(current_dir);
Michael J. Spencer92903a32010-12-07 03:57:17 +0000874 SmallString<128> curDirRootName(cdrn.begin(), cdrn.end());
Michael J. Spencer1e090f02010-12-07 03:57:37 +0000875 path::append(curDirRootName, p);
Michael J. Spencer92903a32010-12-07 03:57:17 +0000876 // Set path to the result.
877 path.swap(curDirRootName);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000878 return std::error_code();
Michael J. Spencer92903a32010-12-07 03:57:17 +0000879 }
880
881 if (rootName && !rootDirectory) {
Michael J. Spencerf616b212010-12-07 17:04:04 +0000882 StringRef pRootName = path::root_name(p);
883 StringRef bRootDirectory = path::root_directory(current_dir);
884 StringRef bRelativePath = path::relative_path(current_dir);
885 StringRef pRelativePath = path::relative_path(p);
Michael J. Spencer92903a32010-12-07 03:57:17 +0000886
887 SmallString<128> res;
Michael J. Spencer1e090f02010-12-07 03:57:37 +0000888 path::append(res, pRootName, bRootDirectory, bRelativePath, pRelativePath);
Michael J. Spencer92903a32010-12-07 03:57:17 +0000889 path.swap(res);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000890 return std::error_code();
Michael J. Spencer92903a32010-12-07 03:57:17 +0000891 }
892
893 llvm_unreachable("All rootName and rootDirectory combinations should have "
894 "occurred above!");
895}
896
Benjamin Kramerae1d5992015-10-05 13:02:43 +0000897std::error_code make_absolute(const Twine &current_directory,
898 SmallVectorImpl<char> &path) {
899 return make_absolute(current_directory, path, true);
900}
901
902std::error_code make_absolute(SmallVectorImpl<char> &path) {
903 return make_absolute(Twine(), path, false);
904}
905
Frederic Riss6b9396c2015-08-06 21:04:55 +0000906std::error_code create_directories(const Twine &Path, bool IgnoreExisting,
907 perms Perms) {
Rafael Espindolab6f72b22014-02-13 16:58:19 +0000908 SmallString<128> PathStorage;
909 StringRef P = Path.toStringRef(PathStorage);
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000910
Rafael Espindolab6f72b22014-02-13 16:58:19 +0000911 // Be optimistic and try to create the directory
Frederic Riss6b9396c2015-08-06 21:04:55 +0000912 std::error_code EC = create_directory(P, IgnoreExisting, Perms);
Rafael Espindolab6f72b22014-02-13 16:58:19 +0000913 // If we succeeded, or had any error other than the parent not existing, just
914 // return it.
Rafael Espindola2a826e42014-06-13 17:20:48 +0000915 if (EC != errc::no_such_file_or_directory)
Rafael Espindolab6f72b22014-02-13 16:58:19 +0000916 return EC;
Michael J. Spencerf616b212010-12-07 17:04:04 +0000917
Rafael Espindolab6f72b22014-02-13 16:58:19 +0000918 // We failed because of a no_such_file_or_directory, try to create the
919 // parent.
920 StringRef Parent = path::parent_path(P);
921 if (Parent.empty())
922 return EC;
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000923
Frederic Riss6b9396c2015-08-06 21:04:55 +0000924 if ((EC = create_directories(Parent, IgnoreExisting, Perms)))
Rafael Espindolab6f72b22014-02-13 16:58:19 +0000925 return EC;
926
Frederic Riss6b9396c2015-08-06 21:04:55 +0000927 return create_directory(P, IgnoreExisting, Perms);
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000928}
929
Justin Bognercd45f962014-06-19 19:35:39 +0000930std::error_code copy_file(const Twine &From, const Twine &To) {
931 int ReadFD, WriteFD;
Zachary Turner1f67a3c2018-06-07 19:58:58 +0000932 if (std::error_code EC = openFileForRead(From, ReadFD, OF_None))
Justin Bognercd45f962014-06-19 19:35:39 +0000933 return EC;
Zachary Turner1f67a3c2018-06-07 19:58:58 +0000934 if (std::error_code EC =
935 openFileForWrite(To, WriteFD, CD_CreateAlways, OF_None)) {
Justin Bognercd45f962014-06-19 19:35:39 +0000936 close(ReadFD);
937 return EC;
938 }
939
940 const size_t BufSize = 4096;
Dylan Noblesmith42836d92014-08-26 02:03:30 +0000941 char *Buf = new char[BufSize];
Justin Bognercd45f962014-06-19 19:35:39 +0000942 int BytesRead = 0, BytesWritten = 0;
943 for (;;) {
944 BytesRead = read(ReadFD, Buf, BufSize);
945 if (BytesRead <= 0)
946 break;
947 while (BytesRead) {
948 BytesWritten = write(WriteFD, Buf, BytesRead);
949 if (BytesWritten < 0)
950 break;
951 BytesRead -= BytesWritten;
952 }
953 if (BytesWritten < 0)
954 break;
955 }
956 close(ReadFD);
957 close(WriteFD);
Dylan Noblesmith42836d92014-08-26 02:03:30 +0000958 delete[] Buf;
Justin Bognercd45f962014-06-19 19:35:39 +0000959
960 if (BytesRead < 0 || BytesWritten < 0)
961 return std::error_code(errno, std::generic_category());
962 return std::error_code();
963}
964
Zachary Turner82a0c972017-03-20 23:33:18 +0000965ErrorOr<MD5::MD5Result> md5_contents(int FD) {
966 MD5 Hash;
967
968 constexpr size_t BufSize = 4096;
969 std::vector<uint8_t> Buf(BufSize);
970 int BytesRead = 0;
971 for (;;) {
972 BytesRead = read(FD, Buf.data(), BufSize);
973 if (BytesRead <= 0)
974 break;
975 Hash.update(makeArrayRef(Buf.data(), BytesRead));
976 }
977
978 if (BytesRead < 0)
979 return std::error_code(errno, std::generic_category());
980 MD5::MD5Result Result;
981 Hash.final(Result);
982 return Result;
983}
984
985ErrorOr<MD5::MD5Result> md5_contents(const Twine &Path) {
986 int FD;
Zachary Turner1f67a3c2018-06-07 19:58:58 +0000987 if (auto EC = openFileForRead(Path, FD, OF_None))
Zachary Turner82a0c972017-03-20 23:33:18 +0000988 return EC;
989
990 auto Result = md5_contents(FD);
991 close(FD);
992 return Result;
993}
994
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000995bool exists(const basic_file_status &status) {
Michael J. Spencer730f51a2010-12-09 17:37:02 +0000996 return status_known(status) && status.type() != file_type::file_not_found;
997}
998
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000999bool status_known(const basic_file_status &s) {
Michael J. Spencer730f51a2010-12-09 17:37:02 +00001000 return s.type() != file_type::status_error;
1001}
1002
Zachary Turner82dd5422017-03-07 16:10:10 +00001003file_type get_file_type(const Twine &Path, bool Follow) {
Zachary Turner990e3cd2017-03-07 03:43:17 +00001004 file_status st;
Zachary Turner82dd5422017-03-07 16:10:10 +00001005 if (status(Path, st, Follow))
Zachary Turner990e3cd2017-03-07 03:43:17 +00001006 return file_type::status_error;
1007 return st.type();
1008}
1009
Peter Collingbourne0dfdb442017-10-10 22:19:46 +00001010bool is_directory(const basic_file_status &status) {
Michael J. Spencer730f51a2010-12-09 17:37:02 +00001011 return status.type() == file_type::directory_file;
1012}
1013
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001014std::error_code is_directory(const Twine &path, bool &result) {
Michael J. Spencer0d771ed2011-01-11 01:21:55 +00001015 file_status st;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001016 if (std::error_code ec = status(path, st))
Michael J. Spencer0d771ed2011-01-11 01:21:55 +00001017 return ec;
1018 result = is_directory(st);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001019 return std::error_code();
Michael J. Spencer0d771ed2011-01-11 01:21:55 +00001020}
1021
Peter Collingbourne0dfdb442017-10-10 22:19:46 +00001022bool is_regular_file(const basic_file_status &status) {
Michael J. Spencer730f51a2010-12-09 17:37:02 +00001023 return status.type() == file_type::regular_file;
1024}
1025
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001026std::error_code is_regular_file(const Twine &path, bool &result) {
Michael J. Spencer0d771ed2011-01-11 01:21:55 +00001027 file_status st;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001028 if (std::error_code ec = status(path, st))
Michael J. Spencer0d771ed2011-01-11 01:21:55 +00001029 return ec;
1030 result = is_regular_file(st);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001031 return std::error_code();
Michael J. Spencer0d771ed2011-01-11 01:21:55 +00001032}
1033
Peter Collingbourne0dfdb442017-10-10 22:19:46 +00001034bool is_symlink_file(const basic_file_status &status) {
Zachary Turner7d86ee52017-03-08 17:56:08 +00001035 return status.type() == file_type::symlink_file;
1036}
1037
1038std::error_code is_symlink_file(const Twine &path, bool &result) {
1039 file_status st;
1040 if (std::error_code ec = status(path, st, false))
1041 return ec;
1042 result = is_symlink_file(st);
1043 return std::error_code();
1044}
1045
Peter Collingbourne0dfdb442017-10-10 22:19:46 +00001046bool is_other(const basic_file_status &status) {
Michael J. Spencer730f51a2010-12-09 17:37:02 +00001047 return exists(status) &&
1048 !is_regular_file(status) &&
Rafael Espindola20063062014-03-20 17:39:04 +00001049 !is_directory(status);
Michael J. Spencer730f51a2010-12-09 17:37:02 +00001050}
1051
Juergen Ributzka84ba3422014-12-18 18:19:47 +00001052std::error_code is_other(const Twine &Path, bool &Result) {
1053 file_status FileStatus;
1054 if (std::error_code EC = status(Path, FileStatus))
1055 return EC;
1056 Result = is_other(FileStatus);
1057 return std::error_code();
1058}
1059
Peter Collingbourne0dfdb442017-10-10 22:19:46 +00001060void directory_entry::replace_filename(const Twine &filename,
1061 basic_file_status st) {
Rafael Espindolaf662e002015-07-15 21:24:07 +00001062 SmallString<128> path = path::parent_path(Path);
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +00001063 path::append(path, filename);
1064 Path = path.str();
1065 Status = st;
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +00001066}
1067
James Henderson566fdf42017-03-16 11:22:09 +00001068ErrorOr<perms> getPermissions(const Twine &Path) {
1069 file_status Status;
1070 if (std::error_code EC = status(Path, Status))
1071 return EC;
1072
1073 return Status.permissions();
1074}
1075
Aaron Ballman345012d2017-03-13 12:24:51 +00001076} // end namespace fs
1077} // end namespace sys
1078} // end namespace llvm
Michael J. Spencerebad2f92010-11-29 22:28:51 +00001079
1080// Include the truly platform-specific parts.
1081#if defined(LLVM_ON_UNIX)
Rafael Espindolaf1fc3822013-06-26 19:33:03 +00001082#include "Unix/Path.inc"
Michael J. Spencerebad2f92010-11-29 22:28:51 +00001083#endif
Nico Weber712e8d22018-04-29 00:45:03 +00001084#if defined(_WIN32)
Rafael Espindolaf1fc3822013-06-26 19:33:03 +00001085#include "Windows/Path.inc"
Michael J. Spencerebad2f92010-11-29 22:28:51 +00001086#endif
Pawel Bylica0e97e5c2015-11-02 09:49:17 +00001087
1088namespace llvm {
1089namespace sys {
Rafael Espindola2c4e9202017-11-28 01:34:20 +00001090namespace fs {
1091TempFile::TempFile(StringRef Name, int FD) : TmpName(Name), FD(FD) {}
1092TempFile::TempFile(TempFile &&Other) { *this = std::move(Other); }
1093TempFile &TempFile::operator=(TempFile &&Other) {
1094 TmpName = std::move(Other.TmpName);
1095 FD = Other.FD;
1096 Other.Done = true;
1097 return *this;
1098}
1099
1100TempFile::~TempFile() { assert(Done); }
1101
1102Error TempFile::discard() {
1103 Done = true;
Rafael Espindola2c4e9202017-11-28 01:34:20 +00001104 std::error_code RemoveEC;
Rafael Espindola3ecd2042017-11-28 01:41:22 +00001105// On windows closing will remove the file.
Nico Weber712e8d22018-04-29 00:45:03 +00001106#ifndef _WIN32
Rafael Espindola3ecd2042017-11-28 01:41:22 +00001107 // Always try to close and remove.
Rafael Espindola2c4e9202017-11-28 01:34:20 +00001108 if (!TmpName.empty()) {
1109 RemoveEC = fs::remove(TmpName);
1110 sys::DontRemoveFileOnSignal(TmpName);
1111 }
Rafael Espindola3ecd2042017-11-28 01:41:22 +00001112#endif
Rafael Espindola2c4e9202017-11-28 01:34:20 +00001113
1114 if (!RemoveEC)
1115 TmpName = "";
1116
1117 if (FD != -1 && close(FD) == -1) {
1118 std::error_code EC = std::error_code(errno, std::generic_category());
1119 return errorCodeToError(EC);
1120 }
1121 FD = -1;
1122
1123 return errorCodeToError(RemoveEC);
1124}
1125
1126Error TempFile::keep(const Twine &Name) {
1127 assert(!Done);
1128 Done = true;
1129 // Always try to close and rename.
Nico Weber712e8d22018-04-29 00:45:03 +00001130#ifdef _WIN32
Rafael Espindola3ecd2042017-11-28 01:41:22 +00001131 // If we cant't cancel the delete don't rename.
Peter Collingbourne881ba102018-06-13 18:03:14 +00001132 auto H = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
1133 std::error_code RenameEC = setDeleteDisposition(H, false);
Rafael Espindola3ecd2042017-11-28 01:41:22 +00001134 if (!RenameEC)
1135 RenameEC = rename_fd(FD, Name);
Rafael Espindola20569e92017-12-05 16:40:56 +00001136 // If we can't rename, discard the temporary file.
1137 if (RenameEC)
Peter Collingbourne881ba102018-06-13 18:03:14 +00001138 setDeleteDisposition(H, true);
Rafael Espindola3ecd2042017-11-28 01:41:22 +00001139#else
Rafael Espindola2c4e9202017-11-28 01:34:20 +00001140 std::error_code RenameEC = fs::rename(TmpName, Name);
Rafael Espindola20569e92017-12-05 16:40:56 +00001141 // If we can't rename, discard the temporary file.
1142 if (RenameEC)
1143 remove(TmpName);
Rafael Espindola2c4e9202017-11-28 01:34:20 +00001144 sys::DontRemoveFileOnSignal(TmpName);
Rafael Espindola3ecd2042017-11-28 01:41:22 +00001145#endif
Rafael Espindola2c4e9202017-11-28 01:34:20 +00001146
1147 if (!RenameEC)
1148 TmpName = "";
1149
1150 if (close(FD) == -1) {
1151 std::error_code EC(errno, std::generic_category());
1152 return errorCodeToError(EC);
1153 }
1154 FD = -1;
1155
1156 return errorCodeToError(RenameEC);
1157}
1158
1159Error TempFile::keep() {
1160 assert(!Done);
1161 Done = true;
1162
Nico Weber712e8d22018-04-29 00:45:03 +00001163#ifdef _WIN32
Peter Collingbourne881ba102018-06-13 18:03:14 +00001164 auto H = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
1165 if (std::error_code EC = setDeleteDisposition(H, false))
Rafael Espindola3ecd2042017-11-28 01:41:22 +00001166 return errorCodeToError(EC);
1167#else
Rafael Espindola2c4e9202017-11-28 01:34:20 +00001168 sys::DontRemoveFileOnSignal(TmpName);
Rafael Espindola3ecd2042017-11-28 01:41:22 +00001169#endif
1170
Rafael Espindola2c4e9202017-11-28 01:34:20 +00001171 TmpName = "";
1172
1173 if (close(FD) == -1) {
1174 std::error_code EC(errno, std::generic_category());
1175 return errorCodeToError(EC);
1176 }
1177 FD = -1;
1178
1179 return Error::success();
1180}
1181
1182Expected<TempFile> TempFile::create(const Twine &Model, unsigned Mode) {
1183 int FD;
1184 SmallString<128> ResultPath;
Zachary Turner8ac1c382018-06-05 19:58:26 +00001185 if (std::error_code EC =
Zachary Turner1f67a3c2018-06-07 19:58:58 +00001186 createUniqueFile(Model, FD, ResultPath, Mode, OF_Delete))
Rafael Espindola2c4e9202017-11-28 01:34:20 +00001187 return errorCodeToError(EC);
1188
Rafael Espindola2c4e9202017-11-28 01:34:20 +00001189 TempFile Ret(ResultPath, FD);
Nico Weber712e8d22018-04-29 00:45:03 +00001190#ifndef _WIN32
Rafael Espindola2c4e9202017-11-28 01:34:20 +00001191 if (sys::RemoveFileOnSignal(ResultPath)) {
Rafael Espindola3ecd2042017-11-28 01:41:22 +00001192 // Make sure we delete the file when RemoveFileOnSignal fails.
Rafael Espindola2c4e9202017-11-28 01:34:20 +00001193 consumeError(Ret.discard());
1194 std::error_code EC(errc::operation_not_permitted);
1195 return errorCodeToError(EC);
1196 }
Rafael Espindola3ecd2042017-11-28 01:41:22 +00001197#endif
Rafael Espindola2c4e9202017-11-28 01:34:20 +00001198 return std::move(Ret);
1199}
1200}
1201
Pawel Bylica0e97e5c2015-11-02 09:49:17 +00001202namespace path {
1203
1204bool user_cache_directory(SmallVectorImpl<char> &Result, const Twine &Path1,
1205 const Twine &Path2, const Twine &Path3) {
1206 if (getUserCacheDir(Result)) {
1207 append(Result, Path1, Path2, Path3);
1208 return true;
1209 }
1210 return false;
1211}
1212
1213} // end namespace path
1214} // end namsspace sys
1215} // end namespace llvm