Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/lib/Support/Path.cpp
Line
Count
Source (jump to first uncovered line)
1
//===-- Path.cpp - Implement OS Path Concept ------------------------------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
//  This file implements the operating system Path API.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "llvm/Support/Path.h"
14
#include "llvm/ADT/ArrayRef.h"
15
#include "llvm/Config/llvm-config.h"
16
#include "llvm/Support/Endian.h"
17
#include "llvm/Support/Errc.h"
18
#include "llvm/Support/ErrorHandling.h"
19
#include "llvm/Support/FileSystem.h"
20
#include "llvm/Support/Process.h"
21
#include "llvm/Support/Signals.h"
22
#include <cctype>
23
#include <cstring>
24
25
#if !defined(_MSC_VER) && !defined(__MINGW32__)
26
#include <unistd.h>
27
#else
28
#include <io.h>
29
#endif
30
31
using namespace llvm;
32
using namespace llvm::support::endian;
33
34
namespace {
35
  using llvm::StringRef;
36
  using llvm::sys::path::is_separator;
37
  using llvm::sys::path::Style;
38
39
276M
  inline Style real_style(Style style) {
40
#ifdef _WIN32
41
    return (style == Style::posix) ? Style::posix : Style::windows;
42
#else
43
276M
    return (style == Style::windows) ? 
Style::windows63.4k
: Style::posix;
44
276M
#endif
45
276M
  }
46
47
46.9M
  inline const char *separators(Style style) {
48
46.9M
    if (real_style(style) == Style::windows)
49
8.34k
      return "\\/";
50
46.9M
    return "/";
51
46.9M
  }
52
53
11.2M
  inline char preferred_separator(Style style) {
54
11.2M
    if (real_style(style) == Style::windows)
55
24
      return '\\';
56
11.2M
    return '/';
57
11.2M
  }
58
59
24.5M
  StringRef find_first_component(StringRef path, Style style) {
60
24.5M
    // Look for this first component in the following order.
61
24.5M
    // * empty (in this case we return an empty string)
62
24.5M
    // * either C: or {//,\\}net.
63
24.5M
    // * {/,\}
64
24.5M
    // * {file,directory}name
65
24.5M
66
24.5M
    if (path.empty())
67
653k
      return path;
68
23.9M
69
23.9M
    if (real_style(style) == Style::windows) {
70
8.95k
      // C:
71
8.95k
      if (path.size() >= 2 &&
72
8.95k
          
std::isalpha(static_cast<unsigned char>(path[0]))8.78k
&&
path[1] == ':'7.90k
)
73
233
        return path.substr(0, 2);
74
23.9M
    }
75
23.9M
76
23.9M
    // //net
77
23.9M
    if ((path.size() > 2) && 
is_separator(path[0], style)23.4M
&&
78
23.9M
        
path[0] == path[1]7.30M
&&
!is_separator(path[2], style)1.43k
) {
79
1.41k
      // Find the next directory separator.
80
1.41k
      size_t end = path.find_first_of(separators(style), 2);
81
1.41k
      return path.substr(0, end);
82
1.41k
    }
83
23.9M
84
23.9M
    // {/,\}
85
23.9M
    if (is_separator(path[0], style))
86
7.30M
      return path.substr(0, 1);
87
16.6M
88
16.6M
    // * {file,directory}name
89
16.6M
    size_t end = path.find_first_of(separators(style));
90
16.6M
    return path.substr(0, end);
91
16.6M
  }
92
93
  // Returns the first character of the filename in str. For paths ending in
94
  // '/', it returns the position of the '/'.
95
5.87M
  size_t filename_pos(StringRef str, Style style) {
96
5.87M
    if (str.size() > 0 && 
is_separator(str[str.size() - 1], style)5.68M
)
97
106k
      return str.size() - 1;
98
5.76M
99
5.76M
    size_t pos = str.find_last_of(separators(style), str.size() - 1);
100
5.76M
101
5.76M
    if (real_style(style) == Style::windows) {
102
289
      if (pos == StringRef::npos)
103
114
        pos = str.find_last_of(':', str.size() - 2);
104
289
    }
105
5.76M
106
5.76M
    if (pos == StringRef::npos || 
(5.37M
pos == 15.37M
&&
is_separator(str[0], style)11.8k
))
107
395k
      return 0;
108
5.37M
109
5.37M
    return pos + 1;
110
5.37M
  }
111
112
  // Returns the position of the root directory in str. If there is no root
113
  // directory in str, it returns StringRef::npos.
114
5.93M
  size_t root_dir_start(StringRef str, Style style) {
115
5.93M
    // case "c:/"
116
5.93M
    if (real_style(style) == Style::windows) {
117
300
      if (str.size() > 2 && 
str[1] == ':'298
&&
is_separator(str[2], style)36
)
118
36
        return 2;
119
5.93M
    }
120
5.93M
121
5.93M
    // case "//net"
122
5.93M
    if (str.size() > 3 && 
is_separator(str[0], style)5.70M
&&
str[0] == str[1]5.44M
&&
123
5.93M
        
!is_separator(str[2], style)434
) {
124
402
      return str.find_first_of(separators(style), 2);
125
402
    }
126
5.93M
127
5.93M
    // case "/"
128
5.93M
    if (str.size() > 0 && 
is_separator(str[0], style)5.74M
)
129
5.47M
      return 0;
130
456k
131
456k
    return StringRef::npos;
132
456k
  }
133
134
  // Returns the position past the end of the "parent path" of path. The parent
135
  // path will not end in '/', unless the parent is the root directory. If the
136
  // path has no parent, 0 is returned.
137
1.84M
  size_t parent_path_end(StringRef path, Style style) {
138
1.84M
    size_t end_pos = filename_pos(path, style);
139
1.84M
140
1.84M
    bool filename_was_sep =
141
1.84M
        path.size() > 0 && 
is_separator(path[end_pos], style)1.83M
;
142
1.84M
143
1.84M
    // Skip separators until we reach root dir (or the start of the string).
144
1.84M
    size_t root_dir_pos = root_dir_start(path, style);
145
3.52M
    while (end_pos > 0 &&
146
3.52M
           
(3.42M
root_dir_pos == StringRef::npos3.42M
||
end_pos > root_dir_pos3.33M
) &&
147
3.52M
           
is_separator(path[end_pos - 1], style)3.42M
)
148
1.68M
      --end_pos;
149
1.84M
150
1.84M
    if (end_pos == root_dir_pos && 
!filename_was_sep22.0k
) {
151
11.3k
      // We've reached the root dir and the input path was *not* ending in a
152
11.3k
      // sequence of slashes. Include the root dir in the parent path.
153
11.3k
      return root_dir_pos + 1;
154
11.3k
    }
155
1.83M
156
1.83M
    // Otherwise, just include before the last slash.
157
1.83M
    return end_pos;
158
1.83M
  }
159
} // end unnamed namespace
160
161
enum FSEntity {
162
  FS_Dir,
163
  FS_File,
164
  FS_Name
165
};
166
167
static std::error_code
168
createUniqueEntity(const Twine &Model, int &ResultFD,
169
                   SmallVectorImpl<char> &ResultPath, bool MakeAbsolute,
170
                   unsigned Mode, FSEntity Type,
171
37.6k
                   sys::fs::OpenFlags Flags = sys::fs::OF_None) {
172
37.6k
173
37.6k
  // Limit the number of attempts we make, so that we don't infinite loop. E.g.
174
37.6k
  // "permission denied" could be for a specific file (so we retry with a
175
37.6k
  // different name) or for the whole directory (retry would always fail).
176
37.6k
  // Checking which is racy, so we try a number of times, then give up.
177
37.6k
  std::error_code EC;
178
39.7k
  for (int Retries = 128; Retries > 0; 
--Retries2.09k
) {
179
39.7k
    sys::fs::createUniquePath(Model, ResultPath, MakeAbsolute);
180
39.7k
    // Try to open + create the file.
181
39.7k
    switch (Type) {
182
39.7k
    case FS_File: {
183
39.6k
      EC = sys::fs::openFileForReadWrite(Twine(ResultPath.begin()), ResultFD,
184
39.6k
                                         sys::fs::CD_CreateNew, Flags, Mode);
185
39.6k
      if (EC) {
186
2.16k
        // errc::permission_denied happens on Windows when we try to open a file
187
2.16k
        // that has been marked for deletion.
188
2.16k
        if (EC == errc::file_exists || 
EC == errc::permission_denied78
)
189
2.09k
          continue;
190
78
        return EC;
191
78
      }
192
37.5k
193
37.5k
      return std::error_code();
194
37.5k
    }
195
37.5k
196
37.5k
    case FS_Name: {
197
1
      EC = sys::fs::access(ResultPath.begin(), sys::fs::AccessMode::Exist);
198
1
      if (EC == errc::no_such_file_or_directory)
199
1
        return std::error_code();
200
0
      if (EC)
201
0
        return EC;
202
0
      continue;
203
0
    }
204
0
205
73
    case FS_Dir: {
206
73
      EC = sys::fs::create_directory(ResultPath.begin(), false);
207
73
      if (EC) {
208
0
        if (EC == errc::file_exists)
209
0
          continue;
210
0
        return EC;
211
0
      }
212
73
      return std::error_code();
213
73
    }
214
0
    }
215
0
    llvm_unreachable("Invalid Type");
216
0
  }
217
37.6k
  
return EC16
;
218
37.6k
}
219
220
namespace llvm {
221
namespace sys  {
222
namespace path {
223
224
24.5M
const_iterator begin(StringRef path, Style style) {
225
24.5M
  const_iterator i;
226
24.5M
  i.Path      = path;
227
24.5M
  i.Component = find_first_component(path, style);
228
24.5M
  i.Position  = 0;
229
24.5M
  i.S = style;
230
24.5M
  return i;
231
24.5M
}
232
233
24.5M
const_iterator end(StringRef path) {
234
24.5M
  const_iterator i;
235
24.5M
  i.Path      = path;
236
24.5M
  i.Position  = path.size();
237
24.5M
  return i;
238
24.5M
}
239
240
27.5M
const_iterator &const_iterator::operator++() {
241
27.5M
  assert(Position < Path.size() && "Tried to increment past end!");
242
27.5M
243
27.5M
  // Increment Position to past the current component
244
27.5M
  Position += Component.size();
245
27.5M
246
27.5M
  // Check for end.
247
27.5M
  if (Position == Path.size()) {
248
4.31M
    Component = StringRef();
249
4.31M
    return *this;
250
4.31M
  }
251
23.2M
252
23.2M
  // Both POSIX and Windows treat paths that begin with exactly two separators
253
23.2M
  // specially.
254
23.2M
  bool was_net = Component.size() > 2 && 
is_separator(Component[0], S)21.6M
&&
255
23.2M
                 
Component[1] == Component[0]1.40k
&&
!is_separator(Component[2], S)1.40k
;
256
23.2M
257
23.2M
  // Handle separators.
258
23.2M
  if (is_separator(Path[Position], S)) {
259
21.9M
    // Root dir.
260
21.9M
    if (was_net ||
261
21.9M
        // c:/
262
21.9M
        
(21.9M
real_style(S) == Style::windows21.9M
&&
Component.endswith(":")161
)) {
263
1.52k
      Component = Path.substr(Position, 1);
264
1.52k
      return *this;
265
1.52k
    }
266
21.9M
267
21.9M
    // Skip extra separators.
268
43.8M
    
while (21.9M
Position != Path.size() &&
is_separator(Path[Position], S)43.8M
) {
269
21.9M
      ++Position;
270
21.9M
    }
271
21.9M
272
21.9M
    // Treat trailing '/' as a '.', unless it is the root dir.
273
21.9M
    if (Position == Path.size() && 
Component != "/"63
) {
274
61
      --Position;
275
61
      Component = ".";
276
61
      return *this;
277
61
    }
278
23.2M
  }
279
23.2M
280
23.2M
  // Find next component.
281
23.2M
  size_t end_pos = Path.find_first_of(separators(S), Position);
282
23.2M
  Component = Path.slice(Position, end_pos);
283
23.2M
284
23.2M
  return *this;
285
23.2M
}
286
287
52.3M
bool const_iterator::operator==(const const_iterator &RHS) const {
288
52.3M
  return 
Path.begin() == RHS.Path.begin()52.3M
&& Position == RHS.Position;
289
52.3M
}
290
291
278
ptrdiff_t const_iterator::operator-(const const_iterator &RHS) const {
292
278
  return Position - RHS.Position;
293
278
}
294
295
2.17M
reverse_iterator rbegin(StringRef Path, Style style) {
296
2.17M
  reverse_iterator I;
297
2.17M
  I.Path = Path;
298
2.17M
  I.Position = Path.size();
299
2.17M
  I.S = style;
300
2.17M
  ++I;
301
2.17M
  return I;
302
2.17M
}
303
304
1.01M
reverse_iterator rend(StringRef Path) {
305
1.01M
  reverse_iterator I;
306
1.01M
  I.Path = Path;
307
1.01M
  I.Component = Path.substr(0, 0);
308
1.01M
  I.Position = 0;
309
1.01M
  return I;
310
1.01M
}
311
312
4.08M
reverse_iterator &reverse_iterator::operator++() {
313
4.08M
  size_t root_dir_pos = root_dir_start(Path, S);
314
4.08M
315
4.08M
  // Skip separators unless it's the root directory.
316
4.08M
  size_t end_pos = Position;
317
6.07M
  while (end_pos > 0 && 
(end_pos - 1) != root_dir_pos5.89M
&&
318
6.07M
         
is_separator(Path[end_pos - 1], S)5.87M
)
319
1.98M
    --end_pos;
320
4.08M
321
4.08M
  // Treat trailing '/' as a '.', unless it is the root dir.
322
4.08M
  if (Position == Path.size() && 
!Path.empty()2.17M
&&
323
4.08M
      
is_separator(Path.back(), S)1.99M
&&
324
4.08M
      
(95.9k
root_dir_pos == StringRef::npos95.9k
||
end_pos - 1 > root_dir_pos95.9k
)) {
325
75.1k
    --Position;
326
75.1k
    Component = ".";
327
75.1k
    return *this;
328
75.1k
  }
329
4.01M
330
4.01M
  // Find next separator.
331
4.01M
  size_t start_pos = filename_pos(Path.substr(0, end_pos), S);
332
4.01M
  Component = Path.slice(start_pos, end_pos);
333
4.01M
  Position = start_pos;
334
4.01M
  return *this;
335
4.01M
}
336
337
1.91M
bool reverse_iterator::operator==(const reverse_iterator &RHS) const {
338
1.91M
  return Path.begin() == RHS.Path.begin() && Component == RHS.Component &&
339
1.91M
         
Position == RHS.Position210
;
340
1.91M
}
341
342
43
ptrdiff_t reverse_iterator::operator-(const reverse_iterator &RHS) const {
343
43
  return Position - RHS.Position;
344
43
}
345
346
4.72M
StringRef root_path(StringRef path, Style style) {
347
4.72M
  const_iterator b = begin(path, style), pos = b, e = end(path);
348
4.72M
  if (b != e) {
349
4.42M
    bool has_net =
350
4.42M
        b->size() > 2 && 
is_separator((*b)[0], style)647k
&&
(*b)[1] == (*b)[0]775
;
351
4.42M
    bool has_drive = (real_style(style) == Style::windows) && 
b->endswith(":")30
;
352
4.42M
353
4.42M
    if (has_net || 
has_drive4.42M
) {
354
789
      if ((++pos != e) && 
is_separator((*pos)[0], style)785
) {
355
785
        // {C:/,//net/}, so get the first two components.
356
785
        return path.substr(0, b->size() + pos->size());
357
785
      } else {
358
4
        // just {C:,//net}, return the first component.
359
4
        return *b;
360
4
      }
361
4.42M
    }
362
4.42M
363
4.42M
    // POSIX style root directory.
364
4.42M
    if (is_separator((*b)[0], style)) {
365
3.58M
      return *b;
366
3.58M
    }
367
1.14M
  }
368
1.14M
369
1.14M
  return StringRef();
370
1.14M
}
371
372
11.5M
StringRef root_name(StringRef path, Style style) {
373
11.5M
  const_iterator b = begin(path, style), e = end(path);
374
11.5M
  if (b != e) {
375
11.4M
    bool has_net =
376
11.4M
        b->size() > 2 && 
is_separator((*b)[0], style)11.2M
&&
(*b)[1] == (*b)[0]8
;
377
11.4M
    bool has_drive = (real_style(style) == Style::windows) && 
b->endswith(":")4.46k
;
378
11.4M
379
11.4M
    if (
has_net11.4M
|| has_drive) {
380
117
      // just {C:,//net}, return the first component.
381
117
      return *b;
382
117
    }
383
11.5M
  }
384
11.5M
385
11.5M
  // No path or no name.
386
11.5M
  return StringRef();
387
11.5M
}
388
389
4.64M
StringRef root_directory(StringRef path, Style style) {
390
4.64M
  const_iterator b = begin(path, style), pos = b, e = end(path);
391
4.64M
  if (b != e) {
392
4.42M
    bool has_net =
393
4.42M
        b->size() > 2 && 
is_separator((*b)[0], style)1.91M
&&
(*b)[1] == (*b)[0]469
;
394
4.42M
    bool has_drive = (real_style(style) == Style::windows) && 
b->endswith(":")4.44k
;
395
4.42M
396
4.42M
    if ((has_net || 
has_drive4.42M
) &&
397
4.42M
        // {C:,//net}, skip to the next component.
398
4.42M
        
(++pos != e)578
&&
is_separator((*pos)[0], style)570
) {
399
569
      return *pos;
400
569
    }
401
4.42M
402
4.42M
    // POSIX style root directory.
403
4.42M
    if (!has_net && 
is_separator((*b)[0], style)4.42M
) {
404
2.36M
      return *b;
405
2.36M
    }
406
2.28M
  }
407
2.28M
408
2.28M
  // No path or no root.
409
2.28M
  return StringRef();
410
2.28M
}
411
412
1.86M
StringRef relative_path(StringRef path, Style style) {
413
1.86M
  StringRef root = root_path(path, style);
414
1.86M
  return path.substr(root.size());
415
1.86M
}
416
417
void append(SmallVectorImpl<char> &path, Style style, const Twine &a,
418
12.3M
            const Twine &b, const Twine &c, const Twine &d) {
419
12.3M
  SmallString<32> a_storage;
420
12.3M
  SmallString<32> b_storage;
421
12.3M
  SmallString<32> c_storage;
422
12.3M
  SmallString<32> d_storage;
423
12.3M
424
12.3M
  SmallVector<StringRef, 4> components;
425
12.3M
  if (
!a.isTriviallyEmpty()12.3M
) components.push_back(a.toStringRef(a_storage));
426
12.3M
  if (!b.isTriviallyEmpty()) 
components.push_back(b.toStringRef(b_storage))780k
;
427
12.3M
  if (!c.isTriviallyEmpty()) 
components.push_back(c.toStringRef(c_storage))644k
;
428
12.3M
  if (!d.isTriviallyEmpty()) 
components.push_back(d.toStringRef(d_storage))383k
;
429
12.3M
430
14.1M
  for (auto &component : components) {
431
14.1M
    bool path_has_sep =
432
14.1M
        !path.empty() && 
is_separator(path[path.size() - 1], style)12.5M
;
433
14.1M
    if (path_has_sep) {
434
1.24M
      // Strip separators from beginning of component.
435
1.24M
      size_t loc = component.find_first_not_of(separators(style));
436
1.24M
      StringRef c = component.substr(loc);
437
1.24M
438
1.24M
      // Append it.
439
1.24M
      path.append(c.begin(), c.end());
440
1.24M
      continue;
441
1.24M
    }
442
12.9M
443
12.9M
    bool component_has_sep =
444
12.9M
        !component.empty() && 
is_separator(component[0], style)12.0M
;
445
12.9M
    if (!component_has_sep &&
446
12.9M
        
!(12.5M
path.empty()12.5M
||
has_root_name(component, style)11.2M
)) {
447
11.2M
      // Add a separator.
448
11.2M
      path.push_back(preferred_separator(style));
449
11.2M
    }
450
12.9M
451
12.9M
    path.append(component.begin(), component.end());
452
12.9M
  }
453
12.3M
}
454
455
void append(SmallVectorImpl<char> &path, const Twine &a, const Twine &b,
456
3.17M
            const Twine &c, const Twine &d) {
457
3.17M
  append(path, Style::native, a, b, c, d);
458
3.17M
}
459
460
void append(SmallVectorImpl<char> &path, const_iterator begin,
461
67
            const_iterator end, Style style) {
462
592
  for (; begin != end; 
++begin525
)
463
525
    path::append(path, style, *begin);
464
67
}
465
466
1.82M
StringRef parent_path(StringRef path, Style style) {
467
1.82M
  size_t end_pos = parent_path_end(path, style);
468
1.82M
  if (end_pos == StringRef::npos)
469
0
    return StringRef();
470
1.82M
  else
471
1.82M
    return path.substr(0, end_pos);
472
1.82M
}
473
474
18.9k
void remove_filename(SmallVectorImpl<char> &path, Style style) {
475
18.9k
  size_t end_pos = parent_path_end(StringRef(path.begin(), path.size()), style);
476
18.9k
  if (end_pos != StringRef::npos)
477
18.9k
    path.set_size(end_pos);
478
18.9k
}
479
480
void replace_extension(SmallVectorImpl<char> &path, const Twine &extension,
481
19.2k
                       Style style) {
482
19.2k
  StringRef p(path.begin(), path.size());
483
19.2k
  SmallString<32> ext_storage;
484
19.2k
  StringRef ext = extension.toStringRef(ext_storage);
485
19.2k
486
19.2k
  // Erase existing extension.
487
19.2k
  size_t pos = p.find_last_of('.');
488
19.2k
  if (pos != StringRef::npos && 
pos >= filename_pos(p, style)18.6k
)
489
17.2k
    path.set_size(pos);
490
19.2k
491
19.2k
  // Append '.' if needed.
492
19.2k
  if (ext.size() > 0 && 
ext[0] != '.'18.4k
)
493
17.5k
    path.push_back('.');
494
19.2k
495
19.2k
  // Append extension.
496
19.2k
  path.append(ext.begin(), ext.end());
497
19.2k
}
498
499
void replace_path_prefix(SmallVectorImpl<char> &Path,
500
                         const StringRef &OldPrefix, const StringRef &NewPrefix,
501
8
                         Style style) {
502
8
  if (OldPrefix.empty() && 
NewPrefix.empty()1
)
503
0
    return;
504
8
505
8
  StringRef OrigPath(Path.begin(), Path.size());
506
8
  if (!OrigPath.startswith(OldPrefix))
507
1
    return;
508
7
509
7
  // If prefixes have the same size we can simply copy the new one over.
510
7
  if (OldPrefix.size() == NewPrefix.size()) {
511
4
    llvm::copy(NewPrefix, Path.begin());
512
4
    return;
513
4
  }
514
3
515
3
  StringRef RelPath = OrigPath.substr(OldPrefix.size());
516
3
  SmallString<256> NewPath;
517
3
  path::append(NewPath, style, NewPrefix);
518
3
  path::append(NewPath, style, RelPath);
519
3
  Path.swap(NewPath);
520
3
}
521
522
461k
void native(const Twine &path, SmallVectorImpl<char> &result, Style style) {
523
461k
  assert((!path.isSingleStringRef() ||
524
461k
          path.getSingleStringRef().data() != result.data()) &&
525
461k
         "path and result are not allowed to overlap!");
526
461k
  // Clear result.
527
461k
  result.clear();
528
461k
  path.toVector(result);
529
461k
  native(result, style);
530
461k
}
531
532
464k
void native(SmallVectorImpl<char> &Path, Style style) {
533
464k
  if (Path.empty())
534
6
    return;
535
464k
  if (real_style(style) == Style::windows) {
536
13
    std::replace(Path.begin(), Path.end(), '/', '\\');
537
13
    if (Path[0] == '~' && 
(0
Path.size() == 10
||
is_separator(Path[1], style)0
)) {
538
0
      SmallString<128> PathHome;
539
0
      home_directory(PathHome);
540
0
      PathHome.append(Path.begin() + 1, Path.end());
541
0
      Path = PathHome;
542
0
    }
543
464k
  } else {
544
60.1M
    for (auto PI = Path.begin(), PE = Path.end(); PI < PE; 
++PI59.6M
) {
545
59.6M
      if (*PI == '\\') {
546
42
        auto PN = PI + 1;
547
42
        if (PN < PE && 
*PN == '\\'38
)
548
1
          ++PI; // increment once, the for loop will move over the escaped slash
549
41
        else
550
41
          *PI = '/';
551
42
      }
552
59.6M
    }
553
464k
  }
554
464k
}
555
556
396
std::string convert_to_slash(StringRef path, Style style) {
557
396
  if (real_style(style) != Style::windows)
558
396
    return path;
559
0
560
0
  std::string s = path.str();
561
0
  std::replace(s.begin(), s.end(), '\\', '/');
562
0
  return s;
563
0
}
564
565
1.15M
StringRef filename(StringRef path, Style style) { return *rbegin(path, style); }
566
567
122k
StringRef stem(StringRef path, Style style) {
568
122k
  StringRef fname = filename(path, style);
569
122k
  size_t pos = fname.find_last_of('.');
570
122k
  if (pos == StringRef::npos)
571
96.1k
    return fname;
572
26.0k
  else
573
26.0k
    if ((fname.size() == 1 && 
fname == "."28
) ||
574
26.0k
        
(26.0k
fname.size() == 226.0k
&&
fname == ".."8
))
575
36
      return fname;
576
26.0k
    else
577
26.0k
      return fname.substr(0, pos);
578
122k
}
579
580
197k
StringRef extension(StringRef path, Style style) {
581
197k
  StringRef fname = filename(path, style);
582
197k
  size_t pos = fname.find_last_of('.');
583
197k
  if (pos == StringRef::npos)
584
117k
    return StringRef();
585
79.7k
  else
586
79.7k
    if ((fname.size() == 1 && 
fname == "."57
) ||
587
79.7k
        
(79.7k
fname.size() == 279.7k
&&
fname == ".."26
))
588
83
      return StringRef();
589
79.7k
    else
590
79.7k
      return fname.substr(pos);
591
197k
}
592
593
216M
bool is_separator(char value, Style style) {
594
216M
  if (value == '/')
595
80.9M
    return true;
596
135M
  if (real_style(style) == Style::windows)
597
29.2k
    return value == '\\';
598
135M
  return false;
599
135M
}
600
601
15.1k
StringRef get_separator(Style style) {
602
15.1k
  if (real_style(style) == Style::windows)
603
0
    return "\\";
604
15.1k
  return "/";
605
15.1k
}
606
607
11.2M
bool has_root_name(const Twine &path, Style style) {
608
11.2M
  SmallString<128> path_storage;
609
11.2M
  StringRef p = path.toStringRef(path_storage);
610
11.2M
611
11.2M
  return !root_name(p, style).empty();
612
11.2M
}
613
614
4.29M
bool has_root_directory(const Twine &path, Style style) {
615
4.29M
  SmallString<128> path_storage;
616
4.29M
  StringRef p = path.toStringRef(path_storage);
617
4.29M
618
4.29M
  return !root_directory(p, style).empty();
619
4.29M
}
620
621
41
bool has_root_path(const Twine &path, Style style) {
622
41
  SmallString<128> path_storage;
623
41
  StringRef p = path.toStringRef(path_storage);
624
41
625
41
  return !root_path(p, style).empty();
626
41
}
627
628
0
bool has_relative_path(const Twine &path, Style style) {
629
0
  SmallString<128> path_storage;
630
0
  StringRef p = path.toStringRef(path_storage);
631
0
632
0
  return !relative_path(p, style).empty();
633
0
}
634
635
41
bool has_filename(const Twine &path, Style style) {
636
41
  SmallString<128> path_storage;
637
41
  StringRef p = path.toStringRef(path_storage);
638
41
639
41
  return !filename(p, style).empty();
640
41
}
641
642
278
bool has_parent_path(const Twine &path, Style style) {
643
278
  SmallString<128> path_storage;
644
278
  StringRef p = path.toStringRef(path_storage);
645
278
646
278
  return !parent_path(p, style).empty();
647
278
}
648
649
41
bool has_stem(const Twine &path, Style style) {
650
41
  SmallString<128> path_storage;
651
41
  StringRef p = path.toStringRef(path_storage);
652
41
653
41
  return !stem(p, style).empty();
654
41
}
655
656
503
bool has_extension(const Twine &path, Style style) {
657
503
  SmallString<128> path_storage;
658
503
  StringRef p = path.toStringRef(path_storage);
659
503
660
503
  return !extension(p, style).empty();
661
503
}
662
663
2.67M
bool is_absolute(const Twine &path, Style style) {
664
2.67M
  SmallString<128> path_storage;
665
2.67M
  StringRef p = path.toStringRef(path_storage);
666
2.67M
667
2.67M
  bool rootDir = has_root_directory(p, style);
668
2.67M
  bool rootName =
669
2.67M
      (real_style(style) != Style::windows) || 
has_root_name(p, style)7.26k
;
670
2.67M
671
2.67M
  return rootDir && 
rootName959k
;
672
2.67M
}
673
674
56.4k
bool is_relative(const Twine &path, Style style) {
675
56.4k
  return !is_absolute(path, style);
676
56.4k
}
677
678
998k
StringRef remove_leading_dotslash(StringRef Path, Style style) {
679
998k
  // Remove leading "./" (or ".//" or "././" etc.)
680
998k
  while (Path.size() > 2 && 
Path[0] == '.'998k
&&
is_separator(Path[1], style)13
) {
681
13
    Path = Path.substr(2);
682
19
    while (Path.size() > 0 && 
is_separator(Path[0], style)18
)
683
6
      Path = Path.substr(1);
684
13
  }
685
998k
  return Path;
686
998k
}
687
688
static SmallString<256> remove_dots(StringRef path, bool remove_dot_dot,
689
1.16M
                                    Style style) {
690
1.16M
  SmallVector<StringRef, 16> components;
691
1.16M
692
1.16M
  // Skip the root path, then look for traversal in the components.
693
1.16M
  StringRef rel = path::relative_path(path, style);
694
1.16M
  for (StringRef C :
695
9.25M
       llvm::make_range(path::begin(rel, style), path::end(rel))) {
696
9.25M
    if (C == ".")
697
56.0k
      continue;
698
9.19M
    // Leading ".." will remain in the path unless it's at the root.
699
9.19M
    if (remove_dot_dot && 
C == ".."8.87M
) {
700
11.7k
      if (!components.empty() && 
components.back() != ".."11.7k
) {
701
11.7k
        components.pop_back();
702
11.7k
        continue;
703
11.7k
      }
704
33
      if (path::is_absolute(path, style))
705
3
        continue;
706
9.18M
    }
707
9.18M
    components.push_back(C);
708
9.18M
  }
709
1.16M
710
1.16M
  SmallString<256> buffer = path::root_path(path, style);
711
1.16M
  for (StringRef C : components)
712
9.17M
    path::append(buffer, style, C);
713
1.16M
  return buffer;
714
1.16M
}
715
716
bool remove_dots(SmallVectorImpl<char> &path, bool remove_dot_dot,
717
1.16M
                 Style style) {
718
1.16M
  StringRef p(path.data(), path.size());
719
1.16M
720
1.16M
  SmallString<256> result = remove_dots(p, remove_dot_dot, style);
721
1.16M
  if (result == path)
722
1.09M
    return false;
723
67.4k
724
67.4k
  path.swap(result);
725
67.4k
  return true;
726
67.4k
}
727
728
} // end namespace path
729
730
namespace fs {
731
732
10.8k
std::error_code getUniqueID(const Twine Path, UniqueID &Result) {
733
10.8k
  file_status Status;
734
10.8k
  std::error_code EC = status(Path, Status);
735
10.8k
  if (EC)
736
148
    return EC;
737
10.6k
  Result = Status.getUniqueID();
738
10.6k
  return std::error_code();
739
10.6k
}
740
741
void createUniquePath(const Twine &Model, SmallVectorImpl<char> &ResultPath,
742
39.7k
                      bool MakeAbsolute) {
743
39.7k
  SmallString<128> ModelStorage;
744
39.7k
  Model.toVector(ModelStorage);
745
39.7k
746
39.7k
  if (MakeAbsolute) {
747
9.23k
    // Make model absolute by prepending a temp directory if it's not already.
748
9.23k
    if (!sys::path::is_absolute(Twine(ModelStorage))) {
749
9.23k
      SmallString<128> TDir;
750
9.23k
      sys::path::system_temp_directory(true, TDir);
751
9.23k
      sys::path::append(TDir, Twine(ModelStorage));
752
9.23k
      ModelStorage.swap(TDir);
753
9.23k
    }
754
9.23k
  }
755
39.7k
756
39.7k
  ResultPath = ModelStorage;
757
39.7k
  ResultPath.push_back(0);
758
39.7k
  ResultPath.pop_back();
759
39.7k
760
39.7k
  // Replace '%' with random chars.
761
4.53M
  for (unsigned i = 0, e = ModelStorage.size(); i != e; 
++i4.49M
) {
762
4.49M
    if (ModelStorage[i] == '%')
763
275k
      ResultPath[i] = "0123456789abcdef"[sys::Process::GetRandomNumber() & 15];
764
4.49M
  }
765
39.7k
}
766
767
std::error_code createUniqueFile(const Twine &Model, int &ResultFd,
768
                                 SmallVectorImpl<char> &ResultPath,
769
20.2k
                                 unsigned Mode) {
770
20.2k
  return createUniqueEntity(Model, ResultFd, ResultPath, false, Mode, FS_File);
771
20.2k
}
772
773
static std::error_code createUniqueFile(const Twine &Model, int &ResultFd,
774
                                        SmallVectorImpl<char> &ResultPath,
775
8.18k
                                        unsigned Mode, OpenFlags Flags) {
776
8.18k
  return createUniqueEntity(Model, ResultFd, ResultPath, false, Mode, FS_File,
777
8.18k
                            Flags);
778
8.18k
}
779
780
std::error_code createUniqueFile(const Twine &Model,
781
                                 SmallVectorImpl<char> &ResultPath,
782
208
                                 unsigned Mode) {
783
208
  int FD;
784
208
  auto EC = createUniqueFile(Model, FD, ResultPath, Mode);
785
208
  if (EC)
786
0
    return EC;
787
208
  // FD is only needed to avoid race conditions. Close it right away.
788
208
  close(FD);
789
208
  return EC;
790
208
}
791
792
static std::error_code
793
createTemporaryFile(const Twine &Model, int &ResultFD,
794
9.15k
                    llvm::SmallVectorImpl<char> &ResultPath, FSEntity Type) {
795
9.15k
  SmallString<128> Storage;
796
9.15k
  StringRef P = Model.toNullTerminatedStringRef(Storage);
797
9.15k
  assert(P.find_first_of(separators(Style::native)) == StringRef::npos &&
798
9.15k
         "Model must be a simple filename.");
799
9.15k
  // Use P.begin() so that createUniqueEntity doesn't need to recreate Storage.
800
9.15k
  return createUniqueEntity(P.begin(), ResultFD, ResultPath, true,
801
9.15k
                            owner_read | owner_write, Type);
802
9.15k
}
803
804
static std::error_code
805
createTemporaryFile(const Twine &Prefix, StringRef Suffix, int &ResultFD,
806
9.15k
                    llvm::SmallVectorImpl<char> &ResultPath, FSEntity Type) {
807
9.15k
  const char *Middle = Suffix.empty() ? 
"-%%%%%%"28
:
"-%%%%%%."9.12k
;
808
9.15k
  return createTemporaryFile(Prefix + Middle + Suffix, ResultFD, ResultPath,
809
9.15k
                             Type);
810
9.15k
}
811
812
std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
813
                                    int &ResultFD,
814
9.15k
                                    SmallVectorImpl<char> &ResultPath) {
815
9.15k
  return createTemporaryFile(Prefix, Suffix, ResultFD, ResultPath, FS_File);
816
9.15k
}
817
818
std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
819
8.97k
                                    SmallVectorImpl<char> &ResultPath) {
820
8.97k
  int FD;
821
8.97k
  auto EC = createTemporaryFile(Prefix, Suffix, FD, ResultPath);
822
8.97k
  if (EC)
823
0
    return EC;
824
8.97k
  // FD is only needed to avoid race conditions. Close it right away.
825
8.97k
  close(FD);
826
8.97k
  return EC;
827
8.97k
}
828
829
830
// This is a mkdtemp with a different pattern. We use createUniqueEntity mostly
831
// for consistency. We should try using mkdtemp.
832
std::error_code createUniqueDirectory(const Twine &Prefix,
833
73
                                      SmallVectorImpl<char> &ResultPath) {
834
73
  int Dummy;
835
73
  return createUniqueEntity(Prefix + "-%%%%%%", Dummy, ResultPath, true, 0,
836
73
                            FS_Dir);
837
73
}
838
839
std::error_code
840
getPotentiallyUniqueFileName(const Twine &Model,
841
0
                             SmallVectorImpl<char> &ResultPath) {
842
0
  int Dummy;
843
0
  return createUniqueEntity(Model, Dummy, ResultPath, false, 0, FS_Name);
844
0
}
845
846
std::error_code
847
getPotentiallyUniqueTempFileName(const Twine &Prefix, StringRef Suffix,
848
1
                                 SmallVectorImpl<char> &ResultPath) {
849
1
  int Dummy;
850
1
  return createTemporaryFile(Prefix, Suffix, Dummy, ResultPath, FS_Name);
851
1
}
852
853
void make_absolute(const Twine &current_directory,
854
1.62M
                   SmallVectorImpl<char> &path) {
855
1.62M
  StringRef p(path.data(), path.size());
856
1.62M
857
1.62M
  bool rootDirectory = path::has_root_directory(p);
858
1.62M
  bool rootName =
859
1.62M
      (real_style(Style::native) != Style::windows) || 
path::has_root_name(p)0
;
860
1.62M
861
1.62M
  // Already absolute.
862
1.62M
  if (
rootName1.62M
&& rootDirectory)
863
1.27M
    return;
864
349k
865
349k
  // All of the following conditions will need the current directory.
866
349k
  SmallString<128> current_dir;
867
349k
  current_directory.toVector(current_dir);
868
349k
869
349k
  // Relative path. Prepend the current directory.
870
349k
  if (!rootName && 
!rootDirectory0
) {
871
0
    // Append path to the current directory.
872
0
    path::append(current_dir, p);
873
0
    // Set path to the result.
874
0
    path.swap(current_dir);
875
0
    return;
876
0
  }
877
349k
878
349k
  if (!rootName && 
rootDirectory0
) {
879
0
    StringRef cdrn = path::root_name(current_dir);
880
0
    SmallString<128> curDirRootName(cdrn.begin(), cdrn.end());
881
0
    path::append(curDirRootName, p);
882
0
    // Set path to the result.
883
0
    path.swap(curDirRootName);
884
0
    return;
885
0
  }
886
349k
887
349k
  
if (349k
rootName349k
&& !rootDirectory) {
888
349k
    StringRef pRootName      = path::root_name(p);
889
349k
    StringRef bRootDirectory = path::root_directory(current_dir);
890
349k
    StringRef bRelativePath  = path::relative_path(current_dir);
891
349k
    StringRef pRelativePath  = path::relative_path(p);
892
349k
893
349k
    SmallString<128> res;
894
349k
    path::append(res, pRootName, bRootDirectory, bRelativePath, pRelativePath);
895
349k
    path.swap(res);
896
349k
    return;
897
349k
  }
898
18.4E
899
18.4E
  llvm_unreachable("All rootName and rootDirectory combinations should have "
900
18.4E
                   "occurred above!");
901
18.4E
}
902
903
26.4k
std::error_code make_absolute(SmallVectorImpl<char> &path) {
904
26.4k
  if (path::is_absolute(path))
905
26.2k
    return {};
906
245
907
245
  SmallString<128> current_dir;
908
245
  if (std::error_code ec = current_path(current_dir))
909
0
    return ec;
910
245
911
245
  make_absolute(current_dir, path);
912
245
  return {};
913
245
}
914
915
std::error_code create_directories(const Twine &Path, bool IgnoreExisting,
916
2.76k
                                   perms Perms) {
917
2.76k
  SmallString<128> PathStorage;
918
2.76k
  StringRef P = Path.toStringRef(PathStorage);
919
2.76k
920
2.76k
  // Be optimistic and try to create the directory
921
2.76k
  std::error_code EC = create_directory(P, IgnoreExisting, Perms);
922
2.76k
  // If we succeeded, or had any error other than the parent not existing, just
923
2.76k
  // return it.
924
2.76k
  if (EC != errc::no_such_file_or_directory)
925
2.07k
    return EC;
926
693
927
693
  // We failed because of a no_such_file_or_directory, try to create the
928
693
  // parent.
929
693
  StringRef Parent = path::parent_path(P);
930
693
  if (Parent.empty())
931
0
    return EC;
932
693
933
693
  if ((EC = create_directories(Parent, IgnoreExisting, Perms)))
934
0
      return EC;
935
693
936
693
  return create_directory(P, IgnoreExisting, Perms);
937
693
}
938
939
0
static std::error_code copy_file_internal(int ReadFD, int WriteFD) {
940
0
  const size_t BufSize = 4096;
941
0
  char *Buf = new char[BufSize];
942
0
  int BytesRead = 0, BytesWritten = 0;
943
0
  for (;;) {
944
0
    BytesRead = read(ReadFD, Buf, BufSize);
945
0
    if (BytesRead <= 0)
946
0
      break;
947
0
    while (BytesRead) {
948
0
      BytesWritten = write(WriteFD, Buf, BytesRead);
949
0
      if (BytesWritten < 0)
950
0
        break;
951
0
      BytesRead -= BytesWritten;
952
0
    }
953
0
    if (BytesWritten < 0)
954
0
      break;
955
0
  }
956
0
  delete[] Buf;
957
0
958
0
  if (BytesRead < 0 || BytesWritten < 0)
959
0
    return std::error_code(errno, std::generic_category());
960
0
  return std::error_code();
961
0
}
962
963
#ifndef __APPLE__
964
std::error_code copy_file(const Twine &From, const Twine &To) {
965
  int ReadFD, WriteFD;
966
  if (std::error_code EC = openFileForRead(From, ReadFD, OF_None))
967
    return EC;
968
  if (std::error_code EC =
969
          openFileForWrite(To, WriteFD, CD_CreateAlways, OF_None)) {
970
    close(ReadFD);
971
    return EC;
972
  }
973
974
  std::error_code EC = copy_file_internal(ReadFD, WriteFD);
975
976
  close(ReadFD);
977
  close(WriteFD);
978
979
  return EC;
980
}
981
#endif
982
983
0
std::error_code copy_file(const Twine &From, int ToFD) {
984
0
  int ReadFD;
985
0
  if (std::error_code EC = openFileForRead(From, ReadFD, OF_None))
986
0
    return EC;
987
0
988
0
  std::error_code EC = copy_file_internal(ReadFD, ToFD);
989
0
990
0
  close(ReadFD);
991
0
992
0
  return EC;
993
0
}
994
995
1
ErrorOr<MD5::MD5Result> md5_contents(int FD) {
996
1
  MD5 Hash;
997
1
998
1
  constexpr size_t BufSize = 4096;
999
1
  std::vector<uint8_t> Buf(BufSize);
1000
1
  int BytesRead = 0;
1001
2
  for (;;) {
1002
2
    BytesRead = read(FD, Buf.data(), BufSize);
1003
2
    if (BytesRead <= 0)
1004
1
      break;
1005
1
    Hash.update(makeArrayRef(Buf.data(), BytesRead));
1006
1
  }
1007
1
1008
1
  if (BytesRead < 0)
1009
0
    return std::error_code(errno, std::generic_category());
1010
1
  MD5::MD5Result Result;
1011
1
  Hash.final(Result);
1012
1
  return Result;
1013
1
}
1014
1015
0
ErrorOr<MD5::MD5Result> md5_contents(const Twine &Path) {
1016
0
  int FD;
1017
0
  if (auto EC = openFileForRead(Path, FD, OF_None))
1018
0
    return EC;
1019
0
1020
0
  auto Result = md5_contents(FD);
1021
0
  close(FD);
1022
0
  return Result;
1023
0
}
1024
1025
17.9k
bool exists(const basic_file_status &status) {
1026
17.9k
  return status_known(status) && status.type() != file_type::file_not_found;
1027
17.9k
}
1028
1029
17.9k
bool status_known(const basic_file_status &s) {
1030
17.9k
  return s.type() != file_type::status_error;
1031
17.9k
}
1032
1033
0
file_type get_file_type(const Twine &Path, bool Follow) {
1034
0
  file_status st;
1035
0
  if (status(Path, st, Follow))
1036
0
    return file_type::status_error;
1037
0
  return st.type();
1038
0
}
1039
1040
2.75k
bool is_directory(const basic_file_status &status) {
1041
2.75k
  return status.type() == file_type::directory_file;
1042
2.75k
}
1043
1044
3.32k
std::error_code is_directory(const Twine &path, bool &result) {
1045
3.32k
  file_status st;
1046
3.32k
  if (std::error_code ec = status(path, st))
1047
622
    return ec;
1048
2.70k
  result = is_directory(st);
1049
2.70k
  return std::error_code();
1050
2.70k
}
1051
1052
13.3k
bool is_regular_file(const basic_file_status &status) {
1053
13.3k
  return status.type() == file_type::regular_file;
1054
13.3k
}
1055
1056
8.10k
std::error_code is_regular_file(const Twine &path, bool &result) {
1057
8.10k
  file_status st;
1058
8.10k
  if (std::error_code ec = status(path, st))
1059
48
    return ec;
1060
8.05k
  result = is_regular_file(st);
1061
8.05k
  return std::error_code();
1062
8.05k
}
1063
1064
525
bool is_symlink_file(const basic_file_status &status) {
1065
525
  return status.type() == file_type::symlink_file;
1066
525
}
1067
1068
530
std::error_code is_symlink_file(const Twine &path, bool &result) {
1069
530
  file_status st;
1070
530
  if (std::error_code ec = status(path, st, false))
1071
5
    return ec;
1072
525
  result = is_symlink_file(st);
1073
525
  return std::error_code();
1074
525
}
1075
1076
0
bool is_other(const basic_file_status &status) {
1077
0
  return exists(status) &&
1078
0
         !is_regular_file(status) &&
1079
0
         !is_directory(status);
1080
0
}
1081
1082
0
std::error_code is_other(const Twine &Path, bool &Result) {
1083
0
  file_status FileStatus;
1084
0
  if (std::error_code EC = status(Path, FileStatus))
1085
0
    return EC;
1086
0
  Result = is_other(FileStatus);
1087
0
  return std::error_code();
1088
0
}
1089
1090
void directory_entry::replace_filename(const Twine &Filename, file_type Type,
1091
12.4k
                                       basic_file_status Status) {
1092
12.4k
  SmallString<128> PathStr = path::parent_path(Path);
1093
12.4k
  path::append(PathStr, Filename);
1094
12.4k
  this->Path = PathStr.str();
1095
12.4k
  this->Type = Type;
1096
12.4k
  this->Status = Status;
1097
12.4k
}
1098
1099
29
ErrorOr<perms> getPermissions(const Twine &Path) {
1100
29
  file_status Status;
1101
29
  if (std::error_code EC = status(Path, Status))
1102
0
    return EC;
1103
29
1104
29
  return Status.permissions();
1105
29
}
1106
1107
} // end namespace fs
1108
} // end namespace sys
1109
} // end namespace llvm
1110
1111
// Include the truly platform-specific parts.
1112
#if defined(LLVM_ON_UNIX)
1113
#include "Unix/Path.inc"
1114
#endif
1115
#if defined(_WIN32)
1116
#include "Windows/Path.inc"
1117
#endif
1118
1119
namespace llvm {
1120
namespace sys {
1121
namespace fs {
1122
8.16k
TempFile::TempFile(StringRef Name, int FD) : TmpName(Name), FD(FD) {}
1123
30.0k
TempFile::TempFile(TempFile &&Other) { *this = std::move(Other); }
1124
30.0k
TempFile &TempFile::operator=(TempFile &&Other) {
1125
30.0k
  TmpName = std::move(Other.TmpName);
1126
30.0k
  FD = Other.FD;
1127
30.0k
  Other.Done = true;
1128
30.0k
  Other.FD = -1;
1129
30.0k
  return *this;
1130
30.0k
}
1131
1132
38.1k
TempFile::~TempFile() { assert(Done); }
1133
1134
7.48k
Error TempFile::discard() {
1135
7.48k
  Done = true;
1136
7.48k
  if (FD != -1 && 
close(FD) == -13.49k
) {
1137
0
    std::error_code EC = std::error_code(errno, std::generic_category());
1138
0
    return errorCodeToError(EC);
1139
0
  }
1140
7.48k
  FD = -1;
1141
7.48k
1142
#ifdef _WIN32
1143
  // On windows closing will remove the file.
1144
  TmpName = "";
1145
  return Error::success();
1146
#else
1147
  // Always try to close and remove.
1148
7.48k
  std::error_code RemoveEC;
1149
7.48k
  if (!TmpName.empty()) {
1150
3.49k
    RemoveEC = fs::remove(TmpName);
1151
3.49k
    sys::DontRemoveFileOnSignal(TmpName);
1152
3.49k
    if (!RemoveEC)
1153
3.49k
      TmpName = "";
1154
3.49k
  }
1155
7.48k
  return errorCodeToError(RemoveEC);
1156
7.48k
#endif
1157
7.48k
}
1158
1159
4.66k
Error TempFile::keep(const Twine &Name) {
1160
4.66k
  assert(!Done);
1161
4.66k
  Done = true;
1162
4.66k
  // Always try to close and rename.
1163
#ifdef _WIN32
1164
  // If we can't cancel the delete don't rename.
1165
  auto H = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
1166
  std::error_code RenameEC = setDeleteDisposition(H, false);
1167
  if (!RenameEC) {
1168
    RenameEC = rename_fd(FD, Name);
1169
    // If rename failed because it's cross-device, copy instead
1170
    if (RenameEC ==
1171
      std::error_code(ERROR_NOT_SAME_DEVICE, std::system_category())) {
1172
      RenameEC = copy_file(TmpName, Name);
1173
      setDeleteDisposition(H, true);
1174
    }
1175
  }
1176
1177
  // If we can't rename, discard the temporary file.
1178
  if (RenameEC)
1179
    setDeleteDisposition(H, true);
1180
#else
1181
  std::error_code RenameEC = fs::rename(TmpName, Name);
1182
4.66k
  if (RenameEC) {
1183
1
    // If we can't rename, try to copy to work around cross-device link issues.
1184
1
    RenameEC = sys::fs::copy_file(TmpName, Name);
1185
1
    // If we can't rename or copy, discard the temporary file.
1186
1
    if (RenameEC)
1187
1
      remove(TmpName);
1188
1
  }
1189
4.66k
  sys::DontRemoveFileOnSignal(TmpName);
1190
4.66k
#endif
1191
4.66k
1192
4.66k
  if (!RenameEC)
1193
4.66k
    TmpName = "";
1194
4.66k
1195
4.66k
  if (close(FD) == -1) {
1196
0
    std::error_code EC(errno, std::generic_category());
1197
0
    return errorCodeToError(EC);
1198
0
  }
1199
4.66k
  FD = -1;
1200
4.66k
1201
4.66k
  return errorCodeToError(RenameEC);
1202
4.66k
}
1203
1204
0
Error TempFile::keep() {
1205
0
  assert(!Done);
1206
0
  Done = true;
1207
0
1208
#ifdef _WIN32
1209
  auto H = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
1210
  if (std::error_code EC = setDeleteDisposition(H, false))
1211
    return errorCodeToError(EC);
1212
#else
1213
  sys::DontRemoveFileOnSignal(TmpName);
1214
0
#endif
1215
0
1216
0
  TmpName = "";
1217
0
1218
0
  if (close(FD) == -1) {
1219
0
    std::error_code EC(errno, std::generic_category());
1220
0
    return errorCodeToError(EC);
1221
0
  }
1222
0
  FD = -1;
1223
0
1224
0
  return Error::success();
1225
0
}
1226
1227
8.18k
Expected<TempFile> TempFile::create(const Twine &Model, unsigned Mode) {
1228
8.18k
  int FD;
1229
8.18k
  SmallString<128> ResultPath;
1230
8.18k
  if (std::error_code EC =
1231
26
          createUniqueFile(Model, FD, ResultPath, Mode, OF_Delete))
1232
26
    return errorCodeToError(EC);
1233
8.16k
1234
8.16k
  TempFile Ret(ResultPath, FD);
1235
8.16k
#ifndef _WIN32
1236
8.16k
  if (sys::RemoveFileOnSignal(ResultPath)) {
1237
0
    // Make sure we delete the file when RemoveFileOnSignal fails.
1238
0
    consumeError(Ret.discard());
1239
0
    std::error_code EC(errc::operation_not_permitted);
1240
0
    return errorCodeToError(EC);
1241
0
  }
1242
8.16k
#endif
1243
8.16k
  return std::move(Ret);
1244
8.16k
}
1245
}
1246
1247
} // end namsspace sys
1248
} // end namespace llvm