Ninja
disk_interface.cc
Go to the documentation of this file.
1 // Copyright 2011 Google Inc. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include "disk_interface.h"
16 
17 #include <algorithm>
18 
19 #include <errno.h>
20 #include <stdio.h>
21 #include <string.h>
22 #include <sys/stat.h>
23 #include <sys/types.h>
24 
25 #ifdef _WIN32
26 #include <windows.h>
27 #include <direct.h> // _mkdir
28 #endif
29 
30 #include "util.h"
31 
32 namespace {
33 
34 string DirName(const string& path) {
35 #ifdef _WIN32
36  const char kPathSeparators[] = "\\/";
37 #else
38  const char kPathSeparators[] = "/";
39 #endif
40  string::size_type slash_pos = path.find_last_of(kPathSeparators);
41  if (slash_pos == string::npos)
42  return string(); // Nothing to do.
43  const char* const kEnd = kPathSeparators + strlen(kPathSeparators);
44  while (slash_pos > 0 &&
45  std::find(kPathSeparators, kEnd, path[slash_pos - 1]) != kEnd)
46  --slash_pos;
47  return path.substr(0, slash_pos);
48 }
49 
50 int MakeDir(const string& path) {
51 #ifdef _WIN32
52  return _mkdir(path.c_str());
53 #else
54  return mkdir(path.c_str(), 0777);
55 #endif
56 }
57 
58 #ifdef _WIN32
59 TimeStamp TimeStampFromFileTime(const FILETIME& filetime) {
60  // FILETIME is in 100-nanosecond increments since the Windows epoch.
61  // We don't much care about epoch correctness but we do want the
62  // resulting value to fit in an integer.
63  uint64_t mtime = ((uint64_t)filetime.dwHighDateTime << 32) |
64  ((uint64_t)filetime.dwLowDateTime);
65  mtime /= 1000000000LL / 100; // 100ns -> s.
66  mtime -= 12622770400LL; // 1600 epoch -> 2000 epoch (subtract 400 years).
67  return (TimeStamp)mtime;
68 }
69 
70 TimeStamp StatSingleFile(const string& path, bool quiet) {
71  WIN32_FILE_ATTRIBUTE_DATA attrs;
72  if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &attrs)) {
73  DWORD err = GetLastError();
74  if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND)
75  return 0;
76  if (!quiet) {
77  Error("GetFileAttributesEx(%s): %s", path.c_str(),
78  GetLastErrorString().c_str());
79  }
80  return -1;
81  }
82  return TimeStampFromFileTime(attrs.ftLastWriteTime);
83 }
84 
85 #pragma warning(push)
86 #pragma warning(disable: 4996) // GetVersionExA is deprecated post SDK 8.1.
87 bool IsWindows7OrLater() {
88  OSVERSIONINFO version_info = { sizeof(version_info) };
89  if (!GetVersionEx(&version_info))
90  Fatal("GetVersionEx: %s", GetLastErrorString().c_str());
91  return version_info.dwMajorVersion > 6 ||
92  version_info.dwMajorVersion == 6 && version_info.dwMinorVersion >= 1;
93 }
94 #pragma warning(pop)
95 
96 bool StatAllFilesInDir(const string& dir, map<string, TimeStamp>* stamps,
97  bool quiet) {
98  // FindExInfoBasic is 30% faster than FindExInfoStandard.
99  static bool can_use_basic_info = IsWindows7OrLater();
100  // This is not in earlier SDKs.
101  const FINDEX_INFO_LEVELS kFindExInfoBasic =
102  static_cast<FINDEX_INFO_LEVELS>(1);
103  FINDEX_INFO_LEVELS level =
104  can_use_basic_info ? kFindExInfoBasic : FindExInfoStandard;
105  WIN32_FIND_DATAA ffd;
106  HANDLE find_handle = FindFirstFileExA((dir + "\\*").c_str(), level, &ffd,
107  FindExSearchNameMatch, NULL, 0);
108 
109  if (find_handle == INVALID_HANDLE_VALUE) {
110  DWORD err = GetLastError();
111  if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND)
112  return true;
113  if (!quiet) {
114  Error("FindFirstFileExA(%s): %s", dir.c_str(),
115  GetLastErrorString().c_str());
116  }
117  return false;
118  }
119  do {
120  string lowername = ffd.cFileName;
121  transform(lowername.begin(), lowername.end(), lowername.begin(), ::tolower);
122  stamps->insert(make_pair(lowername,
123  TimeStampFromFileTime(ffd.ftLastWriteTime)));
124  } while (FindNextFileA(find_handle, &ffd));
125  FindClose(find_handle);
126  return true;
127 }
128 #endif // _WIN32
129 
130 } // namespace
131 
132 // DiskInterface ---------------------------------------------------------------
133 
134 bool DiskInterface::MakeDirs(const string& path) {
135  string dir = DirName(path);
136  if (dir.empty())
137  return true; // Reached root; assume it's there.
138  TimeStamp mtime = Stat(dir);
139  if (mtime < 0)
140  return false; // Error.
141  if (mtime > 0)
142  return true; // Exists already; we're done.
143 
144  // Directory doesn't exist. Try creating its parent first.
145  bool success = MakeDirs(dir);
146  if (!success)
147  return false;
148  return MakeDir(dir);
149 }
150 
151 // RealDiskInterface -----------------------------------------------------------
152 
153 TimeStamp RealDiskInterface::Stat(const string& path) const {
154 #ifdef _WIN32
155  // MSDN: "Naming Files, Paths, and Namespaces"
156  // http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx
157  if (!path.empty() && path[0] != '\\' && path.size() > MAX_PATH) {
158  if (!quiet_) {
159  Error("Stat(%s): Filename longer than %i characters",
160  path.c_str(), MAX_PATH);
161  }
162  return -1;
163  }
164  if (!use_cache_)
165  return StatSingleFile(path, quiet_);
166 
167  string dir = DirName(path);
168  string base(path.substr(dir.size() ? dir.size() + 1 : 0));
169 
170  transform(dir.begin(), dir.end(), dir.begin(), ::tolower);
171  transform(base.begin(), base.end(), base.begin(), ::tolower);
172 
173  Cache::iterator ci = cache_.find(dir);
174  if (ci == cache_.end()) {
175  ci = cache_.insert(make_pair(dir, DirCache())).first;
176  if (!StatAllFilesInDir(dir.empty() ? "." : dir, &ci->second, quiet_)) {
177  cache_.erase(ci);
178  return -1;
179  }
180  }
181  DirCache::iterator di = ci->second.find(base);
182  return di != ci->second.end() ? di->second : 0;
183 #else
184  struct stat st;
185  if (stat(path.c_str(), &st) < 0) {
186  if (errno == ENOENT || errno == ENOTDIR)
187  return 0;
188  if (!quiet_) {
189  Error("stat(%s): %s", path.c_str(), strerror(errno));
190  }
191  return -1;
192  }
193  return st.st_mtime;
194 #endif
195 }
196 
197 bool RealDiskInterface::WriteFile(const string& path, const string& contents) {
198  FILE* fp = fopen(path.c_str(), "w");
199  if (fp == NULL) {
200  Error("WriteFile(%s): Unable to create file. %s",
201  path.c_str(), strerror(errno));
202  return false;
203  }
204 
205  if (fwrite(contents.data(), 1, contents.length(), fp) < contents.length()) {
206  Error("WriteFile(%s): Unable to write to the file. %s",
207  path.c_str(), strerror(errno));
208  fclose(fp);
209  return false;
210  }
211 
212  if (fclose(fp) == EOF) {
213  Error("WriteFile(%s): Unable to close the file. %s",
214  path.c_str(), strerror(errno));
215  return false;
216  }
217 
218  return true;
219 }
220 
221 bool RealDiskInterface::MakeDir(const string& path) {
222  if (::MakeDir(path) < 0) {
223  if (errno == EEXIST) {
224  return true;
225  }
226  Error("mkdir(%s): %s", path.c_str(), strerror(errno));
227  return false;
228  }
229  return true;
230 }
231 
232 string RealDiskInterface::ReadFile(const string& path, string* err) {
233  string contents;
234  int ret = ::ReadFile(path, &contents, err);
235  if (ret == -ENOENT) {
236  // Swallow ENOENT.
237  err->clear();
238  }
239  return contents;
240 }
241 
242 int RealDiskInterface::RemoveFile(const string& path) {
243  if (remove(path.c_str()) < 0) {
244  switch (errno) {
245  case ENOENT:
246  return 1;
247  default:
248  Error("remove(%s): %s", path.c_str(), strerror(errno));
249  return -1;
250  }
251  } else {
252  return 0;
253  }
254 }
255 
257 #ifdef _WIN32
258  use_cache_ = allow;
259  if (!use_cache_)
260  cache_.clear();
261 #endif
262 }
virtual string ReadFile(const string &path, string *err)
Read a file to a string. Fill in |err| on error.
bool MakeDirs(const string &path)
Create all the parent directories for path; like mkdir -p basename path.
int TimeStamp
Definition: timestamp.h:22
IN IN HANDLE
virtual bool WriteFile(const string &path, const string &contents)
Create a file, with the specified name and contents Returns true on success, false on failure...
virtual TimeStamp Stat(const string &path) const
stat() a file, returning the mtime, or 0 if missing and -1 on other errors.
virtual bool MakeDir(const string &path)
Create a directory, returning false on failure.
int ReadFile(const string &path, string *contents, string *err)
Read a file to a string (in text mode: with CRLF conversion on Windows).
Definition: util.cc:282
virtual int RemoveFile(const string &path)
Remove the file named path.
void Fatal(const char *msg,...)
Log a fatal message and exit.
Definition: util.cc:52
void AllowStatCache(bool allow)
Whether stat information can be cached. Only has an effect on Windows.
unsigned long long uint64_t
Definition: win32port.h:22
IN DWORD
void Error(const char *msg,...)
Log an error message.
Definition: util.cc:79