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"
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"
32 const DWORD kFileShareAll
=
33 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
;
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
))
42 *path
= FilePath(file_path_buf
);
46 int CountFilesCreatedAfter(const FilePath
& path
,
47 const base::Time
& comparison_time
) {
48 base::ThreadRestrictions::AssertIOAllowed();
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
) {
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))
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))
69 } while (FindNextFile(find_handle
, &find_file_data
));
70 FindClose(find_handle
);
76 bool Delete(const FilePath
& path
, bool recursive
) {
77 base::ThreadRestrictions::AssertIOAllowed();
79 if (path
.value().length() >= MAX_PATH
)
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)
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
;
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
)
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
)
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
) {
150 if (MoveFileEx(from_path
.value().c_str(), to_path
.value().c_str(),
151 MOVEFILE_COPY_ALLOWED
| MOVEFILE_REPLACE_EXISTING
) != 0)
154 // Keep the last error value from MoveFileEx around in case the below
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
);
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
);
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
179 if (::MoveFile(from_path
.value().c_str(), to_path
.value().c_str()))
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
)) {
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
) {
201 return (::CopyFile(from_path
.value().c_str(), to_path
.value().c_str(),
205 bool ShellCopy(const FilePath
& from_path
, const FilePath
& to_path
,
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
) {
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
|
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
,
240 base::ThreadRestrictions::AssertIOAllowed();
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
);
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)) {
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.
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();
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
)
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;
305 bool GetFileCreationLocalTimeFromHandle(HANDLE file_handle
,
306 LPSYSTEMTIME creation_time
) {
307 base::ThreadRestrictions::AssertIOAllowed();
311 FILETIME utc_filetime
;
312 if (!GetFileTime(file_handle
, &utc_filetime
, NULL
, NULL
))
315 FILETIME local_filetime
;
316 if (!FileTimeToLocalFileTime(&utc_filetime
, &local_filetime
))
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)
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();
345 bool GetShmemTempDir(FilePath
* path
, bool executable
) {
346 return GetTempDir(path
);
349 bool CreateTemporaryFile(FilePath
* path
) {
350 base::ThreadRestrictions::AssertIOAllowed();
354 if (!GetTempDir(path
))
357 if (CreateTemporaryFileInDir(*path
, &temp_file
)) {
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
372 // TODO(jrg): is there equivalent call to use on Windows instead of
374 FILE* CreateAndOpenTemporaryFileInDir(const FilePath
& dir
, FilePath
* path
) {
375 base::ThreadRestrictions::AssertIOAllowed();
376 if (!CreateTemporaryFileInDir(dir
, path
)) {
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();
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
);
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
);
410 bool CreateTemporaryDirInDir(const FilePath
& base_dir
,
411 const FilePath::StringType
& prefix
,
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
;
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
))
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.";
460 DLOG(WARNING
) << "CreateDirectory(" << full_path_str
<< "), "
461 << "conflicts with existing file.";
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()) {
474 if (!CreateDirectory(parent_path
)) {
475 DLOG(WARNING
) << "Failed to create one of the parent directories.";
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.
488 DLOG(WARNING
) << "Failed to create directory " << full_path_str
489 << ", last error is " << error_code
<< ".";
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
) {
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
)) {
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
);
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(),
541 FILE_SHARE_READ
| FILE_SHARE_WRITE
,
544 FILE_FLAG_SEQUENTIAL_SCAN
,
550 if (::ReadFile(file
, data
, size
, &read
, NULL
) &&
551 static_cast<int>(read
) == size
)
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(),
566 DLOG(WARNING
) << "CreateFile failed for path " << filename
.value()
567 << " error code=" << GetLastError();
572 BOOL result
= ::WriteFile(file
, data
, size
, &written
, NULL
);
573 if (result
&& static_cast<int>(written
) == size
)
578 DLOG(WARNING
) << "writing file " << filename
.value()
579 << " failed, error code=" << GetLastError();
581 // Didn't write all the bytes.
582 DLOG(WARNING
) << "wrote" << written
<< " bytes to "
583 << filename
.value() << " expected " << size
;
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(),
598 DLOG(WARNING
) << "CreateFile failed for path " << filename
.value()
599 << " error code=" << GetLastError();
604 BOOL result
= ::WriteFile(file
, data
, size
, &written
, NULL
);
605 if (result
&& static_cast<int>(written
) == size
)
610 DLOG(WARNING
) << "writing file " << filename
.value()
611 << " failed, error code=" << GetLastError();
613 // Didn't write all the bytes.
614 DLOG(WARNING
) << "wrote" << written
<< " bytes to "
615 << filename
.value() << " expected " << size
;
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
)
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();
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());
644 ///////////////////////////////////////////////
647 FileEnumerator::FileEnumerator(const FilePath
& root_path
,
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
,
663 const FilePath::StringType
& pattern
)
664 : recursive_(recursive
),
665 file_type_(file_type
),
666 has_find_data_(false),
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
) {
686 memcpy(info
, &find_data_
, sizeof(*info
));
690 bool FileEnumerator::IsDirectory(const FindInfo
& info
) {
691 return (info
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
) != 0;
695 FilePath
FileEnumerator::GetFilename(const FindInfo
& find_info
) {
696 return FilePath(find_info
.cFileName
);
700 int64
FileEnumerator::GetFilesize(const FindInfo
& find_info
) {
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
);
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.
728 src
= src
.Append(pattern_
);
730 find_handle_
= FindFirstFile(src
.value().c_str(), &find_data_
);
731 has_find_data_
= true;
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();
753 FilePath
cur_file(find_data_
.cFileName
);
754 if (ShouldSkip(cur_file
))
757 // Construct the absolute filename.
758 cur_file
= root_path_
.Append(find_data_
.cFileName
);
760 if (find_data_
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
) {
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
765 pending_paths_
.push(cur_file
);
767 if (file_type_
& FileEnumerator::DIRECTORIES
)
769 } else if (file_type_
& FileEnumerator::FILES
) {
777 ///////////////////////////////////////////////
780 MemoryMappedFile::MemoryMappedFile()
781 : file_(INVALID_HANDLE_VALUE
),
782 file_mapping_(INVALID_HANDLE_VALUE
),
784 length_(INVALID_FILE_SIZE
) {
787 bool MemoryMappedFile::InitializeAsImageSection(const FilePath
& file_name
) {
790 file_
= base::CreatePlatformFile(
791 file_name
, base::PLATFORM_FILE_OPEN
| base::PLATFORM_FILE_READ
,
794 if (file_
== base::kInvalidPlatformFileValue
) {
795 DLOG(ERROR
) << "Couldn't open " << file_name
.value();
799 if (!MapFileToMemoryInternalEx(SEC_IMAGE
)) {
807 bool MemoryMappedFile::MapFileToMemoryInternal() {
808 return MapFileToMemoryInternalEx(0);
811 bool MemoryMappedFile::MapFileToMemoryInternalEx(int flags
) {
812 base::ThreadRestrictions::AssertIOAllowed();
814 if (file_
== INVALID_HANDLE_VALUE
)
817 length_
= ::GetFileSize(file_
, NULL
);
818 if (length_
== INVALID_FILE_SIZE
)
821 file_mapping_
= ::CreateFileMapping(file_
, NULL
, PAGE_READONLY
| flags
,
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);
831 data_
= static_cast<uint8
*>(
832 ::MapViewOfFile(file_mapping_
, FILE_MAP_READ
, 0, 0, 0));
834 UMA_HISTOGRAM_ENUMERATION("MemoryMappedFile.MapViewOfFile",
835 logging::GetLastSystemErrorCode(), 16000);
837 return data_
!= NULL
;
840 void MemoryMappedFile::CloseHandles() {
842 ::UnmapViewOfFile(data_
);
843 if (file_mapping_
!= INVALID_HANDLE_VALUE
)
844 ::CloseHandle(file_mapping_
);
845 if (file_
!= INVALID_HANDLE_VALUE
)
846 ::CloseHandle(file_
);
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
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
))
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.";
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
)));
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.
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(),
931 FILE_ATTRIBUTE_NORMAL
,
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(),
944 1, // Just one byte. No need to look at the data.
946 if (!file_map_handle
)
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);
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
);
969 ::UnmapViewOfFile(file_view
);
973 } // namespace file_util