Path.inc revision 218885
1218885Sdim//===- llvm/Support/Win32/Path.cpp - Win32 Path Implementation ---*- C++ -*-===//
2218885Sdim//
3218885Sdim//                     The LLVM Compiler Infrastructure
4218885Sdim//
5218885Sdim// This file is distributed under the University of Illinois Open Source
6218885Sdim// License. See LICENSE.TXT for details.
7218885Sdim//
8218885Sdim//===----------------------------------------------------------------------===//
9218885Sdim//
10218885Sdim// This file provides the Win32 specific implementation of the Path class.
11218885Sdim//
12218885Sdim//===----------------------------------------------------------------------===//
13218885Sdim
14218885Sdim//===----------------------------------------------------------------------===//
15218885Sdim//=== WARNING: Implementation here must contain only generic Win32 code that
16218885Sdim//===          is guaranteed to work on *all* Win32 variants.
17218885Sdim//===----------------------------------------------------------------------===//
18218885Sdim
19218885Sdim#include "Windows.h"
20218885Sdim#include <malloc.h>
21218885Sdim#include <cstdio>
22218885Sdim
23218885Sdim// We need to undo a macro defined in Windows.h, otherwise we won't compile:
24218885Sdim#undef CopyFile
25218885Sdim#undef GetCurrentDirectory
26218885Sdim
27218885Sdim// Windows happily accepts either forward or backward slashes, though any path
28218885Sdim// returned by a Win32 API will have backward slashes.  As LLVM code basically
29218885Sdim// assumes forward slashes are used, backward slashs are converted where they
30218885Sdim// can be introduced into a path.
31218885Sdim//
32218885Sdim// Another invariant is that a path ends with a slash if and only if the path
33218885Sdim// is a root directory.  Any other use of a trailing slash is stripped.  Unlike
34218885Sdim// in Unix, Windows has a rather complicated notion of a root path and this
35218885Sdim// invariant helps simply the code.
36218885Sdim
37218885Sdimstatic void FlipBackSlashes(std::string& s) {
38218885Sdim  for (size_t i = 0; i < s.size(); i++)
39218885Sdim    if (s[i] == '\\')
40218885Sdim      s[i] = '/';
41218885Sdim}
42218885Sdim
43218885Sdimnamespace llvm {
44218885Sdimnamespace sys {
45218885Sdim
46218885Sdimconst char PathSeparator = ';';
47218885Sdim
48218885SdimStringRef Path::GetEXESuffix() {
49218885Sdim  return "exe";
50218885Sdim}
51218885Sdim
52218885SdimPath::Path(llvm::StringRef p)
53218885Sdim  : path(p) {
54218885Sdim  FlipBackSlashes(path);
55218885Sdim}
56218885Sdim
57218885SdimPath::Path(const char *StrStart, unsigned StrLen)
58218885Sdim  : path(StrStart, StrLen) {
59218885Sdim  FlipBackSlashes(path);
60218885Sdim}
61218885Sdim
62218885SdimPath&
63218885SdimPath::operator=(StringRef that) {
64218885Sdim  path.assign(that.data(), that.size());
65218885Sdim  FlipBackSlashes(path);
66218885Sdim  return *this;
67218885Sdim}
68218885Sdim
69218885Sdim// push_back 0 on create, and pop_back on delete.
70218885Sdimstruct ScopedNullTerminator {
71218885Sdim  std::string &str;
72218885Sdim  ScopedNullTerminator(std::string &s) : str(s) { str.push_back(0); }
73218885Sdim  ~ScopedNullTerminator() {
74218885Sdim    // str.pop_back(); But wait, C++03 doesn't have this...
75218885Sdim    assert(!str.empty() && str[str.size() - 1] == 0
76218885Sdim      && "Null char not present!");
77218885Sdim    str.resize(str.size() - 1);
78218885Sdim  }
79218885Sdim};
80218885Sdim
81218885Sdimbool
82218885SdimPath::isValid() const {
83218885Sdim  if (path.empty())
84218885Sdim    return false;
85218885Sdim
86218885Sdim  // If there is a colon, it must be the second character, preceded by a letter
87218885Sdim  // and followed by something.
88218885Sdim  size_t len = path.size();
89218885Sdim  // This code assumes that path is null terminated, so make sure it is.
90218885Sdim  ScopedNullTerminator snt(path);
91218885Sdim  size_t pos = path.rfind(':',len);
92218885Sdim  size_t rootslash = 0;
93218885Sdim  if (pos != std::string::npos) {
94218885Sdim    if (pos != 1 || !isalpha(path[0]) || len < 3)
95218885Sdim      return false;
96218885Sdim      rootslash = 2;
97218885Sdim  }
98218885Sdim
99218885Sdim  // Look for a UNC path, and if found adjust our notion of the root slash.
100218885Sdim  if (len > 3 && path[0] == '/' && path[1] == '/') {
101218885Sdim    rootslash = path.find('/', 2);
102218885Sdim    if (rootslash == std::string::npos)
103218885Sdim      rootslash = 0;
104218885Sdim  }
105218885Sdim
106218885Sdim  // Check for illegal characters.
107218885Sdim  if (path.find_first_of("\\<>\"|\001\002\003\004\005\006\007\010\011\012"
108218885Sdim                         "\013\014\015\016\017\020\021\022\023\024\025\026"
109218885Sdim                         "\027\030\031\032\033\034\035\036\037")
110218885Sdim      != std::string::npos)
111218885Sdim    return false;
112218885Sdim
113218885Sdim  // Remove trailing slash, unless it's a root slash.
114218885Sdim  if (len > rootslash+1 && path[len-1] == '/')
115218885Sdim    path.erase(--len);
116218885Sdim
117218885Sdim  // Check each component for legality.
118218885Sdim  for (pos = 0; pos < len; ++pos) {
119218885Sdim    // A component may not end in a space.
120218885Sdim    if (path[pos] == ' ') {
121218885Sdim      if (path[pos+1] == '/' || path[pos+1] == '\0')
122218885Sdim        return false;
123218885Sdim    }
124218885Sdim
125218885Sdim    // A component may not end in a period.
126218885Sdim    if (path[pos] == '.') {
127218885Sdim      if (path[pos+1] == '/' || path[pos+1] == '\0') {
128218885Sdim        // Unless it is the pseudo-directory "."...
129218885Sdim        if (pos == 0 || path[pos-1] == '/' || path[pos-1] == ':')
130218885Sdim          return true;
131218885Sdim        // or "..".
132218885Sdim        if (pos > 0 && path[pos-1] == '.') {
133218885Sdim          if (pos == 1 || path[pos-2] == '/' || path[pos-2] == ':')
134218885Sdim            return true;
135218885Sdim        }
136218885Sdim        return false;
137218885Sdim      }
138218885Sdim    }
139218885Sdim  }
140218885Sdim
141218885Sdim  return true;
142218885Sdim}
143218885Sdim
144218885Sdimvoid Path::makeAbsolute() {
145218885Sdim  TCHAR  FullPath[MAX_PATH + 1] = {0};
146218885Sdim  LPTSTR FilePart = NULL;
147218885Sdim
148218885Sdim  DWORD RetLength = ::GetFullPathNameA(path.c_str(),
149218885Sdim                        sizeof(FullPath)/sizeof(FullPath[0]),
150218885Sdim                        FullPath, &FilePart);
151218885Sdim
152218885Sdim  if (0 == RetLength) {
153218885Sdim    // FIXME: Report the error GetLastError()
154218885Sdim    assert(0 && "Unable to make absolute path!");
155218885Sdim  } else if (RetLength > MAX_PATH) {
156218885Sdim    // FIXME: Report too small buffer (needed RetLength bytes).
157218885Sdim    assert(0 && "Unable to make absolute path!");
158218885Sdim  } else {
159218885Sdim    path = FullPath;
160218885Sdim  }
161218885Sdim}
162218885Sdim
163218885Sdimbool
164218885SdimPath::isAbsolute(const char *NameStart, unsigned NameLen) {
165218885Sdim  assert(NameStart);
166218885Sdim  // FIXME: This does not handle correctly an absolute path starting from
167218885Sdim  // a drive letter or in UNC format.
168218885Sdim  switch (NameLen) {
169218885Sdim  case 0:
170218885Sdim    return false;
171218885Sdim  case 1:
172218885Sdim  case 2:
173218885Sdim    return NameStart[0] == '/';
174218885Sdim  default:
175218885Sdim    return
176218885Sdim      (NameStart[0] == '/' || (NameStart[1] == ':' && NameStart[2] == '/')) ||
177218885Sdim      (NameStart[0] == '\\' || (NameStart[1] == ':' && NameStart[2] == '\\'));
178218885Sdim  }
179218885Sdim}
180218885Sdim
181218885Sdimbool
182218885SdimPath::isAbsolute() const {
183218885Sdim  // FIXME: This does not handle correctly an absolute path starting from
184218885Sdim  // a drive letter or in UNC format.
185218885Sdim  switch (path.length()) {
186218885Sdim    case 0:
187218885Sdim      return false;
188218885Sdim    case 1:
189218885Sdim    case 2:
190218885Sdim      return path[0] == '/';
191218885Sdim    default:
192218885Sdim      return path[0] == '/' || (path[1] == ':' && path[2] == '/');
193218885Sdim  }
194218885Sdim}
195218885Sdim
196218885Sdimstatic Path *TempDirectory;
197218885Sdim
198218885SdimPath
199218885SdimPath::GetTemporaryDirectory(std::string* ErrMsg) {
200218885Sdim  if (TempDirectory)
201218885Sdim    return *TempDirectory;
202218885Sdim
203218885Sdim  char pathname[MAX_PATH];
204218885Sdim  if (!GetTempPath(MAX_PATH, pathname)) {
205218885Sdim    if (ErrMsg)
206218885Sdim      *ErrMsg = "Can't determine temporary directory";
207218885Sdim    return Path();
208218885Sdim  }
209218885Sdim
210218885Sdim  Path result;
211218885Sdim  result.set(pathname);
212218885Sdim
213218885Sdim  // Append a subdirectory passed on our process id so multiple LLVMs don't
214218885Sdim  // step on each other's toes.
215218885Sdim#ifdef __MINGW32__
216218885Sdim  // Mingw's Win32 header files are broken.
217218885Sdim  sprintf(pathname, "LLVM_%u", unsigned(GetCurrentProcessId()));
218218885Sdim#else
219218885Sdim  sprintf(pathname, "LLVM_%u", GetCurrentProcessId());
220218885Sdim#endif
221218885Sdim  result.appendComponent(pathname);
222218885Sdim
223218885Sdim  // If there's a directory left over from a previous LLVM execution that
224218885Sdim  // happened to have the same process id, get rid of it.
225218885Sdim  result.eraseFromDisk(true);
226218885Sdim
227218885Sdim  // And finally (re-)create the empty directory.
228218885Sdim  result.createDirectoryOnDisk(false);
229218885Sdim  TempDirectory = new Path(result);
230218885Sdim  return *TempDirectory;
231218885Sdim}
232218885Sdim
233218885Sdim// FIXME: the following set of functions don't map to Windows very well.
234218885SdimPath
235218885SdimPath::GetRootDirectory() {
236218885Sdim  // This is the only notion that that Windows has of a root directory. Nothing
237218885Sdim  // is here except for drives.
238218885Sdim  return Path("file:///");
239218885Sdim}
240218885Sdim
241218885Sdimvoid
242218885SdimPath::GetSystemLibraryPaths(std::vector& Paths) {
243218885Sdim  char buff[MAX_PATH];
244218885Sdim  // Generic form of C:\Windows\System32
245218885Sdim  HRESULT res =  SHGetFolderPathA(NULL,
246218885Sdim                                  CSIDL_FLAG_CREATE | CSIDL_SYSTEM,
247218885Sdim                                  NULL,
248218885Sdim                                  SHGFP_TYPE_CURRENT,
249218885Sdim                                  buff);
250218885Sdim  if (res != S_OK) {
251218885Sdim    assert(0 && "Failed to get system directory");
252218885Sdim    return;
253218885Sdim  }
254218885Sdim  Paths.push_back(sys::Path(buff));
255218885Sdim
256218885Sdim  // Reset buff.
257218885Sdim  buff[0] = 0;
258218885Sdim  // Generic form of C:\Windows
259218885Sdim  res =  SHGetFolderPathA(NULL,
260218885Sdim                          CSIDL_FLAG_CREATE | CSIDL_WINDOWS,
261218885Sdim                          NULL,
262218885Sdim                          SHGFP_TYPE_CURRENT,
263218885Sdim                          buff);
264218885Sdim  if (res != S_OK) {
265218885Sdim    assert(0 && "Failed to get windows directory");
266218885Sdim    return;
267218885Sdim  }
268218885Sdim  Paths.push_back(sys::Path(buff));
269218885Sdim}
270218885Sdim
271218885Sdimvoid
272218885SdimPath::GetBitcodeLibraryPaths(std::vector& Paths) {
273218885Sdim  char * env_var = getenv("LLVM_LIB_SEARCH_PATH");
274218885Sdim  if (env_var != 0) {
275218885Sdim    getPathList(env_var,Paths);
276218885Sdim  }
277218885Sdim#ifdef LLVM_LIBDIR
278218885Sdim  {
279218885Sdim    Path tmpPath;
280218885Sdim    if (tmpPath.set(LLVM_LIBDIR))
281218885Sdim      if (tmpPath.canRead())
282218885Sdim        Paths.push_back(tmpPath);
283218885Sdim  }
284218885Sdim#endif
285218885Sdim  GetSystemLibraryPaths(Paths);
286218885Sdim}
287218885Sdim
288218885SdimPath
289218885SdimPath::GetLLVMDefaultConfigDir() {
290218885Sdim  Path ret = GetUserHomeDirectory();
291218885Sdim  if (!ret.appendComponent(".llvm"))
292218885Sdim    assert(0 && "Failed to append .llvm");
293218885Sdim  return ret;
294218885Sdim}
295218885Sdim
296218885SdimPath
297218885SdimPath::GetUserHomeDirectory() {
298218885Sdim  char buff[MAX_PATH];
299218885Sdim  HRESULT res = SHGetFolderPathA(NULL,
300218885Sdim                                 CSIDL_FLAG_CREATE | CSIDL_APPDATA,
301218885Sdim                                 NULL,
302218885Sdim                                 SHGFP_TYPE_CURRENT,
303218885Sdim                                 buff);
304218885Sdim  if (res != S_OK)
305218885Sdim    assert(0 && "Failed to get user home directory");
306218885Sdim  return Path(buff);
307218885Sdim}
308218885Sdim
309218885SdimPath
310218885SdimPath::GetCurrentDirectory() {
311218885Sdim  char pathname[MAX_PATH];
312218885Sdim  ::GetCurrentDirectoryA(MAX_PATH,pathname);
313218885Sdim  return Path(pathname);
314218885Sdim}
315218885Sdim
316218885Sdim/// GetMainExecutable - Return the path to the main executable, given the
317218885Sdim/// value of argv[0] from program startup.
318218885SdimPath Path::GetMainExecutable(const char *argv0, void *MainAddr) {
319218885Sdim  char pathname[MAX_PATH];
320218885Sdim  DWORD ret = ::GetModuleFileNameA(NULL, pathname, MAX_PATH);
321218885Sdim  return ret != MAX_PATH ? Path(pathname) : Path();
322218885Sdim}
323218885Sdim
324218885Sdim
325218885Sdim// FIXME: the above set of functions don't map to Windows very well.
326218885Sdim
327218885Sdim
328218885SdimStringRef Path::getDirname() const {
329218885Sdim  return getDirnameCharSep(path, "/");
330218885Sdim}
331218885Sdim
332218885SdimStringRef
333218885SdimPath::getBasename() const {
334218885Sdim  // Find the last slash
335218885Sdim  size_t slash = path.rfind('/');
336218885Sdim  if (slash == std::string::npos)
337218885Sdim    slash = 0;
338218885Sdim  else
339218885Sdim    slash++;
340218885Sdim
341218885Sdim  size_t dot = path.rfind('.');
342218885Sdim  if (dot == std::string::npos || dot < slash)
343218885Sdim    return StringRef(path).substr(slash);
344218885Sdim  else
345218885Sdim    return StringRef(path).substr(slash, dot - slash);
346218885Sdim}
347218885Sdim
348218885SdimStringRef
349218885SdimPath::getSuffix() const {
350218885Sdim  // Find the last slash
351218885Sdim  size_t slash = path.rfind('/');
352218885Sdim  if (slash == std::string::npos)
353218885Sdim    slash = 0;
354218885Sdim  else
355218885Sdim    slash++;
356218885Sdim
357218885Sdim  size_t dot = path.rfind('.');
358218885Sdim  if (dot == std::string::npos || dot < slash)
359218885Sdim    return StringRef("");
360218885Sdim  else
361218885Sdim    return StringRef(path).substr(dot + 1);
362218885Sdim}
363218885Sdim
364218885Sdimbool
365218885SdimPath::exists() const {
366218885Sdim  DWORD attr = GetFileAttributes(path.c_str());
367218885Sdim  return attr != INVALID_FILE_ATTRIBUTES;
368218885Sdim}
369218885Sdim
370218885Sdimbool
371218885SdimPath::isDirectory() const {
372218885Sdim  DWORD attr = GetFileAttributes(path.c_str());
373218885Sdim  return (attr != INVALID_FILE_ATTRIBUTES) &&
374218885Sdim         (attr & FILE_ATTRIBUTE_DIRECTORY);
375218885Sdim}
376218885Sdim
377218885Sdimbool
378218885SdimPath::isSymLink() const {
379218885Sdim  DWORD attributes = GetFileAttributes(path.c_str());
380218885Sdim
381218885Sdim  if (attributes == INVALID_FILE_ATTRIBUTES)
382218885Sdim    // There's no sane way to report this :(.
383218885Sdim    assert(0 && "GetFileAttributes returned INVALID_FILE_ATTRIBUTES");
384218885Sdim
385218885Sdim  // This isn't exactly what defines a NTFS symlink, but it is only true for
386218885Sdim  // paths that act like a symlink.
387218885Sdim  return attributes & FILE_ATTRIBUTE_REPARSE_POINT;
388218885Sdim}
389218885Sdim
390218885Sdimbool
391218885SdimPath::canRead() const {
392218885Sdim  // FIXME: take security attributes into account.
393218885Sdim  DWORD attr = GetFileAttributes(path.c_str());
394218885Sdim  return attr != INVALID_FILE_ATTRIBUTES;
395218885Sdim}
396218885Sdim
397218885Sdimbool
398218885SdimPath::canWrite() const {
399218885Sdim  // FIXME: take security attributes into account.
400218885Sdim  DWORD attr = GetFileAttributes(path.c_str());
401218885Sdim  return (attr != INVALID_FILE_ATTRIBUTES) && !(attr & FILE_ATTRIBUTE_READONLY);
402218885Sdim}
403218885Sdim
404218885Sdimbool
405218885SdimPath::canExecute() const {
406218885Sdim  // FIXME: take security attributes into account.
407218885Sdim  DWORD attr = GetFileAttributes(path.c_str());
408218885Sdim  return attr != INVALID_FILE_ATTRIBUTES;
409218885Sdim}
410218885Sdim
411218885Sdimbool
412218885SdimPath::isRegularFile() const {
413218885Sdim  bool res;
414218885Sdim  if (fs::is_regular_file(path, res))
415218885Sdim    return false;
416218885Sdim  return res;
417218885Sdim}
418218885Sdim
419218885SdimStringRef
420218885SdimPath::getLast() const {
421218885Sdim  // Find the last slash
422218885Sdim  size_t pos = path.rfind('/');
423218885Sdim
424218885Sdim  // Handle the corner cases
425218885Sdim  if (pos == std::string::npos)
426218885Sdim    return path;
427218885Sdim
428218885Sdim  // If the last character is a slash, we have a root directory
429218885Sdim  if (pos == path.length()-1)
430218885Sdim    return path;
431218885Sdim
432218885Sdim  // Return everything after the last slash
433218885Sdim  return StringRef(path).substr(pos+1);
434218885Sdim}
435218885Sdim
436218885Sdimconst FileStatus *
437218885SdimPathWithStatus::getFileStatus(bool update, std::string *ErrStr) const {
438218885Sdim  if (!fsIsValid || update) {
439218885Sdim    WIN32_FILE_ATTRIBUTE_DATA fi;
440218885Sdim    if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi)) {
441218885Sdim      MakeErrMsg(ErrStr, "getStatusInfo():" + std::string(path) +
442218885Sdim                      ": Can't get status: ");
443218885Sdim      return 0;
444218885Sdim    }
445218885Sdim
446218885Sdim    status.fileSize = fi.nFileSizeHigh;
447218885Sdim    status.fileSize <<= sizeof(fi.nFileSizeHigh)*8;
448218885Sdim    status.fileSize += fi.nFileSizeLow;
449218885Sdim
450218885Sdim    status.mode = fi.dwFileAttributes & FILE_ATTRIBUTE_READONLY ? 0555 : 0777;
451218885Sdim    status.user = 9999;    // Not applicable to Windows, so...
452218885Sdim    status.group = 9999;   // Not applicable to Windows, so...
453218885Sdim
454218885Sdim    // FIXME: this is only unique if the file is accessed by the same file path.
455218885Sdim    // How do we do this for C:\dir\file and ..\dir\file ? Unix has inode
456218885Sdim    // numbers, but the concept doesn't exist in Windows.
457218885Sdim    status.uniqueID = 0;
458218885Sdim    for (unsigned i = 0; i < path.length(); ++i)
459218885Sdim      status.uniqueID += path[i];
460218885Sdim
461218885Sdim    ULARGE_INTEGER ui;
462218885Sdim    ui.LowPart = fi.ftLastWriteTime.dwLowDateTime;
463218885Sdim    ui.HighPart = fi.ftLastWriteTime.dwHighDateTime;
464218885Sdim    status.modTime.fromWin32Time(ui.QuadPart);
465218885Sdim
466218885Sdim    status.isDir = fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
467218885Sdim    fsIsValid = true;
468218885Sdim  }
469218885Sdim  return &status;
470218885Sdim}
471218885Sdim
472218885Sdimbool Path::makeReadableOnDisk(std::string* ErrMsg) {
473218885Sdim  // All files are readable on Windows (ignoring security attributes).
474218885Sdim  return false;
475218885Sdim}
476218885Sdim
477218885Sdimbool Path::makeWriteableOnDisk(std::string* ErrMsg) {
478218885Sdim  DWORD attr = GetFileAttributes(path.c_str());
479218885Sdim
480218885Sdim  // If it doesn't exist, we're done.
481218885Sdim  if (attr == INVALID_FILE_ATTRIBUTES)
482218885Sdim    return false;
483218885Sdim
484218885Sdim  if (attr & FILE_ATTRIBUTE_READONLY) {
485218885Sdim    if (!SetFileAttributes(path.c_str(), attr & ~FILE_ATTRIBUTE_READONLY)) {
486218885Sdim      MakeErrMsg(ErrMsg, std::string(path) + ": Can't make file writable: ");
487218885Sdim      return true;
488218885Sdim    }
489218885Sdim  }
490218885Sdim  return false;
491218885Sdim}
492218885Sdim
493218885Sdimbool Path::makeExecutableOnDisk(std::string* ErrMsg) {
494218885Sdim  // All files are executable on Windows (ignoring security attributes).
495218885Sdim  return false;
496218885Sdim}
497218885Sdim
498218885Sdimbool
499218885SdimPath::getDirectoryContents(std::set<Path>& result, std::string* ErrMsg) const {
500218885Sdim  WIN32_FILE_ATTRIBUTE_DATA fi;
501218885Sdim  if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi)) {
502218885Sdim    MakeErrMsg(ErrMsg, path + ": can't get status of file");
503218885Sdim    return true;
504218885Sdim  }
505218885Sdim
506218885Sdim  if (!(fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
507218885Sdim    if (ErrMsg)
508218885Sdim      *ErrMsg = path + ": not a directory";
509218885Sdim    return true;
510218885Sdim  }
511218885Sdim
512218885Sdim  result.clear();
513218885Sdim  WIN32_FIND_DATA fd;
514218885Sdim  std::string searchpath = path;
515218885Sdim  if (path.size() == 0 || searchpath[path.size()-1] == '/')
516218885Sdim    searchpath += "*";
517218885Sdim  else
518218885Sdim    searchpath += "/*";
519218885Sdim
520218885Sdim  HANDLE h = FindFirstFile(searchpath.c_str(), &fd);
521218885Sdim  if (h == INVALID_HANDLE_VALUE) {
522218885Sdim    if (GetLastError() == ERROR_FILE_NOT_FOUND)
523218885Sdim      return true; // not really an error, now is it?
524218885Sdim    MakeErrMsg(ErrMsg, path + ": Can't read directory: ");
525218885Sdim    return true;
526218885Sdim  }
527218885Sdim
528218885Sdim  do {
529218885Sdim    if (fd.cFileName[0] == '.')
530218885Sdim      continue;
531218885Sdim    Path aPath(path);
532218885Sdim    aPath.appendComponent(&fd.cFileName[0]);
533218885Sdim    result.insert(aPath);
534218885Sdim  } while (FindNextFile(h, &fd));
535218885Sdim
536218885Sdim  DWORD err = GetLastError();
537218885Sdim  FindClose(h);
538218885Sdim  if (err != ERROR_NO_MORE_FILES) {
539218885Sdim    SetLastError(err);
540218885Sdim    MakeErrMsg(ErrMsg, path + ": Can't read directory: ");
541218885Sdim    return true;
542218885Sdim  }
543218885Sdim  return false;
544218885Sdim}
545218885Sdim
546218885Sdimbool
547218885SdimPath::set(StringRef a_path) {
548218885Sdim  if (a_path.empty())
549218885Sdim    return false;
550218885Sdim  std::string save(path);
551218885Sdim  path = a_path;
552218885Sdim  FlipBackSlashes(path);
553218885Sdim  if (!isValid()) {
554218885Sdim    path = save;
555218885Sdim    return false;
556218885Sdim  }
557218885Sdim  return true;
558218885Sdim}
559218885Sdim
560218885Sdimbool
561218885SdimPath::appendComponent(StringRef name) {
562218885Sdim  if (name.empty())
563218885Sdim    return false;
564218885Sdim  std::string save(path);
565218885Sdim  if (!path.empty()) {
566218885Sdim    size_t last = path.size() - 1;
567218885Sdim    if (path[last] != '/')
568218885Sdim      path += '/';
569218885Sdim  }
570218885Sdim  path += name;
571218885Sdim  if (!isValid()) {
572218885Sdim    path = save;
573218885Sdim    return false;
574218885Sdim  }
575218885Sdim  return true;
576218885Sdim}
577218885Sdim
578218885Sdimbool
579218885SdimPath::eraseComponent() {
580218885Sdim  size_t slashpos = path.rfind('/',path.size());
581218885Sdim  if (slashpos == path.size() - 1 || slashpos == std::string::npos)
582218885Sdim    return false;
583218885Sdim  std::string save(path);
584218885Sdim  path.erase(slashpos);
585218885Sdim  if (!isValid()) {
586218885Sdim    path = save;
587218885Sdim    return false;
588218885Sdim  }
589218885Sdim  return true;
590218885Sdim}
591218885Sdim
592218885Sdimbool
593218885SdimPath::eraseSuffix() {
594218885Sdim  size_t dotpos = path.rfind('.',path.size());
595218885Sdim  size_t slashpos = path.rfind('/',path.size());
596218885Sdim  if (dotpos != std::string::npos) {
597218885Sdim    if (slashpos == std::string::npos || dotpos > slashpos+1) {
598218885Sdim      std::string save(path);
599218885Sdim      path.erase(dotpos, path.size()-dotpos);
600218885Sdim      if (!isValid()) {
601218885Sdim        path = save;
602218885Sdim        return false;
603218885Sdim      }
604218885Sdim      return true;
605218885Sdim    }
606218885Sdim  }
607218885Sdim  return false;
608218885Sdim}
609218885Sdim
610218885Sdiminline bool PathMsg(std::string* ErrMsg, const char* pathname, const char*msg) {
611218885Sdim  if (ErrMsg)
612218885Sdim    *ErrMsg = std::string(pathname) + ": " + std::string(msg);
613218885Sdim  return true;
614218885Sdim}
615218885Sdim
616218885Sdimbool
617218885SdimPath::createDirectoryOnDisk(bool create_parents, std::string* ErrMsg) {
618218885Sdim  // Get a writeable copy of the path name
619218885Sdim  size_t len = path.length();
620218885Sdim  char *pathname = reinterpret_cast<char *>(_alloca(len+2));
621218885Sdim  path.copy(pathname, len);
622218885Sdim  pathname[len] = 0;
623218885Sdim
624218885Sdim  // Make sure it ends with a slash.
625218885Sdim  if (len == 0 || pathname[len - 1] != '/') {
626218885Sdim    pathname[len] = '/';
627218885Sdim    pathname[++len] = 0;
628218885Sdim  }
629218885Sdim
630218885Sdim  // Determine starting point for initial / search.
631218885Sdim  char *next = pathname;
632218885Sdim  if (pathname[0] == '/' && pathname[1] == '/') {
633218885Sdim    // Skip host name.
634218885Sdim    next = strchr(pathname+2, '/');
635218885Sdim    if (next == NULL)
636218885Sdim      return PathMsg(ErrMsg, pathname, "badly formed remote directory");
637218885Sdim
638218885Sdim    // Skip share name.
639218885Sdim    next = strchr(next+1, '/');
640218885Sdim    if (next == NULL)
641218885Sdim      return PathMsg(ErrMsg, pathname,"badly formed remote directory");
642218885Sdim
643218885Sdim    next++;
644218885Sdim    if (*next == 0)
645218885Sdim      return PathMsg(ErrMsg, pathname, "badly formed remote directory");
646218885Sdim
647218885Sdim  } else {
648218885Sdim    if (pathname[1] == ':')
649218885Sdim      next += 2;    // skip drive letter
650218885Sdim    if (*next == '/')
651218885Sdim      next++;       // skip root directory
652218885Sdim  }
653218885Sdim
654218885Sdim  // If we're supposed to create intermediate directories
655218885Sdim  if (create_parents) {
656218885Sdim    // Loop through the directory components until we're done
657218885Sdim    while (*next) {
658218885Sdim      next = strchr(next, '/');
659218885Sdim      *next = 0;
660218885Sdim      if (!CreateDirectory(pathname, NULL) &&
661218885Sdim          GetLastError() != ERROR_ALREADY_EXISTS)
662218885Sdim          return MakeErrMsg(ErrMsg,
663218885Sdim            std::string(pathname) + ": Can't create directory: ");
664218885Sdim      *next++ = '/';
665218885Sdim    }
666218885Sdim  } else {
667218885Sdim    // Drop trailing slash.
668218885Sdim    pathname[len-1] = 0;
669218885Sdim    if (!CreateDirectory(pathname, NULL) &&
670218885Sdim        GetLastError() != ERROR_ALREADY_EXISTS) {
671218885Sdim      return MakeErrMsg(ErrMsg, std::string(pathname) +
672218885Sdim                        ": Can't create directory: ");
673218885Sdim    }
674218885Sdim  }
675218885Sdim  return false;
676218885Sdim}
677218885Sdim
678218885Sdimbool
679218885SdimPath::createFileOnDisk(std::string* ErrMsg) {
680218885Sdim  // Create the file
681218885Sdim  HANDLE h = CreateFile(path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_NEW,
682218885Sdim                        FILE_ATTRIBUTE_NORMAL, NULL);
683218885Sdim  if (h == INVALID_HANDLE_VALUE)
684218885Sdim    return MakeErrMsg(ErrMsg, path + ": Can't create file: ");
685218885Sdim
686218885Sdim  CloseHandle(h);
687218885Sdim  return false;
688218885Sdim}
689218885Sdim
690218885Sdimbool
691218885SdimPath::eraseFromDisk(bool remove_contents, std::string *ErrStr) const {
692218885Sdim  WIN32_FILE_ATTRIBUTE_DATA fi;
693218885Sdim  if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi))
694218885Sdim    return true;
695218885Sdim
696218885Sdim  if (fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
697218885Sdim    // If it doesn't exist, we're done.
698218885Sdim    bool Exists;
699218885Sdim    if (fs::exists(path, Exists) || !Exists)
700218885Sdim      return false;
701218885Sdim
702218885Sdim    char *pathname = reinterpret_cast<char *>(_alloca(path.length()+3));
703218885Sdim    int lastchar = path.length() - 1 ;
704218885Sdim    path.copy(pathname, lastchar+1);
705218885Sdim
706218885Sdim    // Make path end with '/*'.
707218885Sdim    if (pathname[lastchar] != '/')
708218885Sdim      pathname[++lastchar] = '/';
709218885Sdim    pathname[lastchar+1] = '*';
710218885Sdim    pathname[lastchar+2] = 0;
711218885Sdim
712218885Sdim    if (remove_contents) {
713218885Sdim      WIN32_FIND_DATA fd;
714218885Sdim      HANDLE h = FindFirstFile(pathname, &fd);
715218885Sdim
716218885Sdim      // It's a bad idea to alter the contents of a directory while enumerating
717218885Sdim      // its contents. So build a list of its contents first, then destroy them.
718218885Sdim
719218885Sdim      if (h != INVALID_HANDLE_VALUE) {
720218885Sdim        std::vector<Path> list;
721218885Sdim
722218885Sdim        do {
723218885Sdim          if (strcmp(fd.cFileName, ".") == 0)
724218885Sdim            continue;
725218885Sdim          if (strcmp(fd.cFileName, "..") == 0)
726218885Sdim            continue;
727218885Sdim
728218885Sdim          Path aPath(path);
729218885Sdim          aPath.appendComponent(&fd.cFileName[0]);
730218885Sdim          list.push_back(aPath);
731218885Sdim        } while (FindNextFile(h, &fd));
732218885Sdim
733218885Sdim        DWORD err = GetLastError();
734218885Sdim        FindClose(h);
735218885Sdim        if (err != ERROR_NO_MORE_FILES) {
736218885Sdim          SetLastError(err);
737218885Sdim          return MakeErrMsg(ErrStr, path + ": Can't read directory: ");
738218885Sdim        }
739218885Sdim
740218885Sdim        for (std::vector<Path>::iterator I = list.begin(); I != list.end();
741218885Sdim             ++I) {
742218885Sdim          Path &aPath = *I;
743218885Sdim          aPath.eraseFromDisk(true);
744218885Sdim        }
745218885Sdim      } else {
746218885Sdim        if (GetLastError() != ERROR_FILE_NOT_FOUND)
747218885Sdim          return MakeErrMsg(ErrStr, path + ": Can't read directory: ");
748218885Sdim      }
749218885Sdim    }
750218885Sdim
751218885Sdim    pathname[lastchar] = 0;
752218885Sdim    if (!RemoveDirectory(pathname))
753218885Sdim      return MakeErrMsg(ErrStr,
754218885Sdim        std::string(pathname) + ": Can't destroy directory: ");
755218885Sdim    return false;
756218885Sdim  } else {
757218885Sdim    // Read-only files cannot be deleted on Windows.  Must remove the read-only
758218885Sdim    // attribute first.
759218885Sdim    if (fi.dwFileAttributes & FILE_ATTRIBUTE_READONLY) {
760218885Sdim      if (!SetFileAttributes(path.c_str(),
761218885Sdim                             fi.dwFileAttributes & ~FILE_ATTRIBUTE_READONLY))
762218885Sdim        return MakeErrMsg(ErrStr, path + ": Can't destroy file: ");
763218885Sdim    }
764218885Sdim
765218885Sdim    if (!DeleteFile(path.c_str()))
766218885Sdim      return MakeErrMsg(ErrStr, path + ": Can't destroy file: ");
767218885Sdim    return false;
768218885Sdim  }
769218885Sdim}
770218885Sdim
771218885Sdimbool Path::getMagicNumber(std::string& Magic, unsigned len) const {
772218885Sdim  assert(len < 1024 && "Request for magic string too long");
773218885Sdim  char* buf = reinterpret_cast<char*>(alloca(len));
774218885Sdim
775218885Sdim  HANDLE h = CreateFile(path.c_str(),
776218885Sdim                        GENERIC_READ,
777218885Sdim                        FILE_SHARE_READ,
778218885Sdim                        NULL,
779218885Sdim                        OPEN_EXISTING,
780218885Sdim                        FILE_ATTRIBUTE_NORMAL,
781218885Sdim                        NULL);
782218885Sdim  if (h == INVALID_HANDLE_VALUE)
783218885Sdim    return false;
784218885Sdim
785218885Sdim  DWORD nRead = 0;
786218885Sdim  BOOL ret = ReadFile(h, buf, len, &nRead, NULL);
787218885Sdim  CloseHandle(h);
788218885Sdim
789218885Sdim  if (!ret || nRead != len)
790218885Sdim    return false;
791218885Sdim
792218885Sdim  Magic = std::string(buf, len);
793218885Sdim  return true;
794218885Sdim}
795218885Sdim
796218885Sdimbool
797218885SdimPath::renamePathOnDisk(const Path& newName, std::string* ErrMsg) {
798218885Sdim  if (!MoveFileEx(path.c_str(), newName.c_str(), MOVEFILE_REPLACE_EXISTING))
799218885Sdim    return MakeErrMsg(ErrMsg, "Can't move '" + path + "' to '" + newName.path
800218885Sdim        + "': ");
801218885Sdim  return false;
802218885Sdim}
803218885Sdim
804218885Sdimbool
805218885SdimPath::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrMsg) const {
806218885Sdim  // FIXME: should work on directories also.
807218885Sdim  if (!si.isFile) {
808218885Sdim    return true;
809218885Sdim  }
810218885Sdim
811218885Sdim  HANDLE h = CreateFile(path.c_str(),
812218885Sdim                        FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES,
813218885Sdim                        FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
814218885Sdim                        NULL,
815218885Sdim                        OPEN_EXISTING,
816218885Sdim                        FILE_ATTRIBUTE_NORMAL,
817218885Sdim                        NULL);
818218885Sdim  if (h == INVALID_HANDLE_VALUE)
819218885Sdim    return true;
820218885Sdim
821218885Sdim  BY_HANDLE_FILE_INFORMATION bhfi;
822218885Sdim  if (!GetFileInformationByHandle(h, &bhfi)) {
823218885Sdim    DWORD err = GetLastError();
824218885Sdim    CloseHandle(h);
825218885Sdim    SetLastError(err);
826218885Sdim    return MakeErrMsg(ErrMsg, path + ": GetFileInformationByHandle: ");
827218885Sdim  }
828218885Sdim
829218885Sdim  ULARGE_INTEGER ui;
830218885Sdim  ui.QuadPart = si.modTime.toWin32Time();
831218885Sdim  FILETIME ft;
832218885Sdim  ft.dwLowDateTime = ui.LowPart;
833218885Sdim  ft.dwHighDateTime = ui.HighPart;
834218885Sdim  BOOL ret = SetFileTime(h, NULL, &ft, &ft);
835218885Sdim  DWORD err = GetLastError();
836218885Sdim  CloseHandle(h);
837218885Sdim  if (!ret) {
838218885Sdim    SetLastError(err);
839218885Sdim    return MakeErrMsg(ErrMsg, path + ": SetFileTime: ");
840218885Sdim  }
841218885Sdim
842218885Sdim  // Best we can do with Unix permission bits is to interpret the owner
843218885Sdim  // writable bit.
844218885Sdim  if (si.mode & 0200) {
845218885Sdim    if (bhfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY) {
846218885Sdim      if (!SetFileAttributes(path.c_str(),
847218885Sdim              bhfi.dwFileAttributes & ~FILE_ATTRIBUTE_READONLY))
848218885Sdim        return MakeErrMsg(ErrMsg, path + ": SetFileAttributes: ");
849218885Sdim    }
850218885Sdim  } else {
851218885Sdim    if (!(bhfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY)) {
852218885Sdim      if (!SetFileAttributes(path.c_str(),
853218885Sdim              bhfi.dwFileAttributes | FILE_ATTRIBUTE_READONLY))
854218885Sdim        return MakeErrMsg(ErrMsg, path + ": SetFileAttributes: ");
855218885Sdim    }
856218885Sdim  }
857218885Sdim
858218885Sdim  return false;
859218885Sdim}
860218885Sdim
861218885Sdimbool
862218885SdimCopyFile(const sys::Path &Dest, const sys::Path &Src, std::string* ErrMsg) {
863218885Sdim  // Can't use CopyFile macro defined in Windows.h because it would mess up the
864218885Sdim  // above line.  We use the expansion it would have in a non-UNICODE build.
865218885Sdim  if (!::CopyFileA(Src.c_str(), Dest.c_str(), false))
866218885Sdim    return MakeErrMsg(ErrMsg, "Can't copy '" + Src.str() +
867218885Sdim               "' to '" + Dest.str() + "': ");
868218885Sdim  return false;
869218885Sdim}
870218885Sdim
871218885Sdimbool
872218885SdimPath::makeUnique(bool reuse_current, std::string* ErrMsg) {
873218885Sdim  bool Exists;
874218885Sdim  if (reuse_current && (fs::exists(path, Exists) || !Exists))
875218885Sdim    return false; // File doesn't exist already, just use it!
876218885Sdim
877218885Sdim  // Reserve space for -XXXXXX at the end.
878218885Sdim  char *FNBuffer = (char*) alloca(path.size()+8);
879218885Sdim  unsigned offset = path.size();
880218885Sdim  path.copy(FNBuffer, offset);
881218885Sdim
882218885Sdim  // Find a numeric suffix that isn't used by an existing file.  Assume there
883218885Sdim  // won't be more than 1 million files with the same prefix.  Probably a safe
884218885Sdim  // bet.
885218885Sdim  static unsigned FCounter = 0;
886218885Sdim  do {
887218885Sdim    sprintf(FNBuffer+offset, "-%06u", FCounter);
888218885Sdim    if (++FCounter > 999999)
889218885Sdim      FCounter = 0;
890218885Sdim    path = FNBuffer;
891218885Sdim  } while (!fs::exists(path, Exists) && Exists);
892218885Sdim  return false;
893218885Sdim}
894218885Sdim
895218885Sdimbool
896218885SdimPath::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) {
897218885Sdim  // Make this into a unique file name
898218885Sdim  makeUnique(reuse_current, ErrMsg);
899218885Sdim
900218885Sdim  // Now go and create it
901218885Sdim  HANDLE h = CreateFile(path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_NEW,
902218885Sdim                        FILE_ATTRIBUTE_NORMAL, NULL);
903218885Sdim  if (h == INVALID_HANDLE_VALUE)
904218885Sdim    return MakeErrMsg(ErrMsg, path + ": can't create file");
905218885Sdim
906218885Sdim  CloseHandle(h);
907218885Sdim  return false;
908218885Sdim}
909218885Sdim
910218885Sdim/// MapInFilePages - Not yet implemented on win32.
911218885Sdimconst char *Path::MapInFilePages(int FD, uint64_t FileSize) {
912218885Sdim  return 0;
913218885Sdim}
914218885Sdim
915218885Sdim/// MapInFilePages - Not yet implemented on win32.
916218885Sdimvoid Path::UnMapFilePages(const char *Base, uint64_t FileSize) {
917218885Sdim  assert(0 && "NOT IMPLEMENTED");
918218885Sdim}
919218885Sdim
920218885Sdim}
921218885Sdim}
922