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"
8 #include <propvarutil.h>
17 #include "base/file_path.h"
18 #include "base/logging.h"
19 #include "base/metrics/histogram.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/pe_image.h"
26 #include "base/win/scoped_comptr.h"
27 #include "base/win/scoped_handle.h"
28 #include "base/win/win_util.h"
29 #include "base/win/windows_version.h"
35 const DWORD kFileShareAll
=
36 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
;
40 bool AbsolutePath(FilePath
* path
) {
41 base::ThreadRestrictions::AssertIOAllowed();
42 wchar_t file_path_buf
[MAX_PATH
];
43 if (!_wfullpath(file_path_buf
, path
->value().c_str(), MAX_PATH
))
45 *path
= FilePath(file_path_buf
);
49 int CountFilesCreatedAfter(const FilePath
& path
,
50 const base::Time
& comparison_time
) {
51 base::ThreadRestrictions::AssertIOAllowed();
54 FILETIME
comparison_filetime(comparison_time
.ToFileTime());
56 WIN32_FIND_DATA find_file_data
;
57 // All files in given dir
58 std::wstring filename_spec
= path
.Append(L
"*").value();
59 HANDLE find_handle
= FindFirstFile(filename_spec
.c_str(), &find_file_data
);
60 if (find_handle
!= INVALID_HANDLE_VALUE
) {
62 // Don't count current or parent directories.
63 if ((wcscmp(find_file_data
.cFileName
, L
"..") == 0) ||
64 (wcscmp(find_file_data
.cFileName
, L
".") == 0))
67 long result
= CompareFileTime(&find_file_data
.ftCreationTime
, // NOLINT
68 &comparison_filetime
);
69 // File was created after or on comparison time
70 if ((result
== 1) || (result
== 0))
72 } while (FindNextFile(find_handle
, &find_file_data
));
73 FindClose(find_handle
);
79 bool Delete(const FilePath
& path
, bool recursive
) {
80 base::ThreadRestrictions::AssertIOAllowed();
82 if (path
.value().length() >= MAX_PATH
)
86 // If not recursing, then first check to see if |path| is a directory.
87 // If it is, then remove it with RemoveDirectory.
88 base::PlatformFileInfo file_info
;
89 if (GetFileInfo(path
, &file_info
) && file_info
.is_directory
)
90 return RemoveDirectory(path
.value().c_str()) != 0;
92 // Otherwise, it's a file, wildcard or non-existant. Try DeleteFile first
93 // because it should be faster. If DeleteFile fails, then we fall through
94 // to SHFileOperation, which will do the right thing.
95 if (DeleteFile(path
.value().c_str()) != 0)
99 // SHFILEOPSTRUCT wants the path to be terminated with two NULLs,
100 // so we have to use wcscpy because wcscpy_s writes non-NULLs
101 // into the rest of the buffer.
102 wchar_t double_terminated_path
[MAX_PATH
+ 1] = {0};
103 #pragma warning(suppress:4996) // don't complain about wcscpy deprecation
104 wcscpy(double_terminated_path
, path
.value().c_str());
106 SHFILEOPSTRUCT file_operation
= {0};
107 file_operation
.wFunc
= FO_DELETE
;
108 file_operation
.pFrom
= double_terminated_path
;
109 file_operation
.fFlags
= FOF_NOERRORUI
| FOF_SILENT
| FOF_NOCONFIRMATION
;
111 file_operation
.fFlags
|= FOF_NORECURSION
| FOF_FILESONLY
;
112 int err
= SHFileOperation(&file_operation
);
114 // Since we're passing flags to the operation telling it to be silent,
115 // it's possible for the operation to be aborted/cancelled without err
116 // being set (although MSDN doesn't give any scenarios for how this can
117 // happen). See MSDN for SHFileOperation and SHFILEOPTSTRUCT.
118 if (file_operation
.fAnyOperationsAborted
)
121 // Some versions of Windows return ERROR_FILE_NOT_FOUND (0x2) when deleting
122 // an empty directory and some return 0x402 when they should be returning
123 // ERROR_FILE_NOT_FOUND. MSDN says Vista and up won't return 0x402.
124 return (err
== 0 || err
== ERROR_FILE_NOT_FOUND
|| err
== 0x402);
127 bool DeleteAfterReboot(const FilePath
& path
) {
128 base::ThreadRestrictions::AssertIOAllowed();
130 if (path
.value().length() >= MAX_PATH
)
133 return MoveFileEx(path
.value().c_str(), NULL
,
134 MOVEFILE_DELAY_UNTIL_REBOOT
|
135 MOVEFILE_REPLACE_EXISTING
) != FALSE
;
138 bool Move(const FilePath
& from_path
, const FilePath
& to_path
) {
139 base::ThreadRestrictions::AssertIOAllowed();
141 // NOTE: I suspect we could support longer paths, but that would involve
142 // analyzing all our usage of files.
143 if (from_path
.value().length() >= MAX_PATH
||
144 to_path
.value().length() >= MAX_PATH
) {
147 if (MoveFileEx(from_path
.value().c_str(), to_path
.value().c_str(),
148 MOVEFILE_COPY_ALLOWED
| MOVEFILE_REPLACE_EXISTING
) != 0)
151 // Keep the last error value from MoveFileEx around in case the below
154 DWORD last_error
= ::GetLastError();
156 if (DirectoryExists(from_path
)) {
157 // MoveFileEx fails if moving directory across volumes. We will simulate
158 // the move by using Copy and Delete. Ideally we could check whether
159 // from_path and to_path are indeed in different volumes.
160 ret
= CopyAndDeleteDirectory(from_path
, to_path
);
164 // Leave a clue about what went wrong so that it can be (at least) picked
165 // up by a PLOG entry.
166 ::SetLastError(last_error
);
172 bool ReplaceFile(const FilePath
& from_path
, const FilePath
& to_path
) {
173 base::ThreadRestrictions::AssertIOAllowed();
175 // Make sure that the target file exists.
176 HANDLE target_file
= ::CreateFile(
177 to_path
.value().c_str(),
179 FILE_SHARE_READ
| FILE_SHARE_WRITE
,
182 FILE_ATTRIBUTE_NORMAL
,
184 if (target_file
!= INVALID_HANDLE_VALUE
)
185 ::CloseHandle(target_file
);
186 // When writing to a network share, we may not be able to change the ACLs.
187 // Ignore ACL errors then (REPLACEFILE_IGNORE_MERGE_ERRORS).
188 return ::ReplaceFile(to_path
.value().c_str(),
189 from_path
.value().c_str(), NULL
,
190 REPLACEFILE_IGNORE_MERGE_ERRORS
, NULL
, NULL
) ? true : false;
193 bool CopyFile(const FilePath
& from_path
, const FilePath
& to_path
) {
194 base::ThreadRestrictions::AssertIOAllowed();
196 // NOTE: I suspect we could support longer paths, but that would involve
197 // analyzing all our usage of files.
198 if (from_path
.value().length() >= MAX_PATH
||
199 to_path
.value().length() >= MAX_PATH
) {
202 return (::CopyFile(from_path
.value().c_str(), to_path
.value().c_str(),
206 bool ShellCopy(const FilePath
& from_path
, const FilePath
& to_path
,
208 base::ThreadRestrictions::AssertIOAllowed();
210 // NOTE: I suspect we could support longer paths, but that would involve
211 // analyzing all our usage of files.
212 if (from_path
.value().length() >= MAX_PATH
||
213 to_path
.value().length() >= MAX_PATH
) {
217 // SHFILEOPSTRUCT wants the path to be terminated with two NULLs,
218 // so we have to use wcscpy because wcscpy_s writes non-NULLs
219 // into the rest of the buffer.
220 wchar_t double_terminated_path_from
[MAX_PATH
+ 1] = {0};
221 wchar_t double_terminated_path_to
[MAX_PATH
+ 1] = {0};
222 #pragma warning(suppress:4996) // don't complain about wcscpy deprecation
223 wcscpy(double_terminated_path_from
, from_path
.value().c_str());
224 #pragma warning(suppress:4996) // don't complain about wcscpy deprecation
225 wcscpy(double_terminated_path_to
, to_path
.value().c_str());
227 SHFILEOPSTRUCT file_operation
= {0};
228 file_operation
.wFunc
= FO_COPY
;
229 file_operation
.pFrom
= double_terminated_path_from
;
230 file_operation
.pTo
= double_terminated_path_to
;
231 file_operation
.fFlags
= FOF_NOERRORUI
| FOF_SILENT
| FOF_NOCONFIRMATION
|
234 file_operation
.fFlags
|= FOF_NORECURSION
| FOF_FILESONLY
;
236 return (SHFileOperation(&file_operation
) == 0);
239 bool CopyDirectory(const FilePath
& from_path
, const FilePath
& to_path
,
241 base::ThreadRestrictions::AssertIOAllowed();
244 return ShellCopy(from_path
, to_path
, true);
246 // The following code assumes that from path is a directory.
247 DCHECK(DirectoryExists(from_path
));
249 // Instead of creating a new directory, we copy the old one to include the
250 // security information of the folder as part of the copy.
251 if (!PathExists(to_path
)) {
252 // Except that Vista fails to do that, and instead do a recursive copy if
253 // the target directory doesn't exist.
254 if (base::win::GetVersion() >= base::win::VERSION_VISTA
)
255 CreateDirectory(to_path
);
257 ShellCopy(from_path
, to_path
, false);
260 FilePath directory
= from_path
.Append(L
"*.*");
261 return ShellCopy(directory
, to_path
, false);
264 bool CopyAndDeleteDirectory(const FilePath
& from_path
,
265 const FilePath
& to_path
) {
266 base::ThreadRestrictions::AssertIOAllowed();
267 if (CopyDirectory(from_path
, to_path
, true)) {
268 if (Delete(from_path
, true)) {
271 // Like Move, this function is not transactional, so we just
272 // leave the copied bits behind if deleting from_path fails.
273 // If to_path exists previously then we have already overwritten
274 // it by now, we don't get better off by deleting the new bits.
280 bool PathExists(const FilePath
& path
) {
281 base::ThreadRestrictions::AssertIOAllowed();
282 return (GetFileAttributes(path
.value().c_str()) != INVALID_FILE_ATTRIBUTES
);
285 bool PathIsWritable(const FilePath
& path
) {
286 base::ThreadRestrictions::AssertIOAllowed();
288 CreateFile(path
.value().c_str(), FILE_ADD_FILE
, kFileShareAll
,
289 NULL
, OPEN_EXISTING
, FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
291 if (dir
== INVALID_HANDLE_VALUE
)
298 bool DirectoryExists(const FilePath
& path
) {
299 base::ThreadRestrictions::AssertIOAllowed();
300 DWORD fileattr
= GetFileAttributes(path
.value().c_str());
301 if (fileattr
!= INVALID_FILE_ATTRIBUTES
)
302 return (fileattr
& FILE_ATTRIBUTE_DIRECTORY
) != 0;
306 bool GetFileCreationLocalTimeFromHandle(HANDLE file_handle
,
307 LPSYSTEMTIME creation_time
) {
308 base::ThreadRestrictions::AssertIOAllowed();
312 FILETIME utc_filetime
;
313 if (!GetFileTime(file_handle
, &utc_filetime
, NULL
, NULL
))
316 FILETIME local_filetime
;
317 if (!FileTimeToLocalFileTime(&utc_filetime
, &local_filetime
))
320 return !!FileTimeToSystemTime(&local_filetime
, creation_time
);
323 bool GetFileCreationLocalTime(const std::wstring
& filename
,
324 LPSYSTEMTIME creation_time
) {
325 base::ThreadRestrictions::AssertIOAllowed();
326 base::win::ScopedHandle
file_handle(
327 CreateFile(filename
.c_str(), GENERIC_READ
, kFileShareAll
, NULL
,
328 OPEN_EXISTING
, FILE_ATTRIBUTE_NORMAL
, NULL
));
329 return GetFileCreationLocalTimeFromHandle(file_handle
.Get(), creation_time
);
332 bool ResolveShortcut(FilePath
* path
) {
333 base::ThreadRestrictions::AssertIOAllowed();
336 base::win::ScopedComPtr
<IShellLink
> i_shell_link
;
337 bool is_resolved
= false;
339 // Get pointer to the IShellLink interface
340 result
= i_shell_link
.CreateInstance(CLSID_ShellLink
, NULL
,
341 CLSCTX_INPROC_SERVER
);
342 if (SUCCEEDED(result
)) {
343 base::win::ScopedComPtr
<IPersistFile
> persist
;
344 // Query IShellLink for the IPersistFile interface
345 result
= persist
.QueryFrom(i_shell_link
);
346 if (SUCCEEDED(result
)) {
347 WCHAR temp_path
[MAX_PATH
];
348 // Load the shell link
349 result
= persist
->Load(path
->value().c_str(), STGM_READ
);
350 if (SUCCEEDED(result
)) {
351 // Try to find the target of a shortcut
352 result
= i_shell_link
->Resolve(0, SLR_NO_UI
);
353 if (SUCCEEDED(result
)) {
354 result
= i_shell_link
->GetPath(temp_path
, MAX_PATH
,
355 NULL
, SLGP_UNCPRIORITY
);
356 *path
= FilePath(temp_path
);
366 bool CreateShortcutLink(const wchar_t *source
, const wchar_t *destination
,
367 const wchar_t *working_dir
, const wchar_t *arguments
,
368 const wchar_t *description
, const wchar_t *icon
,
369 int icon_index
, const wchar_t* app_id
) {
370 base::ThreadRestrictions::AssertIOAllowed();
372 // Length of arguments and description must be less than MAX_PATH.
373 DCHECK(lstrlen(arguments
) < MAX_PATH
);
374 DCHECK(lstrlen(description
) < MAX_PATH
);
376 base::win::ScopedComPtr
<IShellLink
> i_shell_link
;
377 base::win::ScopedComPtr
<IPersistFile
> i_persist_file
;
379 // Get pointer to the IShellLink interface
380 HRESULT result
= i_shell_link
.CreateInstance(CLSID_ShellLink
, NULL
,
381 CLSCTX_INPROC_SERVER
);
385 // Query IShellLink for the IPersistFile interface
386 result
= i_persist_file
.QueryFrom(i_shell_link
);
390 if (FAILED(i_shell_link
->SetPath(source
)))
393 if (working_dir
&& FAILED(i_shell_link
->SetWorkingDirectory(working_dir
)))
396 if (arguments
&& FAILED(i_shell_link
->SetArguments(arguments
)))
399 if (description
&& FAILED(i_shell_link
->SetDescription(description
)))
402 if (icon
&& FAILED(i_shell_link
->SetIconLocation(icon
, icon_index
)))
405 if (app_id
&& (base::win::GetVersion() >= base::win::VERSION_WIN7
)) {
406 base::win::ScopedComPtr
<IPropertyStore
> property_store
;
407 if (FAILED(property_store
.QueryFrom(i_shell_link
)))
410 if (!base::win::SetAppIdForPropertyStore(property_store
, app_id
))
414 result
= i_persist_file
->Save(destination
, TRUE
);
415 return SUCCEEDED(result
);
418 bool UpdateShortcutLink(const wchar_t *source
, const wchar_t *destination
,
419 const wchar_t *working_dir
, const wchar_t *arguments
,
420 const wchar_t *description
, const wchar_t *icon
,
421 int icon_index
, const wchar_t* app_id
) {
422 base::ThreadRestrictions::AssertIOAllowed();
424 // Length of arguments and description must be less than MAX_PATH.
425 DCHECK(lstrlen(arguments
) < MAX_PATH
);
426 DCHECK(lstrlen(description
) < MAX_PATH
);
428 // Get pointer to the IPersistFile interface and load existing link
429 base::win::ScopedComPtr
<IShellLink
> i_shell_link
;
430 if (FAILED(i_shell_link
.CreateInstance(CLSID_ShellLink
, NULL
,
431 CLSCTX_INPROC_SERVER
)))
434 base::win::ScopedComPtr
<IPersistFile
> i_persist_file
;
435 if (FAILED(i_persist_file
.QueryFrom(i_shell_link
)))
438 if (FAILED(i_persist_file
->Load(destination
, STGM_READWRITE
)))
441 if (source
&& FAILED(i_shell_link
->SetPath(source
)))
444 if (working_dir
&& FAILED(i_shell_link
->SetWorkingDirectory(working_dir
)))
447 if (arguments
&& FAILED(i_shell_link
->SetArguments(arguments
)))
450 if (description
&& FAILED(i_shell_link
->SetDescription(description
)))
453 if (icon
&& FAILED(i_shell_link
->SetIconLocation(icon
, icon_index
)))
456 if (app_id
&& base::win::GetVersion() >= base::win::VERSION_WIN7
) {
457 base::win::ScopedComPtr
<IPropertyStore
> property_store
;
458 if (FAILED(property_store
.QueryFrom(i_shell_link
)))
461 if (!base::win::SetAppIdForPropertyStore(property_store
, app_id
))
465 HRESULT result
= i_persist_file
->Save(destination
, TRUE
);
467 i_persist_file
.Release();
468 i_shell_link
.Release();
470 // If we successfully updated the icon, notify the shell that we have done so.
471 if (SUCCEEDED(result
)) {
472 SHChangeNotify(SHCNE_ASSOCCHANGED
, SHCNF_IDLIST
| SHCNF_FLUSHNOWAIT
,
476 return SUCCEEDED(result
);
479 bool TaskbarPinShortcutLink(const wchar_t* shortcut
) {
480 base::ThreadRestrictions::AssertIOAllowed();
482 // "Pin to taskbar" is only supported after Win7.
483 if (base::win::GetVersion() < base::win::VERSION_WIN7
)
486 int result
= reinterpret_cast<int>(ShellExecute(NULL
, L
"taskbarpin", shortcut
,
491 bool TaskbarUnpinShortcutLink(const wchar_t* shortcut
) {
492 base::ThreadRestrictions::AssertIOAllowed();
494 // "Unpin from taskbar" is only supported after Win7.
495 if (base::win::GetVersion() < base::win::VERSION_WIN7
)
498 int result
= reinterpret_cast<int>(ShellExecute(NULL
, L
"taskbarunpin",
499 shortcut
, NULL
, NULL
, 0));
503 bool GetTempDir(FilePath
* path
) {
504 base::ThreadRestrictions::AssertIOAllowed();
506 wchar_t temp_path
[MAX_PATH
+ 1];
507 DWORD path_len
= ::GetTempPath(MAX_PATH
, temp_path
);
508 if (path_len
>= MAX_PATH
|| path_len
<= 0)
510 // TODO(evanm): the old behavior of this function was to always strip the
511 // trailing slash. We duplicate this here, but it shouldn't be necessary
512 // when everyone is using the appropriate FilePath APIs.
513 *path
= FilePath(temp_path
).StripTrailingSeparators();
517 bool GetShmemTempDir(FilePath
* path
, bool executable
) {
518 return GetTempDir(path
);
521 bool CreateTemporaryFile(FilePath
* path
) {
522 base::ThreadRestrictions::AssertIOAllowed();
526 if (!GetTempDir(path
))
529 if (CreateTemporaryFileInDir(*path
, &temp_file
)) {
537 FILE* CreateAndOpenTemporaryShmemFile(FilePath
* path
, bool executable
) {
538 base::ThreadRestrictions::AssertIOAllowed();
539 return CreateAndOpenTemporaryFile(path
);
542 // On POSIX we have semantics to create and open a temporary file
544 // TODO(jrg): is there equivalent call to use on Windows instead of
546 FILE* CreateAndOpenTemporaryFileInDir(const FilePath
& dir
, FilePath
* path
) {
547 base::ThreadRestrictions::AssertIOAllowed();
548 if (!CreateTemporaryFileInDir(dir
, path
)) {
551 // Open file in binary mode, to avoid problems with fwrite. On Windows
552 // it replaces \n's with \r\n's, which may surprise you.
553 // Reference: http://msdn.microsoft.com/en-us/library/h9t88zwz(VS.71).aspx
554 return OpenFile(*path
, "wb+");
557 bool CreateTemporaryFileInDir(const FilePath
& dir
,
558 FilePath
* temp_file
) {
559 base::ThreadRestrictions::AssertIOAllowed();
561 wchar_t temp_name
[MAX_PATH
+ 1];
563 if (!GetTempFileName(dir
.value().c_str(), L
"", 0, temp_name
)) {
564 DPLOG(WARNING
) << "Failed to get temporary file name in " << dir
.value();
568 DWORD path_len
= GetLongPathName(temp_name
, temp_name
, MAX_PATH
);
569 if (path_len
> MAX_PATH
+ 1 || path_len
== 0) {
570 DPLOG(WARNING
) << "Failed to get long path name for " << temp_name
;
574 std::wstring temp_file_str
;
575 temp_file_str
.assign(temp_name
, path_len
);
576 *temp_file
= FilePath(temp_file_str
);
580 bool CreateTemporaryDirInDir(const FilePath
& base_dir
,
581 const FilePath::StringType
& prefix
,
583 base::ThreadRestrictions::AssertIOAllowed();
585 FilePath path_to_create
;
586 srand(static_cast<uint32
>(time(NULL
)));
588 for (int count
= 0; count
< 50; ++count
) {
589 // Try create a new temporary directory with random generated name. If
590 // the one exists, keep trying another path name until we reach some limit.
591 string16 new_dir_name
;
592 new_dir_name
.assign(prefix
);
593 new_dir_name
.append(base::IntToString16(rand() % kint16max
));
595 path_to_create
= base_dir
.Append(new_dir_name
);
596 if (::CreateDirectory(path_to_create
.value().c_str(), NULL
)) {
597 *new_dir
= path_to_create
;
605 bool CreateNewTempDirectory(const FilePath::StringType
& prefix
,
606 FilePath
* new_temp_path
) {
607 base::ThreadRestrictions::AssertIOAllowed();
609 FilePath system_temp_dir
;
610 if (!GetTempDir(&system_temp_dir
))
613 return CreateTemporaryDirInDir(system_temp_dir
, prefix
, new_temp_path
);
616 bool CreateDirectory(const FilePath
& full_path
) {
617 base::ThreadRestrictions::AssertIOAllowed();
619 // If the path exists, we've succeeded if it's a directory, failed otherwise.
620 const wchar_t* full_path_str
= full_path
.value().c_str();
621 DWORD fileattr
= ::GetFileAttributes(full_path_str
);
622 if (fileattr
!= INVALID_FILE_ATTRIBUTES
) {
623 if ((fileattr
& FILE_ATTRIBUTE_DIRECTORY
) != 0) {
624 DVLOG(1) << "CreateDirectory(" << full_path_str
<< "), "
625 << "directory already exists.";
628 DLOG(WARNING
) << "CreateDirectory(" << full_path_str
<< "), "
629 << "conflicts with existing file.";
633 // Invariant: Path does not exist as file or directory.
635 // Attempt to create the parent recursively. This will immediately return
636 // true if it already exists, otherwise will create all required parent
637 // directories starting with the highest-level missing parent.
638 FilePath
parent_path(full_path
.DirName());
639 if (parent_path
.value() == full_path
.value()) {
642 if (!CreateDirectory(parent_path
)) {
643 DLOG(WARNING
) << "Failed to create one of the parent directories.";
647 if (!::CreateDirectory(full_path_str
, NULL
)) {
648 DWORD error_code
= ::GetLastError();
649 if (error_code
== ERROR_ALREADY_EXISTS
&& DirectoryExists(full_path
)) {
650 // This error code ERROR_ALREADY_EXISTS doesn't indicate whether we
651 // were racing with someone creating the same directory, or a file
652 // with the same path. If DirectoryExists() returns true, we lost the
653 // race to create the same directory.
656 DLOG(WARNING
) << "Failed to create directory " << full_path_str
657 << ", last error is " << error_code
<< ".";
665 // TODO(rkc): Work out if we want to handle NTFS junctions here or not, handle
666 // them if we do decide to.
667 bool IsLink(const FilePath
& file_path
) {
671 bool GetFileInfo(const FilePath
& file_path
, base::PlatformFileInfo
* results
) {
672 base::ThreadRestrictions::AssertIOAllowed();
674 WIN32_FILE_ATTRIBUTE_DATA attr
;
675 if (!GetFileAttributesEx(file_path
.value().c_str(),
676 GetFileExInfoStandard
, &attr
)) {
681 size
.HighPart
= attr
.nFileSizeHigh
;
682 size
.LowPart
= attr
.nFileSizeLow
;
683 results
->size
= size
.QuadPart
;
685 results
->is_directory
=
686 (attr
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
) != 0;
687 results
->last_modified
= base::Time::FromFileTime(attr
.ftLastWriteTime
);
688 results
->last_accessed
= base::Time::FromFileTime(attr
.ftLastAccessTime
);
689 results
->creation_time
= base::Time::FromFileTime(attr
.ftCreationTime
);
694 FILE* OpenFile(const FilePath
& filename
, const char* mode
) {
695 base::ThreadRestrictions::AssertIOAllowed();
696 std::wstring w_mode
= ASCIIToWide(std::string(mode
));
697 return _wfsopen(filename
.value().c_str(), w_mode
.c_str(), _SH_DENYNO
);
700 FILE* OpenFile(const std::string
& filename
, const char* mode
) {
701 base::ThreadRestrictions::AssertIOAllowed();
702 return _fsopen(filename
.c_str(), mode
, _SH_DENYNO
);
705 int ReadFile(const FilePath
& filename
, char* data
, int size
) {
706 base::ThreadRestrictions::AssertIOAllowed();
707 base::win::ScopedHandle
file(CreateFile(filename
.value().c_str(),
709 FILE_SHARE_READ
| FILE_SHARE_WRITE
,
712 FILE_FLAG_SEQUENTIAL_SCAN
,
718 if (::ReadFile(file
, data
, size
, &read
, NULL
) &&
719 static_cast<int>(read
) == size
)
724 int WriteFile(const FilePath
& filename
, const char* data
, int size
) {
725 base::ThreadRestrictions::AssertIOAllowed();
726 base::win::ScopedHandle
file(CreateFile(filename
.value().c_str(),
734 DLOG(WARNING
) << "CreateFile failed for path " << filename
.value()
735 << " error code=" << GetLastError();
740 BOOL result
= ::WriteFile(file
, data
, size
, &written
, NULL
);
741 if (result
&& static_cast<int>(written
) == size
)
746 DLOG(WARNING
) << "writing file " << filename
.value()
747 << " failed, error code=" << GetLastError();
749 // Didn't write all the bytes.
750 DLOG(WARNING
) << "wrote" << written
<< " bytes to "
751 << filename
.value() << " expected " << size
;
756 // Gets the current working directory for the process.
757 bool GetCurrentDirectory(FilePath
* dir
) {
758 base::ThreadRestrictions::AssertIOAllowed();
760 wchar_t system_buffer
[MAX_PATH
];
761 system_buffer
[0] = 0;
762 DWORD len
= ::GetCurrentDirectory(MAX_PATH
, system_buffer
);
763 if (len
== 0 || len
> MAX_PATH
)
765 // TODO(evanm): the old behavior of this function was to always strip the
766 // trailing slash. We duplicate this here, but it shouldn't be necessary
767 // when everyone is using the appropriate FilePath APIs.
768 std::wstring
dir_str(system_buffer
);
769 *dir
= FilePath(dir_str
).StripTrailingSeparators();
773 // Sets the current working directory for the process.
774 bool SetCurrentDirectory(const FilePath
& directory
) {
775 base::ThreadRestrictions::AssertIOAllowed();
776 BOOL ret
= ::SetCurrentDirectory(directory
.value().c_str());
780 ///////////////////////////////////////////////
783 FileEnumerator::FileEnumerator(const FilePath
& root_path
,
786 : recursive_(recursive
),
787 file_type_(file_type
),
788 has_find_data_(false),
789 find_handle_(INVALID_HANDLE_VALUE
) {
790 // INCLUDE_DOT_DOT must not be specified if recursive.
791 DCHECK(!(recursive
&& (INCLUDE_DOT_DOT
& file_type_
)));
792 memset(&find_data_
, 0, sizeof(find_data_
));
793 pending_paths_
.push(root_path
);
796 FileEnumerator::FileEnumerator(const FilePath
& root_path
,
799 const FilePath::StringType
& pattern
)
800 : recursive_(recursive
),
801 file_type_(file_type
),
802 has_find_data_(false),
804 find_handle_(INVALID_HANDLE_VALUE
) {
805 // INCLUDE_DOT_DOT must not be specified if recursive.
806 DCHECK(!(recursive
&& (INCLUDE_DOT_DOT
& file_type_
)));
807 memset(&find_data_
, 0, sizeof(find_data_
));
808 pending_paths_
.push(root_path
);
811 FileEnumerator::~FileEnumerator() {
812 if (find_handle_
!= INVALID_HANDLE_VALUE
)
813 FindClose(find_handle_
);
816 void FileEnumerator::GetFindInfo(FindInfo
* info
) {
822 memcpy(info
, &find_data_
, sizeof(*info
));
825 bool FileEnumerator::IsDirectory(const FindInfo
& info
) {
826 return (info
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
) != 0;
830 FilePath
FileEnumerator::GetFilename(const FindInfo
& find_info
) {
831 return FilePath(find_info
.cFileName
);
835 int64
FileEnumerator::GetFilesize(const FindInfo
& find_info
) {
837 size
.HighPart
= find_info
.nFileSizeHigh
;
838 size
.LowPart
= find_info
.nFileSizeLow
;
839 DCHECK_LE(size
.QuadPart
, std::numeric_limits
<int64
>::max());
840 return static_cast<int64
>(size
.QuadPart
);
844 base::Time
FileEnumerator::GetLastModifiedTime(const FindInfo
& find_info
) {
845 return base::Time::FromFileTime(find_info
.ftLastWriteTime
);
848 FilePath
FileEnumerator::Next() {
849 base::ThreadRestrictions::AssertIOAllowed();
851 while (has_find_data_
|| !pending_paths_
.empty()) {
852 if (!has_find_data_
) {
853 // The last find FindFirstFile operation is done, prepare a new one.
854 root_path_
= pending_paths_
.top();
855 pending_paths_
.pop();
857 // Start a new find operation.
858 FilePath src
= root_path_
;
860 if (pattern_
.empty())
861 src
= src
.Append(L
"*"); // No pattern = match everything.
863 src
= src
.Append(pattern_
);
865 find_handle_
= FindFirstFile(src
.value().c_str(), &find_data_
);
866 has_find_data_
= true;
868 // Search for the next file/directory.
869 if (!FindNextFile(find_handle_
, &find_data_
)) {
870 FindClose(find_handle_
);
871 find_handle_
= INVALID_HANDLE_VALUE
;
875 if (INVALID_HANDLE_VALUE
== find_handle_
) {
876 has_find_data_
= false;
878 // This is reached when we have finished a directory and are advancing to
879 // the next one in the queue. We applied the pattern (if any) to the files
880 // in the root search directory, but for those directories which were
881 // matched, we want to enumerate all files inside them. This will happen
882 // when the handle is empty.
883 pattern_
= FilePath::StringType();
888 FilePath
cur_file(find_data_
.cFileName
);
889 if (ShouldSkip(cur_file
))
892 // Construct the absolute filename.
893 cur_file
= root_path_
.Append(find_data_
.cFileName
);
895 if (find_data_
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
) {
897 // If |cur_file| is a directory, and we are doing recursive searching,
898 // add it to pending_paths_ so we scan it after we finish scanning this
900 pending_paths_
.push(cur_file
);
902 if (file_type_
& FileEnumerator::DIRECTORIES
)
904 } else if (file_type_
& FileEnumerator::FILES
) {
912 ///////////////////////////////////////////////
915 MemoryMappedFile::MemoryMappedFile()
916 : file_(INVALID_HANDLE_VALUE
),
917 file_mapping_(INVALID_HANDLE_VALUE
),
919 length_(INVALID_FILE_SIZE
) {
922 bool MemoryMappedFile::InitializeAsImageSection(const FilePath
& file_name
) {
925 file_
= base::CreatePlatformFile(
926 file_name
, base::PLATFORM_FILE_OPEN
| base::PLATFORM_FILE_READ
,
929 if (file_
== base::kInvalidPlatformFileValue
) {
930 DLOG(ERROR
) << "Couldn't open " << file_name
.value();
934 if (!MapFileToMemoryInternalEx(SEC_IMAGE
)) {
942 bool MemoryMappedFile::MapFileToMemoryInternal() {
943 return MapFileToMemoryInternalEx(0);
946 bool MemoryMappedFile::MapFileToMemoryInternalEx(int flags
) {
947 base::ThreadRestrictions::AssertIOAllowed();
949 if (file_
== INVALID_HANDLE_VALUE
)
952 length_
= ::GetFileSize(file_
, NULL
);
953 if (length_
== INVALID_FILE_SIZE
)
956 file_mapping_
= ::CreateFileMapping(file_
, NULL
, PAGE_READONLY
| flags
,
958 if (!file_mapping_
) {
959 // According to msdn, system error codes are only reserved up to 15999.
960 // http://msdn.microsoft.com/en-us/library/ms681381(v=VS.85).aspx.
961 UMA_HISTOGRAM_ENUMERATION("MemoryMappedFile.CreateFileMapping",
962 logging::GetLastSystemErrorCode(), 16000);
966 data_
= static_cast<uint8
*>(
967 ::MapViewOfFile(file_mapping_
, FILE_MAP_READ
, 0, 0, 0));
969 UMA_HISTOGRAM_ENUMERATION("MemoryMappedFile.MapViewOfFile",
970 logging::GetLastSystemErrorCode(), 16000);
972 return data_
!= NULL
;
975 void MemoryMappedFile::CloseHandles() {
977 ::UnmapViewOfFile(data_
);
978 if (file_mapping_
!= INVALID_HANDLE_VALUE
)
979 ::CloseHandle(file_mapping_
);
980 if (file_
!= INVALID_HANDLE_VALUE
)
981 ::CloseHandle(file_
);
984 file_mapping_
= file_
= INVALID_HANDLE_VALUE
;
985 length_
= INVALID_FILE_SIZE
;
988 bool HasFileBeenModifiedSince(const FileEnumerator::FindInfo
& find_info
,
989 const base::Time
& cutoff_time
) {
990 base::ThreadRestrictions::AssertIOAllowed();
991 FILETIME file_time
= cutoff_time
.ToFileTime();
992 long result
= CompareFileTime(&find_info
.ftLastWriteTime
, // NOLINT
994 return result
== 1 || result
== 0;
997 bool NormalizeFilePath(const FilePath
& path
, FilePath
* real_path
) {
998 base::ThreadRestrictions::AssertIOAllowed();
999 FilePath mapped_file
;
1000 if (!NormalizeToNativeFilePath(path
, &mapped_file
))
1002 // NormalizeToNativeFilePath() will return a path that starts with
1003 // "\Device\Harddisk...". Helper DevicePathToDriveLetterPath()
1004 // will find a drive letter which maps to the path's device, so
1005 // that we return a path starting with a drive letter.
1006 return DevicePathToDriveLetterPath(mapped_file
, real_path
);
1009 bool DevicePathToDriveLetterPath(const FilePath
& nt_device_path
,
1010 FilePath
* out_drive_letter_path
) {
1011 base::ThreadRestrictions::AssertIOAllowed();
1013 // Get the mapping of drive letters to device paths.
1014 const int kDriveMappingSize
= 1024;
1015 wchar_t drive_mapping
[kDriveMappingSize
] = {'\0'};
1016 if (!::GetLogicalDriveStrings(kDriveMappingSize
- 1, drive_mapping
)) {
1017 DLOG(ERROR
) << "Failed to get drive mapping.";
1021 // The drive mapping is a sequence of null terminated strings.
1022 // The last string is empty.
1023 wchar_t* drive_map_ptr
= drive_mapping
;
1024 wchar_t device_path_as_string
[MAX_PATH
];
1025 wchar_t drive
[] = L
" :";
1027 // For each string in the drive mapping, get the junction that links
1028 // to it. If that junction is a prefix of |device_path|, then we
1029 // know that |drive| is the real path prefix.
1030 while (*drive_map_ptr
) {
1031 drive
[0] = drive_map_ptr
[0]; // Copy the drive letter.
1033 if (QueryDosDevice(drive
, device_path_as_string
, MAX_PATH
)) {
1034 FilePath
device_path(device_path_as_string
);
1035 if (device_path
== nt_device_path
||
1036 device_path
.IsParent(nt_device_path
)) {
1037 *out_drive_letter_path
= FilePath(drive
+
1038 nt_device_path
.value().substr(wcslen(device_path_as_string
)));
1042 // Move to the next drive letter string, which starts one
1043 // increment after the '\0' that terminates the current string.
1044 while (*drive_map_ptr
++);
1047 // No drive matched. The path does not start with a device junction
1048 // that is mounted as a drive letter. This means there is no drive
1049 // letter path to the volume that holds |device_path|, so fail.
1053 bool NormalizeToNativeFilePath(const FilePath
& path
, FilePath
* nt_path
) {
1054 base::ThreadRestrictions::AssertIOAllowed();
1055 // In Vista, GetFinalPathNameByHandle() would give us the real path
1056 // from a file handle. If we ever deprecate XP, consider changing the
1057 // code below to a call to GetFinalPathNameByHandle(). The method this
1058 // function uses is explained in the following msdn article:
1059 // http://msdn.microsoft.com/en-us/library/aa366789(VS.85).aspx
1060 base::win::ScopedHandle
file_handle(
1061 ::CreateFile(path
.value().c_str(),
1066 FILE_ATTRIBUTE_NORMAL
,
1071 // Create a file mapping object. Can't easily use MemoryMappedFile, because
1072 // we only map the first byte, and need direct access to the handle. You can
1073 // not map an empty file, this call fails in that case.
1074 base::win::ScopedHandle
file_map_handle(
1075 ::CreateFileMapping(file_handle
.Get(),
1079 1, // Just one byte. No need to look at the data.
1081 if (!file_map_handle
)
1084 // Use a view of the file to get the path to the file.
1085 void* file_view
= MapViewOfFile(file_map_handle
.Get(),
1086 FILE_MAP_READ
, 0, 0, 1);
1090 // The expansion of |path| into a full path may make it longer.
1091 // GetMappedFileName() will fail if the result is longer than MAX_PATH.
1092 // Pad a bit to be safe. If kMaxPathLength is ever changed to be less
1093 // than MAX_PATH, it would be nessisary to test that GetMappedFileName()
1094 // not return kMaxPathLength. This would mean that only part of the
1095 // path fit in |mapped_file_path|.
1096 const int kMaxPathLength
= MAX_PATH
+ 10;
1097 wchar_t mapped_file_path
[kMaxPathLength
];
1098 bool success
= false;
1099 HANDLE cp
= GetCurrentProcess();
1100 if (::GetMappedFileNameW(cp
, file_view
, mapped_file_path
, kMaxPathLength
)) {
1101 *nt_path
= FilePath(mapped_file_path
);
1104 ::UnmapViewOfFile(file_view
);
1108 bool PreReadImage(const wchar_t* file_path
, size_t size_to_read
,
1110 base::ThreadRestrictions::AssertIOAllowed();
1111 if (base::win::GetVersion() > base::win::VERSION_XP
) {
1112 // Vista+ branch. On these OSes, the forced reads through the DLL actually
1113 // slows warm starts. The solution is to sequentially read file contents
1114 // with an optional cap on total amount to read.
1115 base::win::ScopedHandle
file(
1116 CreateFile(file_path
,
1118 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
,
1121 FILE_FLAG_SEQUENTIAL_SCAN
,
1124 if (!file
.IsValid())
1127 // Default to 1MB sequential reads.
1128 const DWORD actual_step_size
= std::max(static_cast<DWORD
>(step_size
),
1129 static_cast<DWORD
>(1024*1024));
1130 LPVOID buffer
= ::VirtualAlloc(NULL
,
1139 size_t total_read
= 0;
1140 while (::ReadFile(file
, buffer
, actual_step_size
, &len
, NULL
) &&
1142 (size_to_read
? total_read
< size_to_read
: true)) {
1143 total_read
+= static_cast<size_t>(len
);
1145 ::VirtualFree(buffer
, 0, MEM_RELEASE
);
1147 // WinXP branch. Here, reading the DLL from disk doesn't do
1148 // what we want so instead we pull the pages into memory by loading
1149 // the DLL and touching pages at a stride.
1150 HMODULE dll_module
= ::LoadLibraryExW(
1153 LOAD_WITH_ALTERED_SEARCH_PATH
| DONT_RESOLVE_DLL_REFERENCES
);
1158 base::win::PEImage
pe_image(dll_module
);
1159 PIMAGE_NT_HEADERS nt_headers
= pe_image
.GetNTHeaders();
1160 size_t actual_size_to_read
= size_to_read
? size_to_read
:
1161 nt_headers
->OptionalHeader
.SizeOfImage
;
1162 volatile uint8
* touch
= reinterpret_cast<uint8
*>(dll_module
);
1164 while (offset
< actual_size_to_read
) {
1165 uint8 unused
= *(touch
+ offset
);
1166 offset
+= step_size
;
1168 FreeLibrary(dll_module
);
1174 } // namespace file_util