1 // Copyright (c) 2011 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>
15 #include "base/file_path.h"
16 #include "base/logging.h"
17 #include "base/metrics/histogram.h"
18 #include "base/win/pe_image.h"
19 #include "base/win/scoped_handle.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_comptr.h"
26 #include "base/win/win_util.h"
27 #include "base/win/windows_version.h"
33 const DWORD kFileShareAll
=
34 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
;
36 // Helper for NormalizeFilePath(), defined below.
37 bool DevicePathToDriveLetterPath(const FilePath
& device_path
,
38 FilePath
* drive_letter_path
) {
39 base::ThreadRestrictions::AssertIOAllowed();
41 // Get the mapping of drive letters to device paths.
42 const int kDriveMappingSize
= 1024;
43 wchar_t drive_mapping
[kDriveMappingSize
] = {'\0'};
44 if (!::GetLogicalDriveStrings(kDriveMappingSize
- 1, drive_mapping
)) {
45 LOG(ERROR
) << "Failed to get drive mapping.";
49 // The drive mapping is a sequence of null terminated strings.
50 // The last string is empty.
51 wchar_t* drive_map_ptr
= drive_mapping
;
52 wchar_t device_name
[MAX_PATH
];
53 wchar_t drive
[] = L
" :";
55 // For each string in the drive mapping, get the junction that links
56 // to it. If that junction is a prefix of |device_path|, then we
57 // know that |drive| is the real path prefix.
58 while (*drive_map_ptr
) {
59 drive
[0] = drive_map_ptr
[0]; // Copy the drive letter.
61 if (QueryDosDevice(drive
, device_name
, MAX_PATH
) &&
62 StartsWith(device_path
.value(), device_name
, true)) {
63 *drive_letter_path
= FilePath(drive
+
64 device_path
.value().substr(wcslen(device_name
)));
67 // Move to the next drive letter string, which starts one
68 // increment after the '\0' that terminates the current string.
69 while (*drive_map_ptr
++);
72 // No drive matched. The path does not start with a device junction
73 // that is mounted as a drive letter. This means there is no drive
74 // letter path to the volume that holds |device_path|, so fail.
80 bool AbsolutePath(FilePath
* path
) {
81 base::ThreadRestrictions::AssertIOAllowed();
82 wchar_t file_path_buf
[MAX_PATH
];
83 if (!_wfullpath(file_path_buf
, path
->value().c_str(), MAX_PATH
))
85 *path
= FilePath(file_path_buf
);
89 int CountFilesCreatedAfter(const FilePath
& path
,
90 const base::Time
& comparison_time
) {
91 base::ThreadRestrictions::AssertIOAllowed();
94 FILETIME
comparison_filetime(comparison_time
.ToFileTime());
96 WIN32_FIND_DATA find_file_data
;
97 // All files in given dir
98 std::wstring filename_spec
= path
.Append(L
"*").value();
99 HANDLE find_handle
= FindFirstFile(filename_spec
.c_str(), &find_file_data
);
100 if (find_handle
!= INVALID_HANDLE_VALUE
) {
102 // Don't count current or parent directories.
103 if ((wcscmp(find_file_data
.cFileName
, L
"..") == 0) ||
104 (wcscmp(find_file_data
.cFileName
, L
".") == 0))
107 long result
= CompareFileTime(&find_file_data
.ftCreationTime
, // NOLINT
108 &comparison_filetime
);
109 // File was created after or on comparison time
110 if ((result
== 1) || (result
== 0))
112 } while (FindNextFile(find_handle
, &find_file_data
));
113 FindClose(find_handle
);
119 bool Delete(const FilePath
& path
, bool recursive
) {
120 base::ThreadRestrictions::AssertIOAllowed();
122 if (path
.value().length() >= MAX_PATH
)
126 // If not recursing, then first check to see if |path| is a directory.
127 // If it is, then remove it with RemoveDirectory.
128 base::PlatformFileInfo file_info
;
129 if (GetFileInfo(path
, &file_info
) && file_info
.is_directory
)
130 return RemoveDirectory(path
.value().c_str()) != 0;
132 // Otherwise, it's a file, wildcard or non-existant. Try DeleteFile first
133 // because it should be faster. If DeleteFile fails, then we fall through
134 // to SHFileOperation, which will do the right thing.
135 if (DeleteFile(path
.value().c_str()) != 0)
139 // SHFILEOPSTRUCT wants the path to be terminated with two NULLs,
140 // so we have to use wcscpy because wcscpy_s writes non-NULLs
141 // into the rest of the buffer.
142 wchar_t double_terminated_path
[MAX_PATH
+ 1] = {0};
143 #pragma warning(suppress:4996) // don't complain about wcscpy deprecation
144 wcscpy(double_terminated_path
, path
.value().c_str());
146 SHFILEOPSTRUCT file_operation
= {0};
147 file_operation
.wFunc
= FO_DELETE
;
148 file_operation
.pFrom
= double_terminated_path
;
149 file_operation
.fFlags
= FOF_NOERRORUI
| FOF_SILENT
| FOF_NOCONFIRMATION
;
151 file_operation
.fFlags
|= FOF_NORECURSION
| FOF_FILESONLY
;
152 int err
= SHFileOperation(&file_operation
);
154 // Since we're passing flags to the operation telling it to be silent,
155 // it's possible for the operation to be aborted/cancelled without err
156 // being set (although MSDN doesn't give any scenarios for how this can
157 // happen). See MSDN for SHFileOperation and SHFILEOPTSTRUCT.
158 if (file_operation
.fAnyOperationsAborted
)
161 // Some versions of Windows return ERROR_FILE_NOT_FOUND (0x2) when deleting
162 // an empty directory and some return 0x402 when they should be returning
163 // ERROR_FILE_NOT_FOUND. MSDN says Vista and up won't return 0x402.
164 return (err
== 0 || err
== ERROR_FILE_NOT_FOUND
|| err
== 0x402);
167 bool DeleteAfterReboot(const FilePath
& path
) {
168 base::ThreadRestrictions::AssertIOAllowed();
170 if (path
.value().length() >= MAX_PATH
)
173 return MoveFileEx(path
.value().c_str(), NULL
,
174 MOVEFILE_DELAY_UNTIL_REBOOT
|
175 MOVEFILE_REPLACE_EXISTING
) != FALSE
;
178 bool Move(const FilePath
& from_path
, const FilePath
& to_path
) {
179 base::ThreadRestrictions::AssertIOAllowed();
181 // NOTE: I suspect we could support longer paths, but that would involve
182 // analyzing all our usage of files.
183 if (from_path
.value().length() >= MAX_PATH
||
184 to_path
.value().length() >= MAX_PATH
) {
187 if (MoveFileEx(from_path
.value().c_str(), to_path
.value().c_str(),
188 MOVEFILE_COPY_ALLOWED
| MOVEFILE_REPLACE_EXISTING
) != 0)
191 // Keep the last error value from MoveFileEx around in case the below
194 DWORD last_error
= ::GetLastError();
196 if (DirectoryExists(from_path
)) {
197 // MoveFileEx fails if moving directory across volumes. We will simulate
198 // the move by using Copy and Delete. Ideally we could check whether
199 // from_path and to_path are indeed in different volumes.
200 ret
= CopyAndDeleteDirectory(from_path
, to_path
);
204 // Leave a clue about what went wrong so that it can be (at least) picked
205 // up by a PLOG entry.
206 ::SetLastError(last_error
);
212 bool ReplaceFile(const FilePath
& from_path
, const FilePath
& to_path
) {
213 base::ThreadRestrictions::AssertIOAllowed();
215 // Make sure that the target file exists.
216 HANDLE target_file
= ::CreateFile(
217 to_path
.value().c_str(),
219 FILE_SHARE_READ
| FILE_SHARE_WRITE
,
222 FILE_ATTRIBUTE_NORMAL
,
224 if (target_file
!= INVALID_HANDLE_VALUE
)
225 ::CloseHandle(target_file
);
226 // When writing to a network share, we may not be able to change the ACLs.
227 // Ignore ACL errors then (REPLACEFILE_IGNORE_MERGE_ERRORS).
228 return ::ReplaceFile(to_path
.value().c_str(),
229 from_path
.value().c_str(), NULL
,
230 REPLACEFILE_IGNORE_MERGE_ERRORS
, NULL
, NULL
) ? true : false;
233 bool CopyFile(const FilePath
& from_path
, const FilePath
& to_path
) {
234 base::ThreadRestrictions::AssertIOAllowed();
236 // NOTE: I suspect we could support longer paths, but that would involve
237 // analyzing all our usage of files.
238 if (from_path
.value().length() >= MAX_PATH
||
239 to_path
.value().length() >= MAX_PATH
) {
242 return (::CopyFile(from_path
.value().c_str(), to_path
.value().c_str(),
246 bool ShellCopy(const FilePath
& from_path
, const FilePath
& to_path
,
248 base::ThreadRestrictions::AssertIOAllowed();
250 // NOTE: I suspect we could support longer paths, but that would involve
251 // analyzing all our usage of files.
252 if (from_path
.value().length() >= MAX_PATH
||
253 to_path
.value().length() >= MAX_PATH
) {
257 // SHFILEOPSTRUCT wants the path to be terminated with two NULLs,
258 // so we have to use wcscpy because wcscpy_s writes non-NULLs
259 // into the rest of the buffer.
260 wchar_t double_terminated_path_from
[MAX_PATH
+ 1] = {0};
261 wchar_t double_terminated_path_to
[MAX_PATH
+ 1] = {0};
262 #pragma warning(suppress:4996) // don't complain about wcscpy deprecation
263 wcscpy(double_terminated_path_from
, from_path
.value().c_str());
264 #pragma warning(suppress:4996) // don't complain about wcscpy deprecation
265 wcscpy(double_terminated_path_to
, to_path
.value().c_str());
267 SHFILEOPSTRUCT file_operation
= {0};
268 file_operation
.wFunc
= FO_COPY
;
269 file_operation
.pFrom
= double_terminated_path_from
;
270 file_operation
.pTo
= double_terminated_path_to
;
271 file_operation
.fFlags
= FOF_NOERRORUI
| FOF_SILENT
| FOF_NOCONFIRMATION
|
274 file_operation
.fFlags
|= FOF_NORECURSION
| FOF_FILESONLY
;
276 return (SHFileOperation(&file_operation
) == 0);
279 bool CopyDirectory(const FilePath
& from_path
, const FilePath
& to_path
,
281 base::ThreadRestrictions::AssertIOAllowed();
284 return ShellCopy(from_path
, to_path
, true);
286 // The following code assumes that from path is a directory.
287 DCHECK(DirectoryExists(from_path
));
289 // Instead of creating a new directory, we copy the old one to include the
290 // security information of the folder as part of the copy.
291 if (!PathExists(to_path
)) {
292 // Except that Vista fails to do that, and instead do a recursive copy if
293 // the target directory doesn't exist.
294 if (base::win::GetVersion() >= base::win::VERSION_VISTA
)
295 CreateDirectory(to_path
);
297 ShellCopy(from_path
, to_path
, false);
300 FilePath directory
= from_path
.Append(L
"*.*");
301 return ShellCopy(directory
, to_path
, false);
304 bool CopyAndDeleteDirectory(const FilePath
& from_path
,
305 const FilePath
& to_path
) {
306 base::ThreadRestrictions::AssertIOAllowed();
307 if (CopyDirectory(from_path
, to_path
, true)) {
308 if (Delete(from_path
, true)) {
311 // Like Move, this function is not transactional, so we just
312 // leave the copied bits behind if deleting from_path fails.
313 // If to_path exists previously then we have already overwritten
314 // it by now, we don't get better off by deleting the new bits.
320 bool PathExists(const FilePath
& path
) {
321 base::ThreadRestrictions::AssertIOAllowed();
322 return (GetFileAttributes(path
.value().c_str()) != INVALID_FILE_ATTRIBUTES
);
325 bool PathIsWritable(const FilePath
& path
) {
326 base::ThreadRestrictions::AssertIOAllowed();
328 CreateFile(path
.value().c_str(), FILE_ADD_FILE
, kFileShareAll
,
329 NULL
, OPEN_EXISTING
, FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
331 if (dir
== INVALID_HANDLE_VALUE
)
338 bool DirectoryExists(const FilePath
& path
) {
339 base::ThreadRestrictions::AssertIOAllowed();
340 DWORD fileattr
= GetFileAttributes(path
.value().c_str());
341 if (fileattr
!= INVALID_FILE_ATTRIBUTES
)
342 return (fileattr
& FILE_ATTRIBUTE_DIRECTORY
) != 0;
346 bool GetFileCreationLocalTimeFromHandle(HANDLE file_handle
,
347 LPSYSTEMTIME creation_time
) {
348 base::ThreadRestrictions::AssertIOAllowed();
352 FILETIME utc_filetime
;
353 if (!GetFileTime(file_handle
, &utc_filetime
, NULL
, NULL
))
356 FILETIME local_filetime
;
357 if (!FileTimeToLocalFileTime(&utc_filetime
, &local_filetime
))
360 return !!FileTimeToSystemTime(&local_filetime
, creation_time
);
363 bool GetFileCreationLocalTime(const std::wstring
& filename
,
364 LPSYSTEMTIME creation_time
) {
365 base::ThreadRestrictions::AssertIOAllowed();
366 base::win::ScopedHandle
file_handle(
367 CreateFile(filename
.c_str(), GENERIC_READ
, kFileShareAll
, NULL
,
368 OPEN_EXISTING
, FILE_ATTRIBUTE_NORMAL
, NULL
));
369 return GetFileCreationLocalTimeFromHandle(file_handle
.Get(), creation_time
);
372 bool ResolveShortcut(FilePath
* path
) {
373 base::ThreadRestrictions::AssertIOAllowed();
376 base::win::ScopedComPtr
<IShellLink
> i_shell_link
;
377 bool is_resolved
= false;
379 // Get pointer to the IShellLink interface
380 result
= i_shell_link
.CreateInstance(CLSID_ShellLink
, NULL
,
381 CLSCTX_INPROC_SERVER
);
382 if (SUCCEEDED(result
)) {
383 base::win::ScopedComPtr
<IPersistFile
> persist
;
384 // Query IShellLink for the IPersistFile interface
385 result
= persist
.QueryFrom(i_shell_link
);
386 if (SUCCEEDED(result
)) {
387 WCHAR temp_path
[MAX_PATH
];
388 // Load the shell link
389 result
= persist
->Load(path
->value().c_str(), STGM_READ
);
390 if (SUCCEEDED(result
)) {
391 // Try to find the target of a shortcut
392 result
= i_shell_link
->Resolve(0, SLR_NO_UI
);
393 if (SUCCEEDED(result
)) {
394 result
= i_shell_link
->GetPath(temp_path
, MAX_PATH
,
395 NULL
, SLGP_UNCPRIORITY
);
396 *path
= FilePath(temp_path
);
406 bool CreateShortcutLink(const wchar_t *source
, const wchar_t *destination
,
407 const wchar_t *working_dir
, const wchar_t *arguments
,
408 const wchar_t *description
, const wchar_t *icon
,
409 int icon_index
, const wchar_t* app_id
) {
410 base::ThreadRestrictions::AssertIOAllowed();
412 // Length of arguments and description must be less than MAX_PATH.
413 DCHECK(lstrlen(arguments
) < MAX_PATH
);
414 DCHECK(lstrlen(description
) < MAX_PATH
);
416 base::win::ScopedComPtr
<IShellLink
> i_shell_link
;
417 base::win::ScopedComPtr
<IPersistFile
> i_persist_file
;
419 // Get pointer to the IShellLink interface
420 HRESULT result
= i_shell_link
.CreateInstance(CLSID_ShellLink
, NULL
,
421 CLSCTX_INPROC_SERVER
);
425 // Query IShellLink for the IPersistFile interface
426 result
= i_persist_file
.QueryFrom(i_shell_link
);
430 if (FAILED(i_shell_link
->SetPath(source
)))
433 if (working_dir
&& FAILED(i_shell_link
->SetWorkingDirectory(working_dir
)))
436 if (arguments
&& FAILED(i_shell_link
->SetArguments(arguments
)))
439 if (description
&& FAILED(i_shell_link
->SetDescription(description
)))
442 if (icon
&& FAILED(i_shell_link
->SetIconLocation(icon
, icon_index
)))
445 if (app_id
&& (base::win::GetVersion() >= base::win::VERSION_WIN7
)) {
446 base::win::ScopedComPtr
<IPropertyStore
> property_store
;
447 if (FAILED(property_store
.QueryFrom(i_shell_link
)))
450 if (!base::win::SetAppIdForPropertyStore(property_store
, app_id
))
454 result
= i_persist_file
->Save(destination
, TRUE
);
455 return SUCCEEDED(result
);
458 bool UpdateShortcutLink(const wchar_t *source
, const wchar_t *destination
,
459 const wchar_t *working_dir
, const wchar_t *arguments
,
460 const wchar_t *description
, const wchar_t *icon
,
461 int icon_index
, const wchar_t* app_id
) {
462 base::ThreadRestrictions::AssertIOAllowed();
464 // Length of arguments and description must be less than MAX_PATH.
465 DCHECK(lstrlen(arguments
) < MAX_PATH
);
466 DCHECK(lstrlen(description
) < MAX_PATH
);
468 // Get pointer to the IPersistFile interface and load existing link
469 base::win::ScopedComPtr
<IShellLink
> i_shell_link
;
470 if (FAILED(i_shell_link
.CreateInstance(CLSID_ShellLink
, NULL
,
471 CLSCTX_INPROC_SERVER
)))
474 base::win::ScopedComPtr
<IPersistFile
> i_persist_file
;
475 if (FAILED(i_persist_file
.QueryFrom(i_shell_link
)))
478 if (FAILED(i_persist_file
->Load(destination
, STGM_READWRITE
)))
481 if (source
&& FAILED(i_shell_link
->SetPath(source
)))
484 if (working_dir
&& FAILED(i_shell_link
->SetWorkingDirectory(working_dir
)))
487 if (arguments
&& FAILED(i_shell_link
->SetArguments(arguments
)))
490 if (description
&& FAILED(i_shell_link
->SetDescription(description
)))
493 if (icon
&& FAILED(i_shell_link
->SetIconLocation(icon
, icon_index
)))
496 if (app_id
&& base::win::GetVersion() >= base::win::VERSION_WIN7
) {
497 base::win::ScopedComPtr
<IPropertyStore
> property_store
;
498 if (FAILED(property_store
.QueryFrom(i_shell_link
)))
501 if (!base::win::SetAppIdForPropertyStore(property_store
, app_id
))
505 HRESULT result
= i_persist_file
->Save(destination
, TRUE
);
507 i_persist_file
.Release();
508 i_shell_link
.Release();
510 // If we successfully updated the icon, notify the shell that we have done so.
511 if (SUCCEEDED(result
)) {
512 SHChangeNotify(SHCNE_ASSOCCHANGED
, SHCNF_IDLIST
| SHCNF_FLUSHNOWAIT
,
516 return SUCCEEDED(result
);
519 bool TaskbarPinShortcutLink(const wchar_t* shortcut
) {
520 base::ThreadRestrictions::AssertIOAllowed();
522 // "Pin to taskbar" is only supported after Win7.
523 if (base::win::GetVersion() < base::win::VERSION_WIN7
)
526 int result
= reinterpret_cast<int>(ShellExecute(NULL
, L
"taskbarpin", shortcut
,
531 bool TaskbarUnpinShortcutLink(const wchar_t* shortcut
) {
532 base::ThreadRestrictions::AssertIOAllowed();
534 // "Unpin from taskbar" is only supported after Win7.
535 if (base::win::GetVersion() < base::win::VERSION_WIN7
)
538 int result
= reinterpret_cast<int>(ShellExecute(NULL
, L
"taskbarunpin",
539 shortcut
, NULL
, NULL
, 0));
543 bool GetTempDir(FilePath
* path
) {
544 base::ThreadRestrictions::AssertIOAllowed();
546 wchar_t temp_path
[MAX_PATH
+ 1];
547 DWORD path_len
= ::GetTempPath(MAX_PATH
, temp_path
);
548 if (path_len
>= MAX_PATH
|| path_len
<= 0)
550 // TODO(evanm): the old behavior of this function was to always strip the
551 // trailing slash. We duplicate this here, but it shouldn't be necessary
552 // when everyone is using the appropriate FilePath APIs.
553 *path
= FilePath(temp_path
).StripTrailingSeparators();
557 bool GetShmemTempDir(FilePath
* path
) {
558 return GetTempDir(path
);
561 bool CreateTemporaryFile(FilePath
* path
) {
562 base::ThreadRestrictions::AssertIOAllowed();
566 if (!GetTempDir(path
))
569 if (CreateTemporaryFileInDir(*path
, &temp_file
)) {
577 FILE* CreateAndOpenTemporaryShmemFile(FilePath
* path
) {
578 base::ThreadRestrictions::AssertIOAllowed();
579 return CreateAndOpenTemporaryFile(path
);
582 // On POSIX we have semantics to create and open a temporary file
584 // TODO(jrg): is there equivalent call to use on Windows instead of
586 FILE* CreateAndOpenTemporaryFileInDir(const FilePath
& dir
, FilePath
* path
) {
587 base::ThreadRestrictions::AssertIOAllowed();
588 if (!CreateTemporaryFileInDir(dir
, path
)) {
591 // Open file in binary mode, to avoid problems with fwrite. On Windows
592 // it replaces \n's with \r\n's, which may surprise you.
593 // Reference: http://msdn.microsoft.com/en-us/library/h9t88zwz(VS.71).aspx
594 return OpenFile(*path
, "wb+");
597 bool CreateTemporaryFileInDir(const FilePath
& dir
,
598 FilePath
* temp_file
) {
599 base::ThreadRestrictions::AssertIOAllowed();
601 wchar_t temp_name
[MAX_PATH
+ 1];
603 if (!GetTempFileName(dir
.value().c_str(), L
"", 0, temp_name
)) {
604 PLOG(WARNING
) << "Failed to get temporary file name in " << dir
.value();
608 DWORD path_len
= GetLongPathName(temp_name
, temp_name
, MAX_PATH
);
609 if (path_len
> MAX_PATH
+ 1 || path_len
== 0) {
610 PLOG(WARNING
) << "Failed to get long path name for " << temp_name
;
614 std::wstring temp_file_str
;
615 temp_file_str
.assign(temp_name
, path_len
);
616 *temp_file
= FilePath(temp_file_str
);
620 bool CreateTemporaryDirInDir(const FilePath
& base_dir
,
621 const FilePath::StringType
& prefix
,
623 base::ThreadRestrictions::AssertIOAllowed();
625 FilePath path_to_create
;
626 srand(static_cast<uint32
>(time(NULL
)));
628 for (int count
= 0; count
< 50; ++count
) {
629 // Try create a new temporary directory with random generated name. If
630 // the one exists, keep trying another path name until we reach some limit.
631 string16 new_dir_name
;
632 new_dir_name
.assign(prefix
);
633 new_dir_name
.append(base::IntToString16(rand() % kint16max
));
635 path_to_create
= base_dir
.Append(new_dir_name
);
636 if (::CreateDirectory(path_to_create
.value().c_str(), NULL
)) {
637 *new_dir
= path_to_create
;
645 bool CreateNewTempDirectory(const FilePath::StringType
& prefix
,
646 FilePath
* new_temp_path
) {
647 base::ThreadRestrictions::AssertIOAllowed();
649 FilePath system_temp_dir
;
650 if (!GetTempDir(&system_temp_dir
))
653 return CreateTemporaryDirInDir(system_temp_dir
, prefix
, new_temp_path
);
656 bool CreateDirectory(const FilePath
& full_path
) {
657 base::ThreadRestrictions::AssertIOAllowed();
659 // If the path exists, we've succeeded if it's a directory, failed otherwise.
660 const wchar_t* full_path_str
= full_path
.value().c_str();
661 DWORD fileattr
= ::GetFileAttributes(full_path_str
);
662 if (fileattr
!= INVALID_FILE_ATTRIBUTES
) {
663 if ((fileattr
& FILE_ATTRIBUTE_DIRECTORY
) != 0) {
664 DVLOG(1) << "CreateDirectory(" << full_path_str
<< "), "
665 << "directory already exists.";
668 LOG(WARNING
) << "CreateDirectory(" << full_path_str
<< "), "
669 << "conflicts with existing file.";
673 // Invariant: Path does not exist as file or directory.
675 // Attempt to create the parent recursively. This will immediately return
676 // true if it already exists, otherwise will create all required parent
677 // directories starting with the highest-level missing parent.
678 FilePath
parent_path(full_path
.DirName());
679 if (parent_path
.value() == full_path
.value()) {
682 if (!CreateDirectory(parent_path
)) {
683 DLOG(WARNING
) << "Failed to create one of the parent directories.";
687 if (!::CreateDirectory(full_path_str
, NULL
)) {
688 DWORD error_code
= ::GetLastError();
689 if (error_code
== ERROR_ALREADY_EXISTS
&& DirectoryExists(full_path
)) {
690 // This error code ERROR_ALREADY_EXISTS doesn't indicate whether we
691 // were racing with someone creating the same directory, or a file
692 // with the same path. If DirectoryExists() returns true, we lost the
693 // race to create the same directory.
696 LOG(WARNING
) << "Failed to create directory " << full_path_str
697 << ", last error is " << error_code
<< ".";
705 // TODO(rkc): Work out if we want to handle NTFS junctions here or not, handle
706 // them if we do decide to.
707 bool IsLink(const FilePath
& file_path
) {
711 bool GetFileInfo(const FilePath
& file_path
, base::PlatformFileInfo
* results
) {
712 base::ThreadRestrictions::AssertIOAllowed();
714 WIN32_FILE_ATTRIBUTE_DATA attr
;
715 if (!GetFileAttributesEx(file_path
.value().c_str(),
716 GetFileExInfoStandard
, &attr
)) {
721 size
.HighPart
= attr
.nFileSizeHigh
;
722 size
.LowPart
= attr
.nFileSizeLow
;
723 results
->size
= size
.QuadPart
;
725 results
->is_directory
=
726 (attr
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
) != 0;
727 results
->last_modified
= base::Time::FromFileTime(attr
.ftLastWriteTime
);
728 results
->last_accessed
= base::Time::FromFileTime(attr
.ftLastAccessTime
);
729 results
->creation_time
= base::Time::FromFileTime(attr
.ftCreationTime
);
734 FILE* OpenFile(const FilePath
& filename
, const char* mode
) {
735 base::ThreadRestrictions::AssertIOAllowed();
736 std::wstring w_mode
= ASCIIToWide(std::string(mode
));
737 return _wfsopen(filename
.value().c_str(), w_mode
.c_str(), _SH_DENYNO
);
740 FILE* OpenFile(const std::string
& filename
, const char* mode
) {
741 base::ThreadRestrictions::AssertIOAllowed();
742 return _fsopen(filename
.c_str(), mode
, _SH_DENYNO
);
745 int ReadFile(const FilePath
& filename
, char* data
, int size
) {
746 base::ThreadRestrictions::AssertIOAllowed();
747 base::win::ScopedHandle
file(CreateFile(filename
.value().c_str(),
749 FILE_SHARE_READ
| FILE_SHARE_WRITE
,
752 FILE_FLAG_SEQUENTIAL_SCAN
,
758 if (::ReadFile(file
, data
, size
, &read
, NULL
) &&
759 static_cast<int>(read
) == size
)
764 int WriteFile(const FilePath
& filename
, const char* data
, int size
) {
765 base::ThreadRestrictions::AssertIOAllowed();
766 base::win::ScopedHandle
file(CreateFile(filename
.value().c_str(),
774 LOG(WARNING
) << "CreateFile failed for path " << filename
.value()
775 << " error code=" << GetLastError();
780 BOOL result
= ::WriteFile(file
, data
, size
, &written
, NULL
);
781 if (result
&& static_cast<int>(written
) == size
)
786 LOG(WARNING
) << "writing file " << filename
.value()
787 << " failed, error code=" << GetLastError();
789 // Didn't write all the bytes.
790 LOG(WARNING
) << "wrote" << written
<< " bytes to " <<
791 filename
.value() << " expected " << size
;
796 bool RenameFileAndResetSecurityDescriptor(const FilePath
& source_file_path
,
797 const FilePath
& target_file_path
) {
798 base::ThreadRestrictions::AssertIOAllowed();
800 // The parameters to SHFileOperation must be terminated with 2 NULL chars.
801 std::wstring source
= source_file_path
.value();
802 std::wstring target
= target_file_path
.value();
804 source
.append(1, L
'\0');
805 target
.append(1, L
'\0');
807 SHFILEOPSTRUCT move_info
= {0};
808 move_info
.wFunc
= FO_MOVE
;
809 move_info
.pFrom
= source
.c_str();
810 move_info
.pTo
= target
.c_str();
811 move_info
.fFlags
= FOF_SILENT
| FOF_NOCONFIRMATION
| FOF_NOERRORUI
|
812 FOF_NOCONFIRMMKDIR
| FOF_NOCOPYSECURITYATTRIBS
;
814 if (0 != SHFileOperation(&move_info
))
820 // Gets the current working directory for the process.
821 bool GetCurrentDirectory(FilePath
* dir
) {
822 base::ThreadRestrictions::AssertIOAllowed();
824 wchar_t system_buffer
[MAX_PATH
];
825 system_buffer
[0] = 0;
826 DWORD len
= ::GetCurrentDirectory(MAX_PATH
, system_buffer
);
827 if (len
== 0 || len
> MAX_PATH
)
829 // TODO(evanm): the old behavior of this function was to always strip the
830 // trailing slash. We duplicate this here, but it shouldn't be necessary
831 // when everyone is using the appropriate FilePath APIs.
832 std::wstring
dir_str(system_buffer
);
833 *dir
= FilePath(dir_str
).StripTrailingSeparators();
837 // Sets the current working directory for the process.
838 bool SetCurrentDirectory(const FilePath
& directory
) {
839 base::ThreadRestrictions::AssertIOAllowed();
840 BOOL ret
= ::SetCurrentDirectory(directory
.value().c_str());
844 ///////////////////////////////////////////////
847 FileEnumerator::FileEnumerator(const FilePath
& root_path
,
849 FileEnumerator::FILE_TYPE file_type
)
850 : recursive_(recursive
),
851 file_type_(file_type
),
852 has_find_data_(false),
853 find_handle_(INVALID_HANDLE_VALUE
) {
854 // INCLUDE_DOT_DOT must not be specified if recursive.
855 DCHECK(!(recursive
&& (INCLUDE_DOT_DOT
& file_type_
)));
856 pending_paths_
.push(root_path
);
859 FileEnumerator::FileEnumerator(const FilePath
& root_path
,
861 FileEnumerator::FILE_TYPE file_type
,
862 const FilePath::StringType
& pattern
)
863 : recursive_(recursive
),
864 file_type_(file_type
),
865 has_find_data_(false),
867 find_handle_(INVALID_HANDLE_VALUE
) {
868 // INCLUDE_DOT_DOT must not be specified if recursive.
869 DCHECK(!(recursive
&& (INCLUDE_DOT_DOT
& file_type_
)));
870 pending_paths_
.push(root_path
);
873 FileEnumerator::~FileEnumerator() {
874 if (find_handle_
!= INVALID_HANDLE_VALUE
)
875 FindClose(find_handle_
);
878 void FileEnumerator::GetFindInfo(FindInfo
* info
) {
884 memcpy(info
, &find_data_
, sizeof(*info
));
887 bool FileEnumerator::IsDirectory(const FindInfo
& info
) {
888 return (info
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
) != 0;
892 FilePath
FileEnumerator::GetFilename(const FindInfo
& find_info
) {
893 return FilePath(find_info
.cFileName
);
896 FilePath
FileEnumerator::Next() {
897 base::ThreadRestrictions::AssertIOAllowed();
899 while (has_find_data_
|| !pending_paths_
.empty()) {
900 if (!has_find_data_
) {
901 // The last find FindFirstFile operation is done, prepare a new one.
902 root_path_
= pending_paths_
.top();
903 pending_paths_
.pop();
905 // Start a new find operation.
906 FilePath src
= root_path_
;
908 if (pattern_
.empty())
909 src
= src
.Append(L
"*"); // No pattern = match everything.
911 src
= src
.Append(pattern_
);
913 find_handle_
= FindFirstFile(src
.value().c_str(), &find_data_
);
914 has_find_data_
= true;
916 // Search for the next file/directory.
917 if (!FindNextFile(find_handle_
, &find_data_
)) {
918 FindClose(find_handle_
);
919 find_handle_
= INVALID_HANDLE_VALUE
;
923 if (INVALID_HANDLE_VALUE
== find_handle_
) {
924 has_find_data_
= false;
926 // This is reached when we have finished a directory and are advancing to
927 // the next one in the queue. We applied the pattern (if any) to the files
928 // in the root search directory, but for those directories which were
929 // matched, we want to enumerate all files inside them. This will happen
930 // when the handle is empty.
931 pattern_
= FilePath::StringType();
936 FilePath
cur_file(find_data_
.cFileName
);
937 if (ShouldSkip(cur_file
))
940 // Construct the absolute filename.
941 cur_file
= root_path_
.Append(find_data_
.cFileName
);
943 if (find_data_
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
) {
945 // If |cur_file| is a directory, and we are doing recursive searching,
946 // add it to pending_paths_ so we scan it after we finish scanning this
948 pending_paths_
.push(cur_file
);
950 if (file_type_
& FileEnumerator::DIRECTORIES
)
952 } else if (file_type_
& FileEnumerator::FILES
) {
960 ///////////////////////////////////////////////
963 MemoryMappedFile::MemoryMappedFile()
964 : file_(INVALID_HANDLE_VALUE
),
965 file_mapping_(INVALID_HANDLE_VALUE
),
967 length_(INVALID_FILE_SIZE
) {
970 bool MemoryMappedFile::InitializeAsImageSection(const FilePath
& file_name
) {
973 file_
= base::CreatePlatformFile(
974 file_name
, base::PLATFORM_FILE_OPEN
| base::PLATFORM_FILE_READ
,
977 if (file_
== base::kInvalidPlatformFileValue
) {
978 LOG(ERROR
) << "Couldn't open " << file_name
.value();
982 if (!MapFileToMemoryInternalEx(SEC_IMAGE
)) {
990 bool MemoryMappedFile::MapFileToMemoryInternal() {
991 return MapFileToMemoryInternalEx(0);
994 bool MemoryMappedFile::MapFileToMemoryInternalEx(int flags
) {
995 base::ThreadRestrictions::AssertIOAllowed();
997 if (file_
== INVALID_HANDLE_VALUE
)
1000 length_
= ::GetFileSize(file_
, NULL
);
1001 if (length_
== INVALID_FILE_SIZE
)
1004 file_mapping_
= ::CreateFileMapping(file_
, NULL
, PAGE_READONLY
| flags
,
1006 if (!file_mapping_
) {
1007 // According to msdn, system error codes are only reserved up to 15999.
1008 // http://msdn.microsoft.com/en-us/library/ms681381(v=VS.85).aspx.
1009 UMA_HISTOGRAM_ENUMERATION("MemoryMappedFile.CreateFileMapping",
1010 logging::GetLastSystemErrorCode(), 16000);
1014 data_
= static_cast<uint8
*>(
1015 ::MapViewOfFile(file_mapping_
, FILE_MAP_READ
, 0, 0, 0));
1017 UMA_HISTOGRAM_ENUMERATION("MemoryMappedFile.MapViewOfFile",
1018 logging::GetLastSystemErrorCode(), 16000);
1020 return data_
!= NULL
;
1023 void MemoryMappedFile::CloseHandles() {
1025 ::UnmapViewOfFile(data_
);
1026 if (file_mapping_
!= INVALID_HANDLE_VALUE
)
1027 ::CloseHandle(file_mapping_
);
1028 if (file_
!= INVALID_HANDLE_VALUE
)
1029 ::CloseHandle(file_
);
1032 file_mapping_
= file_
= INVALID_HANDLE_VALUE
;
1033 length_
= INVALID_FILE_SIZE
;
1036 bool HasFileBeenModifiedSince(const FileEnumerator::FindInfo
& find_info
,
1037 const base::Time
& cutoff_time
) {
1038 base::ThreadRestrictions::AssertIOAllowed();
1039 long result
= CompareFileTime(&find_info
.ftLastWriteTime
, // NOLINT
1040 &cutoff_time
.ToFileTime());
1041 return result
== 1 || result
== 0;
1044 bool NormalizeFilePath(const FilePath
& path
, FilePath
* real_path
) {
1045 base::ThreadRestrictions::AssertIOAllowed();
1046 FilePath mapped_file
;
1047 if (!NormalizeToNativeFilePath(path
, &mapped_file
))
1049 // NormalizeToNativeFilePath() will return a path that starts with
1050 // "\Device\Harddisk...". Helper DevicePathToDriveLetterPath()
1051 // will find a drive letter which maps to the path's device, so
1052 // that we return a path starting with a drive letter.
1053 return DevicePathToDriveLetterPath(mapped_file
, real_path
);
1056 bool NormalizeToNativeFilePath(const FilePath
& path
, FilePath
* nt_path
) {
1057 base::ThreadRestrictions::AssertIOAllowed();
1058 // In Vista, GetFinalPathNameByHandle() would give us the real path
1059 // from a file handle. If we ever deprecate XP, consider changing the
1060 // code below to a call to GetFinalPathNameByHandle(). The method this
1061 // function uses is explained in the following msdn article:
1062 // http://msdn.microsoft.com/en-us/library/aa366789(VS.85).aspx
1063 base::win::ScopedHandle
file_handle(
1064 ::CreateFile(path
.value().c_str(),
1069 FILE_ATTRIBUTE_NORMAL
,
1074 // Create a file mapping object. Can't easily use MemoryMappedFile, because
1075 // we only map the first byte, and need direct access to the handle. You can
1076 // not map an empty file, this call fails in that case.
1077 base::win::ScopedHandle
file_map_handle(
1078 ::CreateFileMapping(file_handle
.Get(),
1082 1, // Just one byte. No need to look at the data.
1084 if (!file_map_handle
)
1087 // Use a view of the file to get the path to the file.
1088 void* file_view
= MapViewOfFile(file_map_handle
.Get(),
1089 FILE_MAP_READ
, 0, 0, 1);
1093 // The expansion of |path| into a full path may make it longer.
1094 // GetMappedFileName() will fail if the result is longer than MAX_PATH.
1095 // Pad a bit to be safe. If kMaxPathLength is ever changed to be less
1096 // than MAX_PATH, it would be nessisary to test that GetMappedFileName()
1097 // not return kMaxPathLength. This would mean that only part of the
1098 // path fit in |mapped_file_path|.
1099 const int kMaxPathLength
= MAX_PATH
+ 10;
1100 wchar_t mapped_file_path
[kMaxPathLength
];
1101 bool success
= false;
1102 HANDLE cp
= GetCurrentProcess();
1103 if (::GetMappedFileNameW(cp
, file_view
, mapped_file_path
, kMaxPathLength
)) {
1104 *nt_path
= FilePath(mapped_file_path
);
1107 ::UnmapViewOfFile(file_view
);
1111 bool PreReadImage(const wchar_t* file_path
, size_t size_to_read
,
1113 base::ThreadRestrictions::AssertIOAllowed();
1114 if (base::win::GetVersion() > base::win::VERSION_XP
) {
1115 // Vista+ branch. On these OSes, the forced reads through the DLL actually
1116 // slows warm starts. The solution is to sequentially read file contents
1117 // with an optional cap on total amount to read.
1118 base::win::ScopedHandle
file(
1119 CreateFile(file_path
,
1121 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
,
1124 FILE_FLAG_SEQUENTIAL_SCAN
,
1127 if (!file
.IsValid())
1130 // Default to 1MB sequential reads.
1131 const DWORD actual_step_size
= std::max(static_cast<DWORD
>(step_size
),
1132 static_cast<DWORD
>(1024*1024));
1133 LPVOID buffer
= ::VirtualAlloc(NULL
,
1142 size_t total_read
= 0;
1143 while (::ReadFile(file
, buffer
, actual_step_size
, &len
, NULL
) &&
1145 (size_to_read
? total_read
< size_to_read
: true)) {
1146 total_read
+= static_cast<size_t>(len
);
1148 ::VirtualFree(buffer
, 0, MEM_RELEASE
);
1150 // WinXP branch. Here, reading the DLL from disk doesn't do
1151 // what we want so instead we pull the pages into memory by loading
1152 // the DLL and touching pages at a stride.
1153 HMODULE dll_module
= ::LoadLibraryExW(
1156 LOAD_WITH_ALTERED_SEARCH_PATH
| DONT_RESOLVE_DLL_REFERENCES
);
1161 base::win::PEImage
pe_image(dll_module
);
1162 PIMAGE_NT_HEADERS nt_headers
= pe_image
.GetNTHeaders();
1163 size_t actual_size_to_read
= size_to_read
? size_to_read
:
1164 nt_headers
->OptionalHeader
.SizeOfImage
;
1165 volatile uint8
* touch
= reinterpret_cast<uint8
*>(dll_module
);
1167 while (offset
< actual_size_to_read
) {
1168 uint8 unused
= *(touch
+ offset
);
1169 offset
+= step_size
;
1171 FreeLibrary(dll_module
);
1177 } // namespace file_util