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"
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"
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
))
38 return FilePath(file_path
);
47 const DWORD kFileShareAll
=
48 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
;
52 bool Delete(const FilePath
& path
, bool recursive
) {
53 base::ThreadRestrictions::AssertIOAllowed();
55 if (path
.value().length() >= MAX_PATH
)
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)
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
;
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
)
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
)
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
) {
126 if (MoveFileEx(from_path
.value().c_str(), to_path
.value().c_str(),
127 MOVEFILE_COPY_ALLOWED
| MOVEFILE_REPLACE_EXISTING
) != 0)
130 // Keep the last error value from MoveFileEx around in case the below
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
);
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
);
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
155 if (::MoveFile(from_path
.value().c_str(), to_path
.value().c_str()))
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
)) {
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
) {
177 return (::CopyFile(from_path
.value().c_str(), to_path
.value().c_str(),
181 bool ShellCopy(const FilePath
& from_path
, const FilePath
& to_path
,
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
) {
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
|
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
,
220 base::ThreadRestrictions::AssertIOAllowed();
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
);
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)) {
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.
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();
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
)
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;
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)
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();
299 bool GetShmemTempDir(FilePath
* path
, bool executable
) {
300 return GetTempDir(path
);
303 bool CreateTemporaryFile(FilePath
* path
) {
304 base::ThreadRestrictions::AssertIOAllowed();
308 if (!GetTempDir(path
))
311 if (CreateTemporaryFileInDir(*path
, &temp_file
)) {
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
326 // TODO(jrg): is there equivalent call to use on Windows instead of
328 FILE* CreateAndOpenTemporaryFileInDir(const FilePath
& dir
, FilePath
* path
) {
329 base::ThreadRestrictions::AssertIOAllowed();
330 if (!CreateTemporaryFileInDir(dir
, path
)) {
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();
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
);
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
);
364 bool CreateTemporaryDirInDir(const FilePath
& base_dir
,
365 const FilePath::StringType
& prefix
,
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
;
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
))
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.";
414 DLOG(WARNING
) << "CreateDirectory(" << full_path_str
<< "), "
415 << "conflicts with existing file.";
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()) {
428 if (!CreateDirectory(parent_path
)) {
429 DLOG(WARNING
) << "Failed to create one of the parent directories.";
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.
442 DLOG(WARNING
) << "Failed to create directory " << full_path_str
443 << ", last error is " << error_code
<< ".";
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
) {
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
)) {
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
);
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(),
495 FILE_SHARE_READ
| FILE_SHARE_WRITE
,
498 FILE_FLAG_SEQUENTIAL_SCAN
,
504 if (::ReadFile(file
, data
, size
, &read
, NULL
) &&
505 static_cast<int>(read
) == size
)
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(),
520 DLOG_GETLASTERROR(WARNING
) << "CreateFile failed for path "
526 BOOL result
= ::WriteFile(file
, data
, size
, &written
, NULL
);
527 if (result
&& static_cast<int>(written
) == size
)
532 DLOG_GETLASTERROR(WARNING
) << "writing file " << filename
.value()
535 // Didn't write all the bytes.
536 DLOG(WARNING
) << "wrote" << written
<< " bytes to "
537 << filename
.value() << " expected " << size
;
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(),
552 DLOG_GETLASTERROR(WARNING
) << "CreateFile failed for path "
558 BOOL result
= ::WriteFile(file
, data
, size
, &written
, NULL
);
559 if (result
&& static_cast<int>(written
) == size
)
564 DLOG_GETLASTERROR(WARNING
) << "writing file " << filename
.value()
567 // Didn't write all the bytes.
568 DLOG(WARNING
) << "wrote" << written
<< " bytes to "
569 << filename
.value() << " expected " << size
;
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
)
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();
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());
598 ///////////////////////////////////////////////
601 FileEnumerator::FileEnumerator(const FilePath
& root_path
,
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
,
617 const FilePath::StringType
& pattern
)
618 : recursive_(recursive
),
619 file_type_(file_type
),
620 has_find_data_(false),
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
) {
640 memcpy(info
, &find_data_
, sizeof(*info
));
644 bool FileEnumerator::IsDirectory(const FindInfo
& info
) {
645 return (info
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
) != 0;
649 FilePath
FileEnumerator::GetFilename(const FindInfo
& find_info
) {
650 return FilePath(find_info
.cFileName
);
654 int64
FileEnumerator::GetFilesize(const FindInfo
& find_info
) {
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
);
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.
682 src
= src
.Append(pattern_
);
684 find_handle_
= FindFirstFile(src
.value().c_str(), &find_data_
);
685 has_find_data_
= true;
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();
707 FilePath
cur_file(find_data_
.cFileName
);
708 if (ShouldSkip(cur_file
))
711 // Construct the absolute filename.
712 cur_file
= root_path_
.Append(find_data_
.cFileName
);
714 if (find_data_
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
) {
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
719 pending_paths_
.push(cur_file
);
721 if (file_type_
& FileEnumerator::DIRECTORIES
)
723 } else if (file_type_
& FileEnumerator::FILES
) {
731 bool NormalizeFilePath(const FilePath
& path
, FilePath
* real_path
) {
732 base::ThreadRestrictions::AssertIOAllowed();
733 FilePath mapped_file
;
734 if (!NormalizeToNativeFilePath(path
, &mapped_file
))
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.";
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
)));
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.
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(),
800 FILE_ATTRIBUTE_NORMAL
,
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(),
813 1, // Just one byte. No need to look at the data.
815 if (!file_map_handle
)
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);
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
);
838 ::UnmapViewOfFile(file_view
);
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(),
848 arraysize(volume_path
))) {
852 DWORD max_length
= 0;
853 if (!GetVolumeInformationW(volume_path
, NULL
, 0, NULL
, &max_length
, NULL
,
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