Revert "Revert "Revert 198403 "Move WrappedTexImage functionality to ui/gl"""
[chromium-blink-merge.git] / base / file_util_win.cc
blob964302adce55b0cafab153460614e5bc2a81a1f3
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 <algorithm>
14 #include <limits>
15 #include <string>
17 #include "base/files/file_path.h"
18 #include "base/logging.h"
19 #include "base/metrics/histogram.h"
20 #include "base/process_util.h"
21 #include "base/string_util.h"
22 #include "base/strings/string_number_conversions.h"
23 #include "base/threading/thread_restrictions.h"
24 #include "base/time.h"
25 #include "base/utf_string_conversions.h"
26 #include "base/win/scoped_handle.h"
27 #include "base/win/windows_version.h"
29 using base::FilePath;
31 namespace base {
33 FilePath MakeAbsoluteFilePath(const FilePath& input) {
34 base::ThreadRestrictions::AssertIOAllowed();
35 wchar_t file_path[MAX_PATH];
36 if (!_wfullpath(file_path, input.value().c_str(), MAX_PATH))
37 return FilePath();
38 return FilePath(file_path);
41 } // namespace base
43 namespace file_util {
45 namespace {
47 const DWORD kFileShareAll =
48 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
50 } // namespace
52 bool Delete(const FilePath& path, bool recursive) {
53 base::ThreadRestrictions::AssertIOAllowed();
55 if (path.value().length() >= MAX_PATH)
56 return false;
58 if (!recursive) {
59 // If not recursing, then first check to see if |path| is a directory.
60 // If it is, then remove it with RemoveDirectory.
61 base::PlatformFileInfo file_info;
62 if (GetFileInfo(path, &file_info) && file_info.is_directory)
63 return RemoveDirectory(path.value().c_str()) != 0;
65 // Otherwise, it's a file, wildcard or non-existant. Try DeleteFile first
66 // because it should be faster. If DeleteFile fails, then we fall through
67 // to SHFileOperation, which will do the right thing.
68 if (DeleteFile(path.value().c_str()) != 0)
69 return true;
72 // SHFILEOPSTRUCT wants the path to be terminated with two NULLs,
73 // so we have to use wcscpy because wcscpy_s writes non-NULLs
74 // into the rest of the buffer.
75 wchar_t double_terminated_path[MAX_PATH + 1] = {0};
76 #pragma warning(suppress:4996) // don't complain about wcscpy deprecation
77 if (g_bug108724_debug)
78 LOG(WARNING) << "copying ";
79 wcscpy(double_terminated_path, path.value().c_str());
81 SHFILEOPSTRUCT file_operation = {0};
82 file_operation.wFunc = FO_DELETE;
83 file_operation.pFrom = double_terminated_path;
84 file_operation.fFlags = FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMATION;
85 if (!recursive)
86 file_operation.fFlags |= FOF_NORECURSION | FOF_FILESONLY;
87 if (g_bug108724_debug)
88 LOG(WARNING) << "Performing shell operation";
89 int err = SHFileOperation(&file_operation);
90 if (g_bug108724_debug)
91 LOG(WARNING) << "Done: " << err;
93 // Since we're passing flags to the operation telling it to be silent,
94 // it's possible for the operation to be aborted/cancelled without err
95 // being set (although MSDN doesn't give any scenarios for how this can
96 // happen). See MSDN for SHFileOperation and SHFILEOPTSTRUCT.
97 if (file_operation.fAnyOperationsAborted)
98 return false;
100 // Some versions of Windows return ERROR_FILE_NOT_FOUND (0x2) when deleting
101 // an empty directory and some return 0x402 when they should be returning
102 // ERROR_FILE_NOT_FOUND. MSDN says Vista and up won't return 0x402.
103 return (err == 0 || err == ERROR_FILE_NOT_FOUND || err == 0x402);
106 bool DeleteAfterReboot(const FilePath& path) {
107 base::ThreadRestrictions::AssertIOAllowed();
109 if (path.value().length() >= MAX_PATH)
110 return false;
112 return MoveFileEx(path.value().c_str(), NULL,
113 MOVEFILE_DELAY_UNTIL_REBOOT |
114 MOVEFILE_REPLACE_EXISTING) != FALSE;
117 bool MoveUnsafe(const FilePath& from_path, const FilePath& to_path) {
118 base::ThreadRestrictions::AssertIOAllowed();
120 // NOTE: I suspect we could support longer paths, but that would involve
121 // analyzing all our usage of files.
122 if (from_path.value().length() >= MAX_PATH ||
123 to_path.value().length() >= MAX_PATH) {
124 return false;
126 if (MoveFileEx(from_path.value().c_str(), to_path.value().c_str(),
127 MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING) != 0)
128 return true;
130 // Keep the last error value from MoveFileEx around in case the below
131 // fails.
132 bool ret = false;
133 DWORD last_error = ::GetLastError();
135 if (DirectoryExists(from_path)) {
136 // MoveFileEx fails if moving directory across volumes. We will simulate
137 // the move by using Copy and Delete. Ideally we could check whether
138 // from_path and to_path are indeed in different volumes.
139 ret = CopyAndDeleteDirectory(from_path, to_path);
142 if (!ret) {
143 // Leave a clue about what went wrong so that it can be (at least) picked
144 // up by a PLOG entry.
145 ::SetLastError(last_error);
148 return ret;
151 bool ReplaceFile(const FilePath& from_path, const FilePath& to_path) {
152 base::ThreadRestrictions::AssertIOAllowed();
153 // Try a simple move first. It will only succeed when |to_path| doesn't
154 // already exist.
155 if (::MoveFile(from_path.value().c_str(), to_path.value().c_str()))
156 return true;
157 // Try the full-blown replace if the move fails, as ReplaceFile will only
158 // succeed when |to_path| does exist. When writing to a network share, we may
159 // not be able to change the ACLs. Ignore ACL errors then
160 // (REPLACEFILE_IGNORE_MERGE_ERRORS).
161 if (::ReplaceFile(to_path.value().c_str(), from_path.value().c_str(), NULL,
162 REPLACEFILE_IGNORE_MERGE_ERRORS, NULL, NULL)) {
163 return true;
165 return false;
168 bool CopyFileUnsafe(const FilePath& from_path, const FilePath& to_path) {
169 base::ThreadRestrictions::AssertIOAllowed();
171 // NOTE: I suspect we could support longer paths, but that would involve
172 // analyzing all our usage of files.
173 if (from_path.value().length() >= MAX_PATH ||
174 to_path.value().length() >= MAX_PATH) {
175 return false;
177 return (::CopyFile(from_path.value().c_str(), to_path.value().c_str(),
178 false) != 0);
181 bool ShellCopy(const FilePath& from_path, const FilePath& to_path,
182 bool recursive) {
183 // WinXP SHFileOperation doesn't like trailing separators.
184 FilePath stripped_from = from_path.StripTrailingSeparators();
185 FilePath stripped_to = to_path.StripTrailingSeparators();
187 base::ThreadRestrictions::AssertIOAllowed();
189 // NOTE: I suspect we could support longer paths, but that would involve
190 // analyzing all our usage of files.
191 if (stripped_from.value().length() >= MAX_PATH ||
192 stripped_to.value().length() >= MAX_PATH) {
193 return false;
196 // SHFILEOPSTRUCT wants the path to be terminated with two NULLs,
197 // so we have to use wcscpy because wcscpy_s writes non-NULLs
198 // into the rest of the buffer.
199 wchar_t double_terminated_path_from[MAX_PATH + 1] = {0};
200 wchar_t double_terminated_path_to[MAX_PATH + 1] = {0};
201 #pragma warning(suppress:4996) // don't complain about wcscpy deprecation
202 wcscpy(double_terminated_path_from, stripped_from.value().c_str());
203 #pragma warning(suppress:4996) // don't complain about wcscpy deprecation
204 wcscpy(double_terminated_path_to, stripped_to.value().c_str());
206 SHFILEOPSTRUCT file_operation = {0};
207 file_operation.wFunc = FO_COPY;
208 file_operation.pFrom = double_terminated_path_from;
209 file_operation.pTo = double_terminated_path_to;
210 file_operation.fFlags = FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMATION |
211 FOF_NOCONFIRMMKDIR;
212 if (!recursive)
213 file_operation.fFlags |= FOF_NORECURSION | FOF_FILESONLY;
215 return (SHFileOperation(&file_operation) == 0);
218 bool CopyDirectory(const FilePath& from_path, const FilePath& to_path,
219 bool recursive) {
220 base::ThreadRestrictions::AssertIOAllowed();
222 if (recursive)
223 return ShellCopy(from_path, to_path, true);
225 // The following code assumes that from path is a directory.
226 DCHECK(DirectoryExists(from_path));
228 // Instead of creating a new directory, we copy the old one to include the
229 // security information of the folder as part of the copy.
230 if (!PathExists(to_path)) {
231 // Except that Vista fails to do that, and instead do a recursive copy if
232 // the target directory doesn't exist.
233 if (base::win::GetVersion() >= base::win::VERSION_VISTA)
234 CreateDirectory(to_path);
235 else
236 ShellCopy(from_path, to_path, false);
239 FilePath directory = from_path.Append(L"*.*");
240 return ShellCopy(directory, to_path, false);
243 bool CopyAndDeleteDirectory(const FilePath& from_path,
244 const FilePath& to_path) {
245 base::ThreadRestrictions::AssertIOAllowed();
246 if (CopyDirectory(from_path, to_path, true)) {
247 if (Delete(from_path, true)) {
248 return true;
250 // Like Move, this function is not transactional, so we just
251 // leave the copied bits behind if deleting from_path fails.
252 // If to_path exists previously then we have already overwritten
253 // it by now, we don't get better off by deleting the new bits.
255 return false;
259 bool PathExists(const FilePath& path) {
260 base::ThreadRestrictions::AssertIOAllowed();
261 return (GetFileAttributes(path.value().c_str()) != INVALID_FILE_ATTRIBUTES);
264 bool PathIsWritable(const FilePath& path) {
265 base::ThreadRestrictions::AssertIOAllowed();
266 HANDLE dir =
267 CreateFile(path.value().c_str(), FILE_ADD_FILE, kFileShareAll,
268 NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
270 if (dir == INVALID_HANDLE_VALUE)
271 return false;
273 CloseHandle(dir);
274 return true;
277 bool DirectoryExists(const FilePath& path) {
278 base::ThreadRestrictions::AssertIOAllowed();
279 DWORD fileattr = GetFileAttributes(path.value().c_str());
280 if (fileattr != INVALID_FILE_ATTRIBUTES)
281 return (fileattr & FILE_ATTRIBUTE_DIRECTORY) != 0;
282 return false;
285 bool GetTempDir(FilePath* path) {
286 base::ThreadRestrictions::AssertIOAllowed();
288 wchar_t temp_path[MAX_PATH + 1];
289 DWORD path_len = ::GetTempPath(MAX_PATH, temp_path);
290 if (path_len >= MAX_PATH || path_len <= 0)
291 return false;
292 // TODO(evanm): the old behavior of this function was to always strip the
293 // trailing slash. We duplicate this here, but it shouldn't be necessary
294 // when everyone is using the appropriate FilePath APIs.
295 *path = FilePath(temp_path).StripTrailingSeparators();
296 return true;
299 bool GetShmemTempDir(FilePath* path, bool executable) {
300 return GetTempDir(path);
303 bool CreateTemporaryFile(FilePath* path) {
304 base::ThreadRestrictions::AssertIOAllowed();
306 FilePath temp_file;
308 if (!GetTempDir(path))
309 return false;
311 if (CreateTemporaryFileInDir(*path, &temp_file)) {
312 *path = temp_file;
313 return true;
316 return false;
319 FILE* CreateAndOpenTemporaryShmemFile(FilePath* path, bool executable) {
320 base::ThreadRestrictions::AssertIOAllowed();
321 return CreateAndOpenTemporaryFile(path);
324 // On POSIX we have semantics to create and open a temporary file
325 // atomically.
326 // TODO(jrg): is there equivalent call to use on Windows instead of
327 // going 2-step?
328 FILE* CreateAndOpenTemporaryFileInDir(const FilePath& dir, FilePath* path) {
329 base::ThreadRestrictions::AssertIOAllowed();
330 if (!CreateTemporaryFileInDir(dir, path)) {
331 return NULL;
333 // Open file in binary mode, to avoid problems with fwrite. On Windows
334 // it replaces \n's with \r\n's, which may surprise you.
335 // Reference: http://msdn.microsoft.com/en-us/library/h9t88zwz(VS.71).aspx
336 return OpenFile(*path, "wb+");
339 bool CreateTemporaryFileInDir(const FilePath& dir,
340 FilePath* temp_file) {
341 base::ThreadRestrictions::AssertIOAllowed();
343 wchar_t temp_name[MAX_PATH + 1];
345 if (!GetTempFileName(dir.value().c_str(), L"", 0, temp_name)) {
346 DPLOG(WARNING) << "Failed to get temporary file name in " << dir.value();
347 return false;
350 wchar_t long_temp_name[MAX_PATH + 1];
351 DWORD long_name_len = GetLongPathName(temp_name, long_temp_name, MAX_PATH);
352 if (long_name_len > MAX_PATH || long_name_len == 0) {
353 // GetLongPathName() failed, but we still have a temporary file.
354 *temp_file = FilePath(temp_name);
355 return true;
358 FilePath::StringType long_temp_name_str;
359 long_temp_name_str.assign(long_temp_name, long_name_len);
360 *temp_file = FilePath(long_temp_name_str);
361 return true;
364 bool CreateTemporaryDirInDir(const FilePath& base_dir,
365 const FilePath::StringType& prefix,
366 FilePath* new_dir) {
367 base::ThreadRestrictions::AssertIOAllowed();
369 FilePath path_to_create;
370 srand(static_cast<uint32>(time(NULL)));
372 for (int count = 0; count < 50; ++count) {
373 // Try create a new temporary directory with random generated name. If
374 // the one exists, keep trying another path name until we reach some limit.
375 string16 new_dir_name;
376 new_dir_name.assign(prefix);
377 new_dir_name.append(base::IntToString16(::base::GetCurrentProcId()));
378 new_dir_name.push_back('_');
379 new_dir_name.append(base::IntToString16(rand() % kint16max));
381 path_to_create = base_dir.Append(new_dir_name);
382 if (::CreateDirectory(path_to_create.value().c_str(), NULL)) {
383 *new_dir = path_to_create;
384 return true;
388 return false;
391 bool CreateNewTempDirectory(const FilePath::StringType& prefix,
392 FilePath* new_temp_path) {
393 base::ThreadRestrictions::AssertIOAllowed();
395 FilePath system_temp_dir;
396 if (!GetTempDir(&system_temp_dir))
397 return false;
399 return CreateTemporaryDirInDir(system_temp_dir, prefix, new_temp_path);
402 bool CreateDirectory(const FilePath& full_path) {
403 base::ThreadRestrictions::AssertIOAllowed();
405 // If the path exists, we've succeeded if it's a directory, failed otherwise.
406 const wchar_t* full_path_str = full_path.value().c_str();
407 DWORD fileattr = ::GetFileAttributes(full_path_str);
408 if (fileattr != INVALID_FILE_ATTRIBUTES) {
409 if ((fileattr & FILE_ATTRIBUTE_DIRECTORY) != 0) {
410 DVLOG(1) << "CreateDirectory(" << full_path_str << "), "
411 << "directory already exists.";
412 return true;
414 DLOG(WARNING) << "CreateDirectory(" << full_path_str << "), "
415 << "conflicts with existing file.";
416 return false;
419 // Invariant: Path does not exist as file or directory.
421 // Attempt to create the parent recursively. This will immediately return
422 // true if it already exists, otherwise will create all required parent
423 // directories starting with the highest-level missing parent.
424 FilePath parent_path(full_path.DirName());
425 if (parent_path.value() == full_path.value()) {
426 return false;
428 if (!CreateDirectory(parent_path)) {
429 DLOG(WARNING) << "Failed to create one of the parent directories.";
430 return false;
433 if (!::CreateDirectory(full_path_str, NULL)) {
434 DWORD error_code = ::GetLastError();
435 if (error_code == ERROR_ALREADY_EXISTS && DirectoryExists(full_path)) {
436 // This error code ERROR_ALREADY_EXISTS doesn't indicate whether we
437 // were racing with someone creating the same directory, or a file
438 // with the same path. If DirectoryExists() returns true, we lost the
439 // race to create the same directory.
440 return true;
441 } else {
442 DLOG(WARNING) << "Failed to create directory " << full_path_str
443 << ", last error is " << error_code << ".";
444 return false;
446 } else {
447 return true;
451 // TODO(rkc): Work out if we want to handle NTFS junctions here or not, handle
452 // them if we do decide to.
453 bool IsLink(const FilePath& file_path) {
454 return false;
457 bool GetFileInfo(const FilePath& file_path, base::PlatformFileInfo* results) {
458 base::ThreadRestrictions::AssertIOAllowed();
460 WIN32_FILE_ATTRIBUTE_DATA attr;
461 if (!GetFileAttributesEx(file_path.value().c_str(),
462 GetFileExInfoStandard, &attr)) {
463 return false;
466 ULARGE_INTEGER size;
467 size.HighPart = attr.nFileSizeHigh;
468 size.LowPart = attr.nFileSizeLow;
469 results->size = size.QuadPart;
471 results->is_directory =
472 (attr.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
473 results->last_modified = base::Time::FromFileTime(attr.ftLastWriteTime);
474 results->last_accessed = base::Time::FromFileTime(attr.ftLastAccessTime);
475 results->creation_time = base::Time::FromFileTime(attr.ftCreationTime);
477 return true;
480 FILE* OpenFile(const FilePath& filename, const char* mode) {
481 base::ThreadRestrictions::AssertIOAllowed();
482 std::wstring w_mode = ASCIIToWide(std::string(mode));
483 return _wfsopen(filename.value().c_str(), w_mode.c_str(), _SH_DENYNO);
486 FILE* OpenFile(const std::string& filename, const char* mode) {
487 base::ThreadRestrictions::AssertIOAllowed();
488 return _fsopen(filename.c_str(), mode, _SH_DENYNO);
491 int ReadFile(const FilePath& filename, char* data, int size) {
492 base::ThreadRestrictions::AssertIOAllowed();
493 base::win::ScopedHandle file(CreateFile(filename.value().c_str(),
494 GENERIC_READ,
495 FILE_SHARE_READ | FILE_SHARE_WRITE,
496 NULL,
497 OPEN_EXISTING,
498 FILE_FLAG_SEQUENTIAL_SCAN,
499 NULL));
500 if (!file)
501 return -1;
503 DWORD read;
504 if (::ReadFile(file, data, size, &read, NULL) &&
505 static_cast<int>(read) == size)
506 return read;
507 return -1;
510 int WriteFile(const FilePath& filename, const char* data, int size) {
511 base::ThreadRestrictions::AssertIOAllowed();
512 base::win::ScopedHandle file(CreateFile(filename.value().c_str(),
513 GENERIC_WRITE,
515 NULL,
516 CREATE_ALWAYS,
518 NULL));
519 if (!file) {
520 DLOG_GETLASTERROR(WARNING) << "CreateFile failed for path "
521 << filename.value();
522 return -1;
525 DWORD written;
526 BOOL result = ::WriteFile(file, data, size, &written, NULL);
527 if (result && static_cast<int>(written) == size)
528 return written;
530 if (!result) {
531 // WriteFile failed.
532 DLOG_GETLASTERROR(WARNING) << "writing file " << filename.value()
533 << " failed";
534 } else {
535 // Didn't write all the bytes.
536 DLOG(WARNING) << "wrote" << written << " bytes to "
537 << filename.value() << " expected " << size;
539 return -1;
542 int AppendToFile(const FilePath& filename, const char* data, int size) {
543 base::ThreadRestrictions::AssertIOAllowed();
544 base::win::ScopedHandle file(CreateFile(filename.value().c_str(),
545 FILE_APPEND_DATA,
547 NULL,
548 OPEN_EXISTING,
550 NULL));
551 if (!file) {
552 DLOG_GETLASTERROR(WARNING) << "CreateFile failed for path "
553 << filename.value();
554 return -1;
557 DWORD written;
558 BOOL result = ::WriteFile(file, data, size, &written, NULL);
559 if (result && static_cast<int>(written) == size)
560 return written;
562 if (!result) {
563 // WriteFile failed.
564 DLOG_GETLASTERROR(WARNING) << "writing file " << filename.value()
565 << " failed";
566 } else {
567 // Didn't write all the bytes.
568 DLOG(WARNING) << "wrote" << written << " bytes to "
569 << filename.value() << " expected " << size;
571 return -1;
574 // Gets the current working directory for the process.
575 bool GetCurrentDirectory(FilePath* dir) {
576 base::ThreadRestrictions::AssertIOAllowed();
578 wchar_t system_buffer[MAX_PATH];
579 system_buffer[0] = 0;
580 DWORD len = ::GetCurrentDirectory(MAX_PATH, system_buffer);
581 if (len == 0 || len > MAX_PATH)
582 return false;
583 // TODO(evanm): the old behavior of this function was to always strip the
584 // trailing slash. We duplicate this here, but it shouldn't be necessary
585 // when everyone is using the appropriate FilePath APIs.
586 std::wstring dir_str(system_buffer);
587 *dir = FilePath(dir_str).StripTrailingSeparators();
588 return true;
591 // Sets the current working directory for the process.
592 bool SetCurrentDirectory(const FilePath& directory) {
593 base::ThreadRestrictions::AssertIOAllowed();
594 BOOL ret = ::SetCurrentDirectory(directory.value().c_str());
595 return ret != 0;
598 ///////////////////////////////////////////////
599 // FileEnumerator
601 FileEnumerator::FileEnumerator(const FilePath& root_path,
602 bool recursive,
603 int file_type)
604 : recursive_(recursive),
605 file_type_(file_type),
606 has_find_data_(false),
607 find_handle_(INVALID_HANDLE_VALUE) {
608 // INCLUDE_DOT_DOT must not be specified if recursive.
609 DCHECK(!(recursive && (INCLUDE_DOT_DOT & file_type_)));
610 memset(&find_data_, 0, sizeof(find_data_));
611 pending_paths_.push(root_path);
614 FileEnumerator::FileEnumerator(const FilePath& root_path,
615 bool recursive,
616 int file_type,
617 const FilePath::StringType& pattern)
618 : recursive_(recursive),
619 file_type_(file_type),
620 has_find_data_(false),
621 pattern_(pattern),
622 find_handle_(INVALID_HANDLE_VALUE) {
623 // INCLUDE_DOT_DOT must not be specified if recursive.
624 DCHECK(!(recursive && (INCLUDE_DOT_DOT & file_type_)));
625 memset(&find_data_, 0, sizeof(find_data_));
626 pending_paths_.push(root_path);
629 FileEnumerator::~FileEnumerator() {
630 if (find_handle_ != INVALID_HANDLE_VALUE)
631 FindClose(find_handle_);
634 void FileEnumerator::GetFindInfo(FindInfo* info) {
635 DCHECK(info);
637 if (!has_find_data_)
638 return;
640 memcpy(info, &find_data_, sizeof(*info));
643 // static
644 bool FileEnumerator::IsDirectory(const FindInfo& info) {
645 return (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
648 // static
649 FilePath FileEnumerator::GetFilename(const FindInfo& find_info) {
650 return FilePath(find_info.cFileName);
653 // static
654 int64 FileEnumerator::GetFilesize(const FindInfo& find_info) {
655 ULARGE_INTEGER size;
656 size.HighPart = find_info.nFileSizeHigh;
657 size.LowPart = find_info.nFileSizeLow;
658 DCHECK_LE(size.QuadPart, std::numeric_limits<int64>::max());
659 return static_cast<int64>(size.QuadPart);
662 // static
663 base::Time FileEnumerator::GetLastModifiedTime(const FindInfo& find_info) {
664 return base::Time::FromFileTime(find_info.ftLastWriteTime);
667 FilePath FileEnumerator::Next() {
668 base::ThreadRestrictions::AssertIOAllowed();
670 while (has_find_data_ || !pending_paths_.empty()) {
671 if (!has_find_data_) {
672 // The last find FindFirstFile operation is done, prepare a new one.
673 root_path_ = pending_paths_.top();
674 pending_paths_.pop();
676 // Start a new find operation.
677 FilePath src = root_path_;
679 if (pattern_.empty())
680 src = src.Append(L"*"); // No pattern = match everything.
681 else
682 src = src.Append(pattern_);
684 find_handle_ = FindFirstFile(src.value().c_str(), &find_data_);
685 has_find_data_ = true;
686 } else {
687 // Search for the next file/directory.
688 if (!FindNextFile(find_handle_, &find_data_)) {
689 FindClose(find_handle_);
690 find_handle_ = INVALID_HANDLE_VALUE;
694 if (INVALID_HANDLE_VALUE == find_handle_) {
695 has_find_data_ = false;
697 // This is reached when we have finished a directory and are advancing to
698 // the next one in the queue. We applied the pattern (if any) to the files
699 // in the root search directory, but for those directories which were
700 // matched, we want to enumerate all files inside them. This will happen
701 // when the handle is empty.
702 pattern_ = FilePath::StringType();
704 continue;
707 FilePath cur_file(find_data_.cFileName);
708 if (ShouldSkip(cur_file))
709 continue;
711 // Construct the absolute filename.
712 cur_file = root_path_.Append(find_data_.cFileName);
714 if (find_data_.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
715 if (recursive_) {
716 // If |cur_file| is a directory, and we are doing recursive searching,
717 // add it to pending_paths_ so we scan it after we finish scanning this
718 // directory.
719 pending_paths_.push(cur_file);
721 if (file_type_ & FileEnumerator::DIRECTORIES)
722 return cur_file;
723 } else if (file_type_ & FileEnumerator::FILES) {
724 return cur_file;
728 return FilePath();
731 bool NormalizeFilePath(const FilePath& path, FilePath* real_path) {
732 base::ThreadRestrictions::AssertIOAllowed();
733 FilePath mapped_file;
734 if (!NormalizeToNativeFilePath(path, &mapped_file))
735 return false;
736 // NormalizeToNativeFilePath() will return a path that starts with
737 // "\Device\Harddisk...". Helper DevicePathToDriveLetterPath()
738 // will find a drive letter which maps to the path's device, so
739 // that we return a path starting with a drive letter.
740 return DevicePathToDriveLetterPath(mapped_file, real_path);
743 bool DevicePathToDriveLetterPath(const FilePath& nt_device_path,
744 FilePath* out_drive_letter_path) {
745 base::ThreadRestrictions::AssertIOAllowed();
747 // Get the mapping of drive letters to device paths.
748 const int kDriveMappingSize = 1024;
749 wchar_t drive_mapping[kDriveMappingSize] = {'\0'};
750 if (!::GetLogicalDriveStrings(kDriveMappingSize - 1, drive_mapping)) {
751 DLOG(ERROR) << "Failed to get drive mapping.";
752 return false;
755 // The drive mapping is a sequence of null terminated strings.
756 // The last string is empty.
757 wchar_t* drive_map_ptr = drive_mapping;
758 wchar_t device_path_as_string[MAX_PATH];
759 wchar_t drive[] = L" :";
761 // For each string in the drive mapping, get the junction that links
762 // to it. If that junction is a prefix of |device_path|, then we
763 // know that |drive| is the real path prefix.
764 while (*drive_map_ptr) {
765 drive[0] = drive_map_ptr[0]; // Copy the drive letter.
767 if (QueryDosDevice(drive, device_path_as_string, MAX_PATH)) {
768 FilePath device_path(device_path_as_string);
769 if (device_path == nt_device_path ||
770 device_path.IsParent(nt_device_path)) {
771 *out_drive_letter_path = FilePath(drive +
772 nt_device_path.value().substr(wcslen(device_path_as_string)));
773 return true;
776 // Move to the next drive letter string, which starts one
777 // increment after the '\0' that terminates the current string.
778 while (*drive_map_ptr++);
781 // No drive matched. The path does not start with a device junction
782 // that is mounted as a drive letter. This means there is no drive
783 // letter path to the volume that holds |device_path|, so fail.
784 return false;
787 bool NormalizeToNativeFilePath(const FilePath& path, FilePath* nt_path) {
788 base::ThreadRestrictions::AssertIOAllowed();
789 // In Vista, GetFinalPathNameByHandle() would give us the real path
790 // from a file handle. If we ever deprecate XP, consider changing the
791 // code below to a call to GetFinalPathNameByHandle(). The method this
792 // function uses is explained in the following msdn article:
793 // http://msdn.microsoft.com/en-us/library/aa366789(VS.85).aspx
794 base::win::ScopedHandle file_handle(
795 ::CreateFile(path.value().c_str(),
796 GENERIC_READ,
797 kFileShareAll,
798 NULL,
799 OPEN_EXISTING,
800 FILE_ATTRIBUTE_NORMAL,
801 NULL));
802 if (!file_handle)
803 return false;
805 // Create a file mapping object. Can't easily use MemoryMappedFile, because
806 // we only map the first byte, and need direct access to the handle. You can
807 // not map an empty file, this call fails in that case.
808 base::win::ScopedHandle file_map_handle(
809 ::CreateFileMapping(file_handle.Get(),
810 NULL,
811 PAGE_READONLY,
813 1, // Just one byte. No need to look at the data.
814 NULL));
815 if (!file_map_handle)
816 return false;
818 // Use a view of the file to get the path to the file.
819 void* file_view = MapViewOfFile(file_map_handle.Get(),
820 FILE_MAP_READ, 0, 0, 1);
821 if (!file_view)
822 return false;
824 // The expansion of |path| into a full path may make it longer.
825 // GetMappedFileName() will fail if the result is longer than MAX_PATH.
826 // Pad a bit to be safe. If kMaxPathLength is ever changed to be less
827 // than MAX_PATH, it would be nessisary to test that GetMappedFileName()
828 // not return kMaxPathLength. This would mean that only part of the
829 // path fit in |mapped_file_path|.
830 const int kMaxPathLength = MAX_PATH + 10;
831 wchar_t mapped_file_path[kMaxPathLength];
832 bool success = false;
833 HANDLE cp = GetCurrentProcess();
834 if (::GetMappedFileNameW(cp, file_view, mapped_file_path, kMaxPathLength)) {
835 *nt_path = FilePath(mapped_file_path);
836 success = true;
838 ::UnmapViewOfFile(file_view);
839 return success;
842 int GetMaximumPathComponentLength(const FilePath& path) {
843 base::ThreadRestrictions::AssertIOAllowed();
845 wchar_t volume_path[MAX_PATH];
846 if (!GetVolumePathNameW(path.NormalizePathSeparators().value().c_str(),
847 volume_path,
848 arraysize(volume_path))) {
849 return -1;
852 DWORD max_length = 0;
853 if (!GetVolumeInformationW(volume_path, NULL, 0, NULL, &max_length, NULL,
854 NULL, 0)) {
855 return -1;
858 // Length of |path| with path separator appended.
859 size_t prefix = path.StripTrailingSeparators().value().size() + 1;
860 // The whole path string must be shorter than MAX_PATH. That is, it must be
861 // prefix + component_length < MAX_PATH (or equivalently, <= MAX_PATH - 1).
862 int whole_path_limit = std::max(0, MAX_PATH - 1 - static_cast<int>(prefix));
863 return std::min(whole_path_limit, static_cast<int>(max_length));
866 } // namespace file_util