Update .DEPS.git
[chromium-blink-merge.git] / base / file_util_win.cc
blobc5b2711d9c3e5860a649d810834fa8f2c9ba3bf3
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "base/file_util.h"
7 #include <windows.h>
8 #include <psapi.h>
9 #include <shellapi.h>
10 #include <shlobj.h>
11 #include <time.h>
13 #include <limits>
14 #include <string>
16 #include "base/file_path.h"
17 #include "base/logging.h"
18 #include "base/metrics/histogram.h"
19 #include "base/process_util.h"
20 #include "base/string_number_conversions.h"
21 #include "base/string_util.h"
22 #include "base/threading/thread_restrictions.h"
23 #include "base/time.h"
24 #include "base/utf_string_conversions.h"
25 #include "base/win/scoped_handle.h"
26 #include "base/win/windows_version.h"
28 namespace file_util {
30 namespace {
32 const DWORD kFileShareAll =
33 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
35 } // namespace
37 bool AbsolutePath(FilePath* path) {
38 base::ThreadRestrictions::AssertIOAllowed();
39 wchar_t file_path_buf[MAX_PATH];
40 if (!_wfullpath(file_path_buf, path->value().c_str(), MAX_PATH))
41 return false;
42 *path = FilePath(file_path_buf);
43 return true;
46 int CountFilesCreatedAfter(const FilePath& path,
47 const base::Time& comparison_time) {
48 base::ThreadRestrictions::AssertIOAllowed();
50 int file_count = 0;
51 FILETIME comparison_filetime(comparison_time.ToFileTime());
53 WIN32_FIND_DATA find_file_data;
54 // All files in given dir
55 std::wstring filename_spec = path.Append(L"*").value();
56 HANDLE find_handle = FindFirstFile(filename_spec.c_str(), &find_file_data);
57 if (find_handle != INVALID_HANDLE_VALUE) {
58 do {
59 // Don't count current or parent directories.
60 if ((wcscmp(find_file_data.cFileName, L"..") == 0) ||
61 (wcscmp(find_file_data.cFileName, L".") == 0))
62 continue;
64 long result = CompareFileTime(&find_file_data.ftCreationTime, // NOLINT
65 &comparison_filetime);
66 // File was created after or on comparison time
67 if ((result == 1) || (result == 0))
68 ++file_count;
69 } while (FindNextFile(find_handle, &find_file_data));
70 FindClose(find_handle);
73 return file_count;
76 bool Delete(const FilePath& path, bool recursive) {
77 base::ThreadRestrictions::AssertIOAllowed();
79 if (path.value().length() >= MAX_PATH)
80 return false;
82 if (!recursive) {
83 // If not recursing, then first check to see if |path| is a directory.
84 // If it is, then remove it with RemoveDirectory.
85 base::PlatformFileInfo file_info;
86 if (GetFileInfo(path, &file_info) && file_info.is_directory)
87 return RemoveDirectory(path.value().c_str()) != 0;
89 // Otherwise, it's a file, wildcard or non-existant. Try DeleteFile first
90 // because it should be faster. If DeleteFile fails, then we fall through
91 // to SHFileOperation, which will do the right thing.
92 if (DeleteFile(path.value().c_str()) != 0)
93 return true;
96 // SHFILEOPSTRUCT wants the path to be terminated with two NULLs,
97 // so we have to use wcscpy because wcscpy_s writes non-NULLs
98 // into the rest of the buffer.
99 wchar_t double_terminated_path[MAX_PATH + 1] = {0};
100 #pragma warning(suppress:4996) // don't complain about wcscpy deprecation
101 if (g_bug108724_debug)
102 LOG(WARNING) << "copying ";
103 wcscpy(double_terminated_path, path.value().c_str());
105 SHFILEOPSTRUCT file_operation = {0};
106 file_operation.wFunc = FO_DELETE;
107 file_operation.pFrom = double_terminated_path;
108 file_operation.fFlags = FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMATION;
109 if (!recursive)
110 file_operation.fFlags |= FOF_NORECURSION | FOF_FILESONLY;
111 if (g_bug108724_debug)
112 LOG(WARNING) << "Performing shell operation";
113 int err = SHFileOperation(&file_operation);
114 if (g_bug108724_debug)
115 LOG(WARNING) << "Done: " << err;
117 // Since we're passing flags to the operation telling it to be silent,
118 // it's possible for the operation to be aborted/cancelled without err
119 // being set (although MSDN doesn't give any scenarios for how this can
120 // happen). See MSDN for SHFileOperation and SHFILEOPTSTRUCT.
121 if (file_operation.fAnyOperationsAborted)
122 return false;
124 // Some versions of Windows return ERROR_FILE_NOT_FOUND (0x2) when deleting
125 // an empty directory and some return 0x402 when they should be returning
126 // ERROR_FILE_NOT_FOUND. MSDN says Vista and up won't return 0x402.
127 return (err == 0 || err == ERROR_FILE_NOT_FOUND || err == 0x402);
130 bool DeleteAfterReboot(const FilePath& path) {
131 base::ThreadRestrictions::AssertIOAllowed();
133 if (path.value().length() >= MAX_PATH)
134 return false;
136 return MoveFileEx(path.value().c_str(), NULL,
137 MOVEFILE_DELAY_UNTIL_REBOOT |
138 MOVEFILE_REPLACE_EXISTING) != FALSE;
141 bool Move(const FilePath& from_path, const FilePath& to_path) {
142 base::ThreadRestrictions::AssertIOAllowed();
144 // NOTE: I suspect we could support longer paths, but that would involve
145 // analyzing all our usage of files.
146 if (from_path.value().length() >= MAX_PATH ||
147 to_path.value().length() >= MAX_PATH) {
148 return false;
150 if (MoveFileEx(from_path.value().c_str(), to_path.value().c_str(),
151 MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING) != 0)
152 return true;
154 // Keep the last error value from MoveFileEx around in case the below
155 // fails.
156 bool ret = false;
157 DWORD last_error = ::GetLastError();
159 if (DirectoryExists(from_path)) {
160 // MoveFileEx fails if moving directory across volumes. We will simulate
161 // the move by using Copy and Delete. Ideally we could check whether
162 // from_path and to_path are indeed in different volumes.
163 ret = CopyAndDeleteDirectory(from_path, to_path);
166 if (!ret) {
167 // Leave a clue about what went wrong so that it can be (at least) picked
168 // up by a PLOG entry.
169 ::SetLastError(last_error);
172 return ret;
175 bool ReplaceFile(const FilePath& from_path, const FilePath& to_path) {
176 base::ThreadRestrictions::AssertIOAllowed();
177 // Try a simple move first. It will only succeed when |to_path| doesn't
178 // already exist.
179 if (::MoveFile(from_path.value().c_str(), to_path.value().c_str()))
180 return true;
181 // Try the full-blown replace if the move fails, as ReplaceFile will only
182 // succeed when |to_path| does exist. When writing to a network share, we may
183 // not be able to change the ACLs. Ignore ACL errors then
184 // (REPLACEFILE_IGNORE_MERGE_ERRORS).
185 if (::ReplaceFile(to_path.value().c_str(), from_path.value().c_str(), NULL,
186 REPLACEFILE_IGNORE_MERGE_ERRORS, NULL, NULL)) {
187 return true;
189 return false;
192 bool CopyFile(const FilePath& from_path, const FilePath& to_path) {
193 base::ThreadRestrictions::AssertIOAllowed();
195 // NOTE: I suspect we could support longer paths, but that would involve
196 // analyzing all our usage of files.
197 if (from_path.value().length() >= MAX_PATH ||
198 to_path.value().length() >= MAX_PATH) {
199 return false;
201 return (::CopyFile(from_path.value().c_str(), to_path.value().c_str(),
202 false) != 0);
205 bool ShellCopy(const FilePath& from_path, const FilePath& to_path,
206 bool recursive) {
207 base::ThreadRestrictions::AssertIOAllowed();
209 // NOTE: I suspect we could support longer paths, but that would involve
210 // analyzing all our usage of files.
211 if (from_path.value().length() >= MAX_PATH ||
212 to_path.value().length() >= MAX_PATH) {
213 return false;
216 // SHFILEOPSTRUCT wants the path to be terminated with two NULLs,
217 // so we have to use wcscpy because wcscpy_s writes non-NULLs
218 // into the rest of the buffer.
219 wchar_t double_terminated_path_from[MAX_PATH + 1] = {0};
220 wchar_t double_terminated_path_to[MAX_PATH + 1] = {0};
221 #pragma warning(suppress:4996) // don't complain about wcscpy deprecation
222 wcscpy(double_terminated_path_from, from_path.value().c_str());
223 #pragma warning(suppress:4996) // don't complain about wcscpy deprecation
224 wcscpy(double_terminated_path_to, to_path.value().c_str());
226 SHFILEOPSTRUCT file_operation = {0};
227 file_operation.wFunc = FO_COPY;
228 file_operation.pFrom = double_terminated_path_from;
229 file_operation.pTo = double_terminated_path_to;
230 file_operation.fFlags = FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMATION |
231 FOF_NOCONFIRMMKDIR;
232 if (!recursive)
233 file_operation.fFlags |= FOF_NORECURSION | FOF_FILESONLY;
235 return (SHFileOperation(&file_operation) == 0);
238 bool CopyDirectory(const FilePath& from_path, const FilePath& to_path,
239 bool recursive) {
240 base::ThreadRestrictions::AssertIOAllowed();
242 if (recursive)
243 return ShellCopy(from_path, to_path, true);
245 // The following code assumes that from path is a directory.
246 DCHECK(DirectoryExists(from_path));
248 // Instead of creating a new directory, we copy the old one to include the
249 // security information of the folder as part of the copy.
250 if (!PathExists(to_path)) {
251 // Except that Vista fails to do that, and instead do a recursive copy if
252 // the target directory doesn't exist.
253 if (base::win::GetVersion() >= base::win::VERSION_VISTA)
254 CreateDirectory(to_path);
255 else
256 ShellCopy(from_path, to_path, false);
259 FilePath directory = from_path.Append(L"*.*");
260 return ShellCopy(directory, to_path, false);
263 bool CopyAndDeleteDirectory(const FilePath& from_path,
264 const FilePath& to_path) {
265 base::ThreadRestrictions::AssertIOAllowed();
266 if (CopyDirectory(from_path, to_path, true)) {
267 if (Delete(from_path, true)) {
268 return true;
270 // Like Move, this function is not transactional, so we just
271 // leave the copied bits behind if deleting from_path fails.
272 // If to_path exists previously then we have already overwritten
273 // it by now, we don't get better off by deleting the new bits.
275 return false;
279 bool PathExists(const FilePath& path) {
280 base::ThreadRestrictions::AssertIOAllowed();
281 return (GetFileAttributes(path.value().c_str()) != INVALID_FILE_ATTRIBUTES);
284 bool PathIsWritable(const FilePath& path) {
285 base::ThreadRestrictions::AssertIOAllowed();
286 HANDLE dir =
287 CreateFile(path.value().c_str(), FILE_ADD_FILE, kFileShareAll,
288 NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
290 if (dir == INVALID_HANDLE_VALUE)
291 return false;
293 CloseHandle(dir);
294 return true;
297 bool DirectoryExists(const FilePath& path) {
298 base::ThreadRestrictions::AssertIOAllowed();
299 DWORD fileattr = GetFileAttributes(path.value().c_str());
300 if (fileattr != INVALID_FILE_ATTRIBUTES)
301 return (fileattr & FILE_ATTRIBUTE_DIRECTORY) != 0;
302 return false;
305 bool GetFileCreationLocalTimeFromHandle(HANDLE file_handle,
306 LPSYSTEMTIME creation_time) {
307 base::ThreadRestrictions::AssertIOAllowed();
308 if (!file_handle)
309 return false;
311 FILETIME utc_filetime;
312 if (!GetFileTime(file_handle, &utc_filetime, NULL, NULL))
313 return false;
315 FILETIME local_filetime;
316 if (!FileTimeToLocalFileTime(&utc_filetime, &local_filetime))
317 return false;
319 return !!FileTimeToSystemTime(&local_filetime, creation_time);
322 bool GetFileCreationLocalTime(const std::wstring& filename,
323 LPSYSTEMTIME creation_time) {
324 base::ThreadRestrictions::AssertIOAllowed();
325 base::win::ScopedHandle file_handle(
326 CreateFile(filename.c_str(), GENERIC_READ, kFileShareAll, NULL,
327 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL));
328 return GetFileCreationLocalTimeFromHandle(file_handle.Get(), creation_time);
331 bool GetTempDir(FilePath* path) {
332 base::ThreadRestrictions::AssertIOAllowed();
334 wchar_t temp_path[MAX_PATH + 1];
335 DWORD path_len = ::GetTempPath(MAX_PATH, temp_path);
336 if (path_len >= MAX_PATH || path_len <= 0)
337 return false;
338 // TODO(evanm): the old behavior of this function was to always strip the
339 // trailing slash. We duplicate this here, but it shouldn't be necessary
340 // when everyone is using the appropriate FilePath APIs.
341 *path = FilePath(temp_path).StripTrailingSeparators();
342 return true;
345 bool GetShmemTempDir(FilePath* path, bool executable) {
346 return GetTempDir(path);
349 bool CreateTemporaryFile(FilePath* path) {
350 base::ThreadRestrictions::AssertIOAllowed();
352 FilePath temp_file;
354 if (!GetTempDir(path))
355 return false;
357 if (CreateTemporaryFileInDir(*path, &temp_file)) {
358 *path = temp_file;
359 return true;
362 return false;
365 FILE* CreateAndOpenTemporaryShmemFile(FilePath* path, bool executable) {
366 base::ThreadRestrictions::AssertIOAllowed();
367 return CreateAndOpenTemporaryFile(path);
370 // On POSIX we have semantics to create and open a temporary file
371 // atomically.
372 // TODO(jrg): is there equivalent call to use on Windows instead of
373 // going 2-step?
374 FILE* CreateAndOpenTemporaryFileInDir(const FilePath& dir, FilePath* path) {
375 base::ThreadRestrictions::AssertIOAllowed();
376 if (!CreateTemporaryFileInDir(dir, path)) {
377 return NULL;
379 // Open file in binary mode, to avoid problems with fwrite. On Windows
380 // it replaces \n's with \r\n's, which may surprise you.
381 // Reference: http://msdn.microsoft.com/en-us/library/h9t88zwz(VS.71).aspx
382 return OpenFile(*path, "wb+");
385 bool CreateTemporaryFileInDir(const FilePath& dir,
386 FilePath* temp_file) {
387 base::ThreadRestrictions::AssertIOAllowed();
389 wchar_t temp_name[MAX_PATH + 1];
391 if (!GetTempFileName(dir.value().c_str(), L"", 0, temp_name)) {
392 DPLOG(WARNING) << "Failed to get temporary file name in " << dir.value();
393 return false;
396 wchar_t long_temp_name[MAX_PATH + 1];
397 DWORD long_name_len = GetLongPathName(temp_name, long_temp_name, MAX_PATH);
398 if (long_name_len > MAX_PATH || long_name_len == 0) {
399 // GetLongPathName() failed, but we still have a temporary file.
400 *temp_file = FilePath(temp_name);
401 return true;
404 FilePath::StringType long_temp_name_str;
405 long_temp_name_str.assign(long_temp_name, long_name_len);
406 *temp_file = FilePath(long_temp_name_str);
407 return true;
410 bool CreateTemporaryDirInDir(const FilePath& base_dir,
411 const FilePath::StringType& prefix,
412 FilePath* new_dir) {
413 base::ThreadRestrictions::AssertIOAllowed();
415 FilePath path_to_create;
416 srand(static_cast<uint32>(time(NULL)));
418 for (int count = 0; count < 50; ++count) {
419 // Try create a new temporary directory with random generated name. If
420 // the one exists, keep trying another path name until we reach some limit.
421 string16 new_dir_name;
422 new_dir_name.assign(prefix);
423 new_dir_name.append(base::IntToString16(::base::GetCurrentProcId()));
424 new_dir_name.push_back('_');
425 new_dir_name.append(base::IntToString16(rand() % kint16max));
427 path_to_create = base_dir.Append(new_dir_name);
428 if (::CreateDirectory(path_to_create.value().c_str(), NULL)) {
429 *new_dir = path_to_create;
430 return true;
434 return false;
437 bool CreateNewTempDirectory(const FilePath::StringType& prefix,
438 FilePath* new_temp_path) {
439 base::ThreadRestrictions::AssertIOAllowed();
441 FilePath system_temp_dir;
442 if (!GetTempDir(&system_temp_dir))
443 return false;
445 return CreateTemporaryDirInDir(system_temp_dir, prefix, new_temp_path);
448 bool CreateDirectory(const FilePath& full_path) {
449 base::ThreadRestrictions::AssertIOAllowed();
451 // If the path exists, we've succeeded if it's a directory, failed otherwise.
452 const wchar_t* full_path_str = full_path.value().c_str();
453 DWORD fileattr = ::GetFileAttributes(full_path_str);
454 if (fileattr != INVALID_FILE_ATTRIBUTES) {
455 if ((fileattr & FILE_ATTRIBUTE_DIRECTORY) != 0) {
456 DVLOG(1) << "CreateDirectory(" << full_path_str << "), "
457 << "directory already exists.";
458 return true;
460 DLOG(WARNING) << "CreateDirectory(" << full_path_str << "), "
461 << "conflicts with existing file.";
462 return false;
465 // Invariant: Path does not exist as file or directory.
467 // Attempt to create the parent recursively. This will immediately return
468 // true if it already exists, otherwise will create all required parent
469 // directories starting with the highest-level missing parent.
470 FilePath parent_path(full_path.DirName());
471 if (parent_path.value() == full_path.value()) {
472 return false;
474 if (!CreateDirectory(parent_path)) {
475 DLOG(WARNING) << "Failed to create one of the parent directories.";
476 return false;
479 if (!::CreateDirectory(full_path_str, NULL)) {
480 DWORD error_code = ::GetLastError();
481 if (error_code == ERROR_ALREADY_EXISTS && DirectoryExists(full_path)) {
482 // This error code ERROR_ALREADY_EXISTS doesn't indicate whether we
483 // were racing with someone creating the same directory, or a file
484 // with the same path. If DirectoryExists() returns true, we lost the
485 // race to create the same directory.
486 return true;
487 } else {
488 DLOG(WARNING) << "Failed to create directory " << full_path_str
489 << ", last error is " << error_code << ".";
490 return false;
492 } else {
493 return true;
497 // TODO(rkc): Work out if we want to handle NTFS junctions here or not, handle
498 // them if we do decide to.
499 bool IsLink(const FilePath& file_path) {
500 return false;
503 bool GetFileInfo(const FilePath& file_path, base::PlatformFileInfo* results) {
504 base::ThreadRestrictions::AssertIOAllowed();
506 WIN32_FILE_ATTRIBUTE_DATA attr;
507 if (!GetFileAttributesEx(file_path.value().c_str(),
508 GetFileExInfoStandard, &attr)) {
509 return false;
512 ULARGE_INTEGER size;
513 size.HighPart = attr.nFileSizeHigh;
514 size.LowPart = attr.nFileSizeLow;
515 results->size = size.QuadPart;
517 results->is_directory =
518 (attr.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
519 results->last_modified = base::Time::FromFileTime(attr.ftLastWriteTime);
520 results->last_accessed = base::Time::FromFileTime(attr.ftLastAccessTime);
521 results->creation_time = base::Time::FromFileTime(attr.ftCreationTime);
523 return true;
526 FILE* OpenFile(const FilePath& filename, const char* mode) {
527 base::ThreadRestrictions::AssertIOAllowed();
528 std::wstring w_mode = ASCIIToWide(std::string(mode));
529 return _wfsopen(filename.value().c_str(), w_mode.c_str(), _SH_DENYNO);
532 FILE* OpenFile(const std::string& filename, const char* mode) {
533 base::ThreadRestrictions::AssertIOAllowed();
534 return _fsopen(filename.c_str(), mode, _SH_DENYNO);
537 int ReadFile(const FilePath& filename, char* data, int size) {
538 base::ThreadRestrictions::AssertIOAllowed();
539 base::win::ScopedHandle file(CreateFile(filename.value().c_str(),
540 GENERIC_READ,
541 FILE_SHARE_READ | FILE_SHARE_WRITE,
542 NULL,
543 OPEN_EXISTING,
544 FILE_FLAG_SEQUENTIAL_SCAN,
545 NULL));
546 if (!file)
547 return -1;
549 DWORD read;
550 if (::ReadFile(file, data, size, &read, NULL) &&
551 static_cast<int>(read) == size)
552 return read;
553 return -1;
556 int WriteFile(const FilePath& filename, const char* data, int size) {
557 base::ThreadRestrictions::AssertIOAllowed();
558 base::win::ScopedHandle file(CreateFile(filename.value().c_str(),
559 GENERIC_WRITE,
561 NULL,
562 CREATE_ALWAYS,
564 NULL));
565 if (!file) {
566 DLOG(WARNING) << "CreateFile failed for path " << filename.value()
567 << " error code=" << GetLastError();
568 return -1;
571 DWORD written;
572 BOOL result = ::WriteFile(file, data, size, &written, NULL);
573 if (result && static_cast<int>(written) == size)
574 return written;
576 if (!result) {
577 // WriteFile failed.
578 DLOG(WARNING) << "writing file " << filename.value()
579 << " failed, error code=" << GetLastError();
580 } else {
581 // Didn't write all the bytes.
582 DLOG(WARNING) << "wrote" << written << " bytes to "
583 << filename.value() << " expected " << size;
585 return -1;
588 int AppendToFile(const FilePath& filename, const char* data, int size) {
589 base::ThreadRestrictions::AssertIOAllowed();
590 base::win::ScopedHandle file(CreateFile(filename.value().c_str(),
591 FILE_APPEND_DATA,
593 NULL,
594 OPEN_EXISTING,
596 NULL));
597 if (!file) {
598 DLOG(WARNING) << "CreateFile failed for path " << filename.value()
599 << " error code=" << GetLastError();
600 return -1;
603 DWORD written;
604 BOOL result = ::WriteFile(file, data, size, &written, NULL);
605 if (result && static_cast<int>(written) == size)
606 return written;
608 if (!result) {
609 // WriteFile failed.
610 DLOG(WARNING) << "writing file " << filename.value()
611 << " failed, error code=" << GetLastError();
612 } else {
613 // Didn't write all the bytes.
614 DLOG(WARNING) << "wrote" << written << " bytes to "
615 << filename.value() << " expected " << size;
617 return -1;
620 // Gets the current working directory for the process.
621 bool GetCurrentDirectory(FilePath* dir) {
622 base::ThreadRestrictions::AssertIOAllowed();
624 wchar_t system_buffer[MAX_PATH];
625 system_buffer[0] = 0;
626 DWORD len = ::GetCurrentDirectory(MAX_PATH, system_buffer);
627 if (len == 0 || len > MAX_PATH)
628 return false;
629 // TODO(evanm): the old behavior of this function was to always strip the
630 // trailing slash. We duplicate this here, but it shouldn't be necessary
631 // when everyone is using the appropriate FilePath APIs.
632 std::wstring dir_str(system_buffer);
633 *dir = FilePath(dir_str).StripTrailingSeparators();
634 return true;
637 // Sets the current working directory for the process.
638 bool SetCurrentDirectory(const FilePath& directory) {
639 base::ThreadRestrictions::AssertIOAllowed();
640 BOOL ret = ::SetCurrentDirectory(directory.value().c_str());
641 return ret != 0;
644 ///////////////////////////////////////////////
645 // FileEnumerator
647 FileEnumerator::FileEnumerator(const FilePath& root_path,
648 bool recursive,
649 int file_type)
650 : recursive_(recursive),
651 file_type_(file_type),
652 has_find_data_(false),
653 find_handle_(INVALID_HANDLE_VALUE) {
654 // INCLUDE_DOT_DOT must not be specified if recursive.
655 DCHECK(!(recursive && (INCLUDE_DOT_DOT & file_type_)));
656 memset(&find_data_, 0, sizeof(find_data_));
657 pending_paths_.push(root_path);
660 FileEnumerator::FileEnumerator(const FilePath& root_path,
661 bool recursive,
662 int file_type,
663 const FilePath::StringType& pattern)
664 : recursive_(recursive),
665 file_type_(file_type),
666 has_find_data_(false),
667 pattern_(pattern),
668 find_handle_(INVALID_HANDLE_VALUE) {
669 // INCLUDE_DOT_DOT must not be specified if recursive.
670 DCHECK(!(recursive && (INCLUDE_DOT_DOT & file_type_)));
671 memset(&find_data_, 0, sizeof(find_data_));
672 pending_paths_.push(root_path);
675 FileEnumerator::~FileEnumerator() {
676 if (find_handle_ != INVALID_HANDLE_VALUE)
677 FindClose(find_handle_);
680 void FileEnumerator::GetFindInfo(FindInfo* info) {
681 DCHECK(info);
683 if (!has_find_data_)
684 return;
686 memcpy(info, &find_data_, sizeof(*info));
689 // static
690 bool FileEnumerator::IsDirectory(const FindInfo& info) {
691 return (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
694 // static
695 FilePath FileEnumerator::GetFilename(const FindInfo& find_info) {
696 return FilePath(find_info.cFileName);
699 // static
700 int64 FileEnumerator::GetFilesize(const FindInfo& find_info) {
701 ULARGE_INTEGER size;
702 size.HighPart = find_info.nFileSizeHigh;
703 size.LowPart = find_info.nFileSizeLow;
704 DCHECK_LE(size.QuadPart, std::numeric_limits<int64>::max());
705 return static_cast<int64>(size.QuadPart);
708 // static
709 base::Time FileEnumerator::GetLastModifiedTime(const FindInfo& find_info) {
710 return base::Time::FromFileTime(find_info.ftLastWriteTime);
713 FilePath FileEnumerator::Next() {
714 base::ThreadRestrictions::AssertIOAllowed();
716 while (has_find_data_ || !pending_paths_.empty()) {
717 if (!has_find_data_) {
718 // The last find FindFirstFile operation is done, prepare a new one.
719 root_path_ = pending_paths_.top();
720 pending_paths_.pop();
722 // Start a new find operation.
723 FilePath src = root_path_;
725 if (pattern_.empty())
726 src = src.Append(L"*"); // No pattern = match everything.
727 else
728 src = src.Append(pattern_);
730 find_handle_ = FindFirstFile(src.value().c_str(), &find_data_);
731 has_find_data_ = true;
732 } else {
733 // Search for the next file/directory.
734 if (!FindNextFile(find_handle_, &find_data_)) {
735 FindClose(find_handle_);
736 find_handle_ = INVALID_HANDLE_VALUE;
740 if (INVALID_HANDLE_VALUE == find_handle_) {
741 has_find_data_ = false;
743 // This is reached when we have finished a directory and are advancing to
744 // the next one in the queue. We applied the pattern (if any) to the files
745 // in the root search directory, but for those directories which were
746 // matched, we want to enumerate all files inside them. This will happen
747 // when the handle is empty.
748 pattern_ = FilePath::StringType();
750 continue;
753 FilePath cur_file(find_data_.cFileName);
754 if (ShouldSkip(cur_file))
755 continue;
757 // Construct the absolute filename.
758 cur_file = root_path_.Append(find_data_.cFileName);
760 if (find_data_.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
761 if (recursive_) {
762 // If |cur_file| is a directory, and we are doing recursive searching,
763 // add it to pending_paths_ so we scan it after we finish scanning this
764 // directory.
765 pending_paths_.push(cur_file);
767 if (file_type_ & FileEnumerator::DIRECTORIES)
768 return cur_file;
769 } else if (file_type_ & FileEnumerator::FILES) {
770 return cur_file;
774 return FilePath();
777 ///////////////////////////////////////////////
778 // MemoryMappedFile
780 MemoryMappedFile::MemoryMappedFile()
781 : file_(INVALID_HANDLE_VALUE),
782 file_mapping_(INVALID_HANDLE_VALUE),
783 data_(NULL),
784 length_(INVALID_FILE_SIZE) {
787 bool MemoryMappedFile::InitializeAsImageSection(const FilePath& file_name) {
788 if (IsValid())
789 return false;
790 file_ = base::CreatePlatformFile(
791 file_name, base::PLATFORM_FILE_OPEN | base::PLATFORM_FILE_READ,
792 NULL, NULL);
794 if (file_ == base::kInvalidPlatformFileValue) {
795 DLOG(ERROR) << "Couldn't open " << file_name.value();
796 return false;
799 if (!MapFileToMemoryInternalEx(SEC_IMAGE)) {
800 CloseHandles();
801 return false;
804 return true;
807 bool MemoryMappedFile::MapFileToMemoryInternal() {
808 return MapFileToMemoryInternalEx(0);
811 bool MemoryMappedFile::MapFileToMemoryInternalEx(int flags) {
812 base::ThreadRestrictions::AssertIOAllowed();
814 if (file_ == INVALID_HANDLE_VALUE)
815 return false;
817 length_ = ::GetFileSize(file_, NULL);
818 if (length_ == INVALID_FILE_SIZE)
819 return false;
821 file_mapping_ = ::CreateFileMapping(file_, NULL, PAGE_READONLY | flags,
822 0, 0, NULL);
823 if (!file_mapping_) {
824 // According to msdn, system error codes are only reserved up to 15999.
825 // http://msdn.microsoft.com/en-us/library/ms681381(v=VS.85).aspx.
826 UMA_HISTOGRAM_ENUMERATION("MemoryMappedFile.CreateFileMapping",
827 logging::GetLastSystemErrorCode(), 16000);
828 return false;
831 data_ = static_cast<uint8*>(
832 ::MapViewOfFile(file_mapping_, FILE_MAP_READ, 0, 0, 0));
833 if (!data_) {
834 UMA_HISTOGRAM_ENUMERATION("MemoryMappedFile.MapViewOfFile",
835 logging::GetLastSystemErrorCode(), 16000);
837 return data_ != NULL;
840 void MemoryMappedFile::CloseHandles() {
841 if (data_)
842 ::UnmapViewOfFile(data_);
843 if (file_mapping_ != INVALID_HANDLE_VALUE)
844 ::CloseHandle(file_mapping_);
845 if (file_ != INVALID_HANDLE_VALUE)
846 ::CloseHandle(file_);
848 data_ = NULL;
849 file_mapping_ = file_ = INVALID_HANDLE_VALUE;
850 length_ = INVALID_FILE_SIZE;
853 bool HasFileBeenModifiedSince(const FileEnumerator::FindInfo& find_info,
854 const base::Time& cutoff_time) {
855 base::ThreadRestrictions::AssertIOAllowed();
856 FILETIME file_time = cutoff_time.ToFileTime();
857 long result = CompareFileTime(&find_info.ftLastWriteTime, // NOLINT
858 &file_time);
859 return result == 1 || result == 0;
862 bool NormalizeFilePath(const FilePath& path, FilePath* real_path) {
863 base::ThreadRestrictions::AssertIOAllowed();
864 FilePath mapped_file;
865 if (!NormalizeToNativeFilePath(path, &mapped_file))
866 return false;
867 // NormalizeToNativeFilePath() will return a path that starts with
868 // "\Device\Harddisk...". Helper DevicePathToDriveLetterPath()
869 // will find a drive letter which maps to the path's device, so
870 // that we return a path starting with a drive letter.
871 return DevicePathToDriveLetterPath(mapped_file, real_path);
874 bool DevicePathToDriveLetterPath(const FilePath& nt_device_path,
875 FilePath* out_drive_letter_path) {
876 base::ThreadRestrictions::AssertIOAllowed();
878 // Get the mapping of drive letters to device paths.
879 const int kDriveMappingSize = 1024;
880 wchar_t drive_mapping[kDriveMappingSize] = {'\0'};
881 if (!::GetLogicalDriveStrings(kDriveMappingSize - 1, drive_mapping)) {
882 DLOG(ERROR) << "Failed to get drive mapping.";
883 return false;
886 // The drive mapping is a sequence of null terminated strings.
887 // The last string is empty.
888 wchar_t* drive_map_ptr = drive_mapping;
889 wchar_t device_path_as_string[MAX_PATH];
890 wchar_t drive[] = L" :";
892 // For each string in the drive mapping, get the junction that links
893 // to it. If that junction is a prefix of |device_path|, then we
894 // know that |drive| is the real path prefix.
895 while (*drive_map_ptr) {
896 drive[0] = drive_map_ptr[0]; // Copy the drive letter.
898 if (QueryDosDevice(drive, device_path_as_string, MAX_PATH)) {
899 FilePath device_path(device_path_as_string);
900 if (device_path == nt_device_path ||
901 device_path.IsParent(nt_device_path)) {
902 *out_drive_letter_path = FilePath(drive +
903 nt_device_path.value().substr(wcslen(device_path_as_string)));
904 return true;
907 // Move to the next drive letter string, which starts one
908 // increment after the '\0' that terminates the current string.
909 while (*drive_map_ptr++);
912 // No drive matched. The path does not start with a device junction
913 // that is mounted as a drive letter. This means there is no drive
914 // letter path to the volume that holds |device_path|, so fail.
915 return false;
918 bool NormalizeToNativeFilePath(const FilePath& path, FilePath* nt_path) {
919 base::ThreadRestrictions::AssertIOAllowed();
920 // In Vista, GetFinalPathNameByHandle() would give us the real path
921 // from a file handle. If we ever deprecate XP, consider changing the
922 // code below to a call to GetFinalPathNameByHandle(). The method this
923 // function uses is explained in the following msdn article:
924 // http://msdn.microsoft.com/en-us/library/aa366789(VS.85).aspx
925 base::win::ScopedHandle file_handle(
926 ::CreateFile(path.value().c_str(),
927 GENERIC_READ,
928 kFileShareAll,
929 NULL,
930 OPEN_EXISTING,
931 FILE_ATTRIBUTE_NORMAL,
932 NULL));
933 if (!file_handle)
934 return false;
936 // Create a file mapping object. Can't easily use MemoryMappedFile, because
937 // we only map the first byte, and need direct access to the handle. You can
938 // not map an empty file, this call fails in that case.
939 base::win::ScopedHandle file_map_handle(
940 ::CreateFileMapping(file_handle.Get(),
941 NULL,
942 PAGE_READONLY,
944 1, // Just one byte. No need to look at the data.
945 NULL));
946 if (!file_map_handle)
947 return false;
949 // Use a view of the file to get the path to the file.
950 void* file_view = MapViewOfFile(file_map_handle.Get(),
951 FILE_MAP_READ, 0, 0, 1);
952 if (!file_view)
953 return false;
955 // The expansion of |path| into a full path may make it longer.
956 // GetMappedFileName() will fail if the result is longer than MAX_PATH.
957 // Pad a bit to be safe. If kMaxPathLength is ever changed to be less
958 // than MAX_PATH, it would be nessisary to test that GetMappedFileName()
959 // not return kMaxPathLength. This would mean that only part of the
960 // path fit in |mapped_file_path|.
961 const int kMaxPathLength = MAX_PATH + 10;
962 wchar_t mapped_file_path[kMaxPathLength];
963 bool success = false;
964 HANDLE cp = GetCurrentProcess();
965 if (::GetMappedFileNameW(cp, file_view, mapped_file_path, kMaxPathLength)) {
966 *nt_path = FilePath(mapped_file_path);
967 success = true;
969 ::UnmapViewOfFile(file_view);
970 return success;
973 } // namespace file_util