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>
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
;
38 // Helper for NormalizeFilePath(), defined below.
39 bool DevicePathToDriveLetterPath(const FilePath
& device_path
,
40 FilePath
* drive_letter_path
) {
41 base::ThreadRestrictions::AssertIOAllowed();
43 // Get the mapping of drive letters to device paths.
44 const int kDriveMappingSize
= 1024;
45 wchar_t drive_mapping
[kDriveMappingSize
] = {'\0'};
46 if (!::GetLogicalDriveStrings(kDriveMappingSize
- 1, drive_mapping
)) {
47 LOG(ERROR
) << "Failed to get drive mapping.";
51 // The drive mapping is a sequence of null terminated strings.
52 // The last string is empty.
53 wchar_t* drive_map_ptr
= drive_mapping
;
54 wchar_t device_name
[MAX_PATH
];
55 wchar_t drive
[] = L
" :";
57 // For each string in the drive mapping, get the junction that links
58 // to it. If that junction is a prefix of |device_path|, then we
59 // know that |drive| is the real path prefix.
60 while (*drive_map_ptr
) {
61 drive
[0] = drive_map_ptr
[0]; // Copy the drive letter.
63 if (QueryDosDevice(drive
, device_name
, MAX_PATH
) &&
64 StartsWith(device_path
.value(), device_name
, true)) {
65 *drive_letter_path
= FilePath(drive
+
66 device_path
.value().substr(wcslen(device_name
)));
69 // Move to the next drive letter string, which starts one
70 // increment after the '\0' that terminates the current string.
71 while (*drive_map_ptr
++);
74 // No drive matched. The path does not start with a device junction
75 // that is mounted as a drive letter. This means there is no drive
76 // letter path to the volume that holds |device_path|, so fail.
82 bool AbsolutePath(FilePath
* path
) {
83 base::ThreadRestrictions::AssertIOAllowed();
84 wchar_t file_path_buf
[MAX_PATH
];
85 if (!_wfullpath(file_path_buf
, path
->value().c_str(), MAX_PATH
))
87 *path
= FilePath(file_path_buf
);
91 int CountFilesCreatedAfter(const FilePath
& path
,
92 const base::Time
& comparison_time
) {
93 base::ThreadRestrictions::AssertIOAllowed();
96 FILETIME
comparison_filetime(comparison_time
.ToFileTime());
98 WIN32_FIND_DATA find_file_data
;
99 // All files in given dir
100 std::wstring filename_spec
= path
.Append(L
"*").value();
101 HANDLE find_handle
= FindFirstFile(filename_spec
.c_str(), &find_file_data
);
102 if (find_handle
!= INVALID_HANDLE_VALUE
) {
104 // Don't count current or parent directories.
105 if ((wcscmp(find_file_data
.cFileName
, L
"..") == 0) ||
106 (wcscmp(find_file_data
.cFileName
, L
".") == 0))
109 long result
= CompareFileTime(&find_file_data
.ftCreationTime
, // NOLINT
110 &comparison_filetime
);
111 // File was created after or on comparison time
112 if ((result
== 1) || (result
== 0))
114 } while (FindNextFile(find_handle
, &find_file_data
));
115 FindClose(find_handle
);
121 bool Delete(const FilePath
& path
, bool recursive
) {
122 base::ThreadRestrictions::AssertIOAllowed();
124 if (path
.value().length() >= MAX_PATH
)
128 // If not recursing, then first check to see if |path| is a directory.
129 // If it is, then remove it with RemoveDirectory.
130 base::PlatformFileInfo file_info
;
131 if (GetFileInfo(path
, &file_info
) && file_info
.is_directory
)
132 return RemoveDirectory(path
.value().c_str()) != 0;
134 // Otherwise, it's a file, wildcard or non-existant. Try DeleteFile first
135 // because it should be faster. If DeleteFile fails, then we fall through
136 // to SHFileOperation, which will do the right thing.
137 if (DeleteFile(path
.value().c_str()) != 0)
141 // SHFILEOPSTRUCT wants the path to be terminated with two NULLs,
142 // so we have to use wcscpy because wcscpy_s writes non-NULLs
143 // into the rest of the buffer.
144 wchar_t double_terminated_path
[MAX_PATH
+ 1] = {0};
145 #pragma warning(suppress:4996) // don't complain about wcscpy deprecation
146 wcscpy(double_terminated_path
, path
.value().c_str());
148 SHFILEOPSTRUCT file_operation
= {0};
149 file_operation
.wFunc
= FO_DELETE
;
150 file_operation
.pFrom
= double_terminated_path
;
151 file_operation
.fFlags
= FOF_NOERRORUI
| FOF_SILENT
| FOF_NOCONFIRMATION
;
153 file_operation
.fFlags
|= FOF_NORECURSION
| FOF_FILESONLY
;
154 int err
= SHFileOperation(&file_operation
);
156 // Since we're passing flags to the operation telling it to be silent,
157 // it's possible for the operation to be aborted/cancelled without err
158 // being set (although MSDN doesn't give any scenarios for how this can
159 // happen). See MSDN for SHFileOperation and SHFILEOPTSTRUCT.
160 if (file_operation
.fAnyOperationsAborted
)
163 // Some versions of Windows return ERROR_FILE_NOT_FOUND (0x2) when deleting
164 // an empty directory and some return 0x402 when they should be returning
165 // ERROR_FILE_NOT_FOUND. MSDN says Vista and up won't return 0x402.
166 return (err
== 0 || err
== ERROR_FILE_NOT_FOUND
|| err
== 0x402);
169 bool DeleteAfterReboot(const FilePath
& path
) {
170 base::ThreadRestrictions::AssertIOAllowed();
172 if (path
.value().length() >= MAX_PATH
)
175 return MoveFileEx(path
.value().c_str(), NULL
,
176 MOVEFILE_DELAY_UNTIL_REBOOT
|
177 MOVEFILE_REPLACE_EXISTING
) != FALSE
;
180 bool Move(const FilePath
& from_path
, const FilePath
& to_path
) {
181 base::ThreadRestrictions::AssertIOAllowed();
183 // NOTE: I suspect we could support longer paths, but that would involve
184 // analyzing all our usage of files.
185 if (from_path
.value().length() >= MAX_PATH
||
186 to_path
.value().length() >= MAX_PATH
) {
189 if (MoveFileEx(from_path
.value().c_str(), to_path
.value().c_str(),
190 MOVEFILE_COPY_ALLOWED
| MOVEFILE_REPLACE_EXISTING
) != 0)
193 // Keep the last error value from MoveFileEx around in case the below
196 DWORD last_error
= ::GetLastError();
198 if (DirectoryExists(from_path
)) {
199 // MoveFileEx fails if moving directory across volumes. We will simulate
200 // the move by using Copy and Delete. Ideally we could check whether
201 // from_path and to_path are indeed in different volumes.
202 ret
= CopyAndDeleteDirectory(from_path
, to_path
);
206 // Leave a clue about what went wrong so that it can be (at least) picked
207 // up by a PLOG entry.
208 ::SetLastError(last_error
);
214 bool ReplaceFile(const FilePath
& from_path
, const FilePath
& to_path
) {
215 base::ThreadRestrictions::AssertIOAllowed();
217 // Make sure that the target file exists.
218 HANDLE target_file
= ::CreateFile(
219 to_path
.value().c_str(),
221 FILE_SHARE_READ
| FILE_SHARE_WRITE
,
224 FILE_ATTRIBUTE_NORMAL
,
226 if (target_file
!= INVALID_HANDLE_VALUE
)
227 ::CloseHandle(target_file
);
228 // When writing to a network share, we may not be able to change the ACLs.
229 // Ignore ACL errors then (REPLACEFILE_IGNORE_MERGE_ERRORS).
230 return ::ReplaceFile(to_path
.value().c_str(),
231 from_path
.value().c_str(), NULL
,
232 REPLACEFILE_IGNORE_MERGE_ERRORS
, NULL
, NULL
) ? true : false;
235 bool CopyFile(const FilePath
& from_path
, const FilePath
& to_path
) {
236 base::ThreadRestrictions::AssertIOAllowed();
238 // NOTE: I suspect we could support longer paths, but that would involve
239 // analyzing all our usage of files.
240 if (from_path
.value().length() >= MAX_PATH
||
241 to_path
.value().length() >= MAX_PATH
) {
244 return (::CopyFile(from_path
.value().c_str(), to_path
.value().c_str(),
248 bool ShellCopy(const FilePath
& from_path
, const FilePath
& to_path
,
250 base::ThreadRestrictions::AssertIOAllowed();
252 // NOTE: I suspect we could support longer paths, but that would involve
253 // analyzing all our usage of files.
254 if (from_path
.value().length() >= MAX_PATH
||
255 to_path
.value().length() >= MAX_PATH
) {
259 // SHFILEOPSTRUCT wants the path to be terminated with two NULLs,
260 // so we have to use wcscpy because wcscpy_s writes non-NULLs
261 // into the rest of the buffer.
262 wchar_t double_terminated_path_from
[MAX_PATH
+ 1] = {0};
263 wchar_t double_terminated_path_to
[MAX_PATH
+ 1] = {0};
264 #pragma warning(suppress:4996) // don't complain about wcscpy deprecation
265 wcscpy(double_terminated_path_from
, from_path
.value().c_str());
266 #pragma warning(suppress:4996) // don't complain about wcscpy deprecation
267 wcscpy(double_terminated_path_to
, to_path
.value().c_str());
269 SHFILEOPSTRUCT file_operation
= {0};
270 file_operation
.wFunc
= FO_COPY
;
271 file_operation
.pFrom
= double_terminated_path_from
;
272 file_operation
.pTo
= double_terminated_path_to
;
273 file_operation
.fFlags
= FOF_NOERRORUI
| FOF_SILENT
| FOF_NOCONFIRMATION
|
276 file_operation
.fFlags
|= FOF_NORECURSION
| FOF_FILESONLY
;
278 return (SHFileOperation(&file_operation
) == 0);
281 bool CopyDirectory(const FilePath
& from_path
, const FilePath
& to_path
,
283 base::ThreadRestrictions::AssertIOAllowed();
286 return ShellCopy(from_path
, to_path
, true);
288 // The following code assumes that from path is a directory.
289 DCHECK(DirectoryExists(from_path
));
291 // Instead of creating a new directory, we copy the old one to include the
292 // security information of the folder as part of the copy.
293 if (!PathExists(to_path
)) {
294 // Except that Vista fails to do that, and instead do a recursive copy if
295 // the target directory doesn't exist.
296 if (base::win::GetVersion() >= base::win::VERSION_VISTA
)
297 CreateDirectory(to_path
);
299 ShellCopy(from_path
, to_path
, false);
302 FilePath directory
= from_path
.Append(L
"*.*");
303 return ShellCopy(directory
, to_path
, false);
306 bool CopyAndDeleteDirectory(const FilePath
& from_path
,
307 const FilePath
& to_path
) {
308 base::ThreadRestrictions::AssertIOAllowed();
309 if (CopyDirectory(from_path
, to_path
, true)) {
310 if (Delete(from_path
, true)) {
313 // Like Move, this function is not transactional, so we just
314 // leave the copied bits behind if deleting from_path fails.
315 // If to_path exists previously then we have already overwritten
316 // it by now, we don't get better off by deleting the new bits.
322 bool PathExists(const FilePath
& path
) {
323 base::ThreadRestrictions::AssertIOAllowed();
324 return (GetFileAttributes(path
.value().c_str()) != INVALID_FILE_ATTRIBUTES
);
327 bool PathIsWritable(const FilePath
& path
) {
328 base::ThreadRestrictions::AssertIOAllowed();
330 CreateFile(path
.value().c_str(), FILE_ADD_FILE
, kFileShareAll
,
331 NULL
, OPEN_EXISTING
, FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
333 if (dir
== INVALID_HANDLE_VALUE
)
340 bool DirectoryExists(const FilePath
& path
) {
341 base::ThreadRestrictions::AssertIOAllowed();
342 DWORD fileattr
= GetFileAttributes(path
.value().c_str());
343 if (fileattr
!= INVALID_FILE_ATTRIBUTES
)
344 return (fileattr
& FILE_ATTRIBUTE_DIRECTORY
) != 0;
348 bool GetFileCreationLocalTimeFromHandle(HANDLE file_handle
,
349 LPSYSTEMTIME creation_time
) {
350 base::ThreadRestrictions::AssertIOAllowed();
354 FILETIME utc_filetime
;
355 if (!GetFileTime(file_handle
, &utc_filetime
, NULL
, NULL
))
358 FILETIME local_filetime
;
359 if (!FileTimeToLocalFileTime(&utc_filetime
, &local_filetime
))
362 return !!FileTimeToSystemTime(&local_filetime
, creation_time
);
365 bool GetFileCreationLocalTime(const std::wstring
& filename
,
366 LPSYSTEMTIME creation_time
) {
367 base::ThreadRestrictions::AssertIOAllowed();
368 base::win::ScopedHandle
file_handle(
369 CreateFile(filename
.c_str(), GENERIC_READ
, kFileShareAll
, NULL
,
370 OPEN_EXISTING
, FILE_ATTRIBUTE_NORMAL
, NULL
));
371 return GetFileCreationLocalTimeFromHandle(file_handle
.Get(), creation_time
);
374 bool ResolveShortcut(FilePath
* path
) {
375 base::ThreadRestrictions::AssertIOAllowed();
378 base::win::ScopedComPtr
<IShellLink
> i_shell_link
;
379 bool is_resolved
= false;
381 // Get pointer to the IShellLink interface
382 result
= i_shell_link
.CreateInstance(CLSID_ShellLink
, NULL
,
383 CLSCTX_INPROC_SERVER
);
384 if (SUCCEEDED(result
)) {
385 base::win::ScopedComPtr
<IPersistFile
> persist
;
386 // Query IShellLink for the IPersistFile interface
387 result
= persist
.QueryFrom(i_shell_link
);
388 if (SUCCEEDED(result
)) {
389 WCHAR temp_path
[MAX_PATH
];
390 // Load the shell link
391 result
= persist
->Load(path
->value().c_str(), STGM_READ
);
392 if (SUCCEEDED(result
)) {
393 // Try to find the target of a shortcut
394 result
= i_shell_link
->Resolve(0, SLR_NO_UI
);
395 if (SUCCEEDED(result
)) {
396 result
= i_shell_link
->GetPath(temp_path
, MAX_PATH
,
397 NULL
, SLGP_UNCPRIORITY
);
398 *path
= FilePath(temp_path
);
408 bool CreateShortcutLink(const wchar_t *source
, const wchar_t *destination
,
409 const wchar_t *working_dir
, const wchar_t *arguments
,
410 const wchar_t *description
, const wchar_t *icon
,
411 int icon_index
, const wchar_t* app_id
) {
412 base::ThreadRestrictions::AssertIOAllowed();
414 // Length of arguments and description must be less than MAX_PATH.
415 DCHECK(lstrlen(arguments
) < MAX_PATH
);
416 DCHECK(lstrlen(description
) < MAX_PATH
);
418 base::win::ScopedComPtr
<IShellLink
> i_shell_link
;
419 base::win::ScopedComPtr
<IPersistFile
> i_persist_file
;
421 // Get pointer to the IShellLink interface
422 HRESULT result
= i_shell_link
.CreateInstance(CLSID_ShellLink
, NULL
,
423 CLSCTX_INPROC_SERVER
);
427 // Query IShellLink for the IPersistFile interface
428 result
= i_persist_file
.QueryFrom(i_shell_link
);
432 if (FAILED(i_shell_link
->SetPath(source
)))
435 if (working_dir
&& FAILED(i_shell_link
->SetWorkingDirectory(working_dir
)))
438 if (arguments
&& FAILED(i_shell_link
->SetArguments(arguments
)))
441 if (description
&& FAILED(i_shell_link
->SetDescription(description
)))
444 if (icon
&& FAILED(i_shell_link
->SetIconLocation(icon
, icon_index
)))
447 if (app_id
&& (base::win::GetVersion() >= base::win::VERSION_WIN7
)) {
448 base::win::ScopedComPtr
<IPropertyStore
> property_store
;
449 if (FAILED(property_store
.QueryFrom(i_shell_link
)))
452 if (!base::win::SetAppIdForPropertyStore(property_store
, app_id
))
456 result
= i_persist_file
->Save(destination
, TRUE
);
457 return SUCCEEDED(result
);
460 bool UpdateShortcutLink(const wchar_t *source
, const wchar_t *destination
,
461 const wchar_t *working_dir
, const wchar_t *arguments
,
462 const wchar_t *description
, const wchar_t *icon
,
463 int icon_index
, const wchar_t* app_id
) {
464 base::ThreadRestrictions::AssertIOAllowed();
466 // Length of arguments and description must be less than MAX_PATH.
467 DCHECK(lstrlen(arguments
) < MAX_PATH
);
468 DCHECK(lstrlen(description
) < MAX_PATH
);
470 // Get pointer to the IPersistFile interface and load existing link
471 base::win::ScopedComPtr
<IShellLink
> i_shell_link
;
472 if (FAILED(i_shell_link
.CreateInstance(CLSID_ShellLink
, NULL
,
473 CLSCTX_INPROC_SERVER
)))
476 base::win::ScopedComPtr
<IPersistFile
> i_persist_file
;
477 if (FAILED(i_persist_file
.QueryFrom(i_shell_link
)))
480 if (FAILED(i_persist_file
->Load(destination
, STGM_READWRITE
)))
483 if (source
&& FAILED(i_shell_link
->SetPath(source
)))
486 if (working_dir
&& FAILED(i_shell_link
->SetWorkingDirectory(working_dir
)))
489 if (arguments
&& FAILED(i_shell_link
->SetArguments(arguments
)))
492 if (description
&& FAILED(i_shell_link
->SetDescription(description
)))
495 if (icon
&& FAILED(i_shell_link
->SetIconLocation(icon
, icon_index
)))
498 if (app_id
&& base::win::GetVersion() >= base::win::VERSION_WIN7
) {
499 base::win::ScopedComPtr
<IPropertyStore
> property_store
;
500 if (FAILED(property_store
.QueryFrom(i_shell_link
)))
503 if (!base::win::SetAppIdForPropertyStore(property_store
, app_id
))
507 HRESULT result
= i_persist_file
->Save(destination
, TRUE
);
509 i_persist_file
.Release();
510 i_shell_link
.Release();
512 // If we successfully updated the icon, notify the shell that we have done so.
513 if (SUCCEEDED(result
)) {
514 SHChangeNotify(SHCNE_ASSOCCHANGED
, SHCNF_IDLIST
| SHCNF_FLUSHNOWAIT
,
518 return SUCCEEDED(result
);
521 bool TaskbarPinShortcutLink(const wchar_t* shortcut
) {
522 base::ThreadRestrictions::AssertIOAllowed();
524 // "Pin to taskbar" is only supported after Win7.
525 if (base::win::GetVersion() < base::win::VERSION_WIN7
)
528 int result
= reinterpret_cast<int>(ShellExecute(NULL
, L
"taskbarpin", shortcut
,
533 bool TaskbarUnpinShortcutLink(const wchar_t* shortcut
) {
534 base::ThreadRestrictions::AssertIOAllowed();
536 // "Unpin from taskbar" is only supported after Win7.
537 if (base::win::GetVersion() < base::win::VERSION_WIN7
)
540 int result
= reinterpret_cast<int>(ShellExecute(NULL
, L
"taskbarunpin",
541 shortcut
, NULL
, NULL
, 0));
545 bool GetTempDir(FilePath
* path
) {
546 base::ThreadRestrictions::AssertIOAllowed();
548 wchar_t temp_path
[MAX_PATH
+ 1];
549 DWORD path_len
= ::GetTempPath(MAX_PATH
, temp_path
);
550 if (path_len
>= MAX_PATH
|| path_len
<= 0)
552 // TODO(evanm): the old behavior of this function was to always strip the
553 // trailing slash. We duplicate this here, but it shouldn't be necessary
554 // when everyone is using the appropriate FilePath APIs.
555 *path
= FilePath(temp_path
).StripTrailingSeparators();
559 bool GetShmemTempDir(FilePath
* path
) {
560 return GetTempDir(path
);
563 bool CreateTemporaryFile(FilePath
* path
) {
564 base::ThreadRestrictions::AssertIOAllowed();
568 if (!GetTempDir(path
))
571 if (CreateTemporaryFileInDir(*path
, &temp_file
)) {
579 FILE* CreateAndOpenTemporaryShmemFile(FilePath
* path
) {
580 base::ThreadRestrictions::AssertIOAllowed();
581 return CreateAndOpenTemporaryFile(path
);
584 // On POSIX we have semantics to create and open a temporary file
586 // TODO(jrg): is there equivalent call to use on Windows instead of
588 FILE* CreateAndOpenTemporaryFileInDir(const FilePath
& dir
, FilePath
* path
) {
589 base::ThreadRestrictions::AssertIOAllowed();
590 if (!CreateTemporaryFileInDir(dir
, path
)) {
593 // Open file in binary mode, to avoid problems with fwrite. On Windows
594 // it replaces \n's with \r\n's, which may surprise you.
595 // Reference: http://msdn.microsoft.com/en-us/library/h9t88zwz(VS.71).aspx
596 return OpenFile(*path
, "wb+");
599 bool CreateTemporaryFileInDir(const FilePath
& dir
,
600 FilePath
* temp_file
) {
601 base::ThreadRestrictions::AssertIOAllowed();
603 wchar_t temp_name
[MAX_PATH
+ 1];
605 if (!GetTempFileName(dir
.value().c_str(), L
"", 0, temp_name
)) {
606 PLOG(WARNING
) << "Failed to get temporary file name in " << dir
.value();
610 DWORD path_len
= GetLongPathName(temp_name
, temp_name
, MAX_PATH
);
611 if (path_len
> MAX_PATH
+ 1 || path_len
== 0) {
612 PLOG(WARNING
) << "Failed to get long path name for " << temp_name
;
616 std::wstring temp_file_str
;
617 temp_file_str
.assign(temp_name
, path_len
);
618 *temp_file
= FilePath(temp_file_str
);
622 bool CreateTemporaryDirInDir(const FilePath
& base_dir
,
623 const FilePath::StringType
& prefix
,
625 base::ThreadRestrictions::AssertIOAllowed();
627 FilePath path_to_create
;
628 srand(static_cast<uint32
>(time(NULL
)));
630 for (int count
= 0; count
< 50; ++count
) {
631 // Try create a new temporary directory with random generated name. If
632 // the one exists, keep trying another path name until we reach some limit.
633 string16 new_dir_name
;
634 new_dir_name
.assign(prefix
);
635 new_dir_name
.append(base::IntToString16(rand() % kint16max
));
637 path_to_create
= base_dir
.Append(new_dir_name
);
638 if (::CreateDirectory(path_to_create
.value().c_str(), NULL
)) {
639 *new_dir
= path_to_create
;
647 bool CreateNewTempDirectory(const FilePath::StringType
& prefix
,
648 FilePath
* new_temp_path
) {
649 base::ThreadRestrictions::AssertIOAllowed();
651 FilePath system_temp_dir
;
652 if (!GetTempDir(&system_temp_dir
))
655 return CreateTemporaryDirInDir(system_temp_dir
, prefix
, new_temp_path
);
658 bool CreateDirectory(const FilePath
& full_path
) {
659 base::ThreadRestrictions::AssertIOAllowed();
661 // If the path exists, we've succeeded if it's a directory, failed otherwise.
662 const wchar_t* full_path_str
= full_path
.value().c_str();
663 DWORD fileattr
= ::GetFileAttributes(full_path_str
);
664 if (fileattr
!= INVALID_FILE_ATTRIBUTES
) {
665 if ((fileattr
& FILE_ATTRIBUTE_DIRECTORY
) != 0) {
666 DVLOG(1) << "CreateDirectory(" << full_path_str
<< "), "
667 << "directory already exists.";
670 LOG(WARNING
) << "CreateDirectory(" << full_path_str
<< "), "
671 << "conflicts with existing file.";
675 // Invariant: Path does not exist as file or directory.
677 // Attempt to create the parent recursively. This will immediately return
678 // true if it already exists, otherwise will create all required parent
679 // directories starting with the highest-level missing parent.
680 FilePath
parent_path(full_path
.DirName());
681 if (parent_path
.value() == full_path
.value()) {
684 if (!CreateDirectory(parent_path
)) {
685 DLOG(WARNING
) << "Failed to create one of the parent directories.";
689 if (!::CreateDirectory(full_path_str
, NULL
)) {
690 DWORD error_code
= ::GetLastError();
691 if (error_code
== ERROR_ALREADY_EXISTS
&& DirectoryExists(full_path
)) {
692 // This error code ERROR_ALREADY_EXISTS doesn't indicate whether we
693 // were racing with someone creating the same directory, or a file
694 // with the same path. If DirectoryExists() returns true, we lost the
695 // race to create the same directory.
698 LOG(WARNING
) << "Failed to create directory " << full_path_str
699 << ", last error is " << error_code
<< ".";
707 // TODO(rkc): Work out if we want to handle NTFS junctions here or not, handle
708 // them if we do decide to.
709 bool IsLink(const FilePath
& file_path
) {
713 bool GetFileInfo(const FilePath
& file_path
, base::PlatformFileInfo
* results
) {
714 base::ThreadRestrictions::AssertIOAllowed();
716 WIN32_FILE_ATTRIBUTE_DATA attr
;
717 if (!GetFileAttributesEx(file_path
.value().c_str(),
718 GetFileExInfoStandard
, &attr
)) {
723 size
.HighPart
= attr
.nFileSizeHigh
;
724 size
.LowPart
= attr
.nFileSizeLow
;
725 results
->size
= size
.QuadPart
;
727 results
->is_directory
=
728 (attr
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
) != 0;
729 results
->last_modified
= base::Time::FromFileTime(attr
.ftLastWriteTime
);
730 results
->last_accessed
= base::Time::FromFileTime(attr
.ftLastAccessTime
);
731 results
->creation_time
= base::Time::FromFileTime(attr
.ftCreationTime
);
736 FILE* OpenFile(const FilePath
& filename
, const char* mode
) {
737 base::ThreadRestrictions::AssertIOAllowed();
738 std::wstring w_mode
= ASCIIToWide(std::string(mode
));
739 return _wfsopen(filename
.value().c_str(), w_mode
.c_str(), _SH_DENYNO
);
742 FILE* OpenFile(const std::string
& filename
, const char* mode
) {
743 base::ThreadRestrictions::AssertIOAllowed();
744 return _fsopen(filename
.c_str(), mode
, _SH_DENYNO
);
747 int ReadFile(const FilePath
& filename
, char* data
, int size
) {
748 base::ThreadRestrictions::AssertIOAllowed();
749 base::win::ScopedHandle
file(CreateFile(filename
.value().c_str(),
751 FILE_SHARE_READ
| FILE_SHARE_WRITE
,
754 FILE_FLAG_SEQUENTIAL_SCAN
,
760 if (::ReadFile(file
, data
, size
, &read
, NULL
) &&
761 static_cast<int>(read
) == size
)
766 int WriteFile(const FilePath
& filename
, const char* data
, int size
) {
767 base::ThreadRestrictions::AssertIOAllowed();
768 base::win::ScopedHandle
file(CreateFile(filename
.value().c_str(),
776 LOG(WARNING
) << "CreateFile failed for path " << filename
.value()
777 << " error code=" << GetLastError();
782 BOOL result
= ::WriteFile(file
, data
, size
, &written
, NULL
);
783 if (result
&& static_cast<int>(written
) == size
)
788 LOG(WARNING
) << "writing file " << filename
.value()
789 << " failed, error code=" << GetLastError();
791 // Didn't write all the bytes.
792 LOG(WARNING
) << "wrote" << written
<< " bytes to " <<
793 filename
.value() << " expected " << size
;
798 // Gets the current working directory for the process.
799 bool GetCurrentDirectory(FilePath
* dir
) {
800 base::ThreadRestrictions::AssertIOAllowed();
802 wchar_t system_buffer
[MAX_PATH
];
803 system_buffer
[0] = 0;
804 DWORD len
= ::GetCurrentDirectory(MAX_PATH
, system_buffer
);
805 if (len
== 0 || len
> MAX_PATH
)
807 // TODO(evanm): the old behavior of this function was to always strip the
808 // trailing slash. We duplicate this here, but it shouldn't be necessary
809 // when everyone is using the appropriate FilePath APIs.
810 std::wstring
dir_str(system_buffer
);
811 *dir
= FilePath(dir_str
).StripTrailingSeparators();
815 // Sets the current working directory for the process.
816 bool SetCurrentDirectory(const FilePath
& directory
) {
817 base::ThreadRestrictions::AssertIOAllowed();
818 BOOL ret
= ::SetCurrentDirectory(directory
.value().c_str());
822 ///////////////////////////////////////////////
825 FileEnumerator::FileEnumerator(const FilePath
& root_path
,
828 : recursive_(recursive
),
829 file_type_(file_type
),
830 has_find_data_(false),
831 find_handle_(INVALID_HANDLE_VALUE
) {
832 // INCLUDE_DOT_DOT must not be specified if recursive.
833 DCHECK(!(recursive
&& (INCLUDE_DOT_DOT
& file_type_
)));
834 pending_paths_
.push(root_path
);
837 FileEnumerator::FileEnumerator(const FilePath
& root_path
,
840 const FilePath::StringType
& pattern
)
841 : recursive_(recursive
),
842 file_type_(file_type
),
843 has_find_data_(false),
845 find_handle_(INVALID_HANDLE_VALUE
) {
846 // INCLUDE_DOT_DOT must not be specified if recursive.
847 DCHECK(!(recursive
&& (INCLUDE_DOT_DOT
& file_type_
)));
848 pending_paths_
.push(root_path
);
851 FileEnumerator::~FileEnumerator() {
852 if (find_handle_
!= INVALID_HANDLE_VALUE
)
853 FindClose(find_handle_
);
856 void FileEnumerator::GetFindInfo(FindInfo
* info
) {
862 memcpy(info
, &find_data_
, sizeof(*info
));
865 bool FileEnumerator::IsDirectory(const FindInfo
& info
) {
866 return (info
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
) != 0;
870 FilePath
FileEnumerator::GetFilename(const FindInfo
& find_info
) {
871 return FilePath(find_info
.cFileName
);
875 int64
FileEnumerator::GetFilesize(const FindInfo
& find_info
) {
877 size
.HighPart
= find_info
.nFileSizeHigh
;
878 size
.LowPart
= find_info
.nFileSizeLow
;
879 DCHECK_LE(size
.QuadPart
, std::numeric_limits
<int64
>::max());
880 return static_cast<int64
>(size
.QuadPart
);
884 base::Time
FileEnumerator::GetLastModifiedTime(const FindInfo
& find_info
) {
885 return base::Time::FromFileTime(find_info
.ftLastWriteTime
);
888 FilePath
FileEnumerator::Next() {
889 base::ThreadRestrictions::AssertIOAllowed();
891 while (has_find_data_
|| !pending_paths_
.empty()) {
892 if (!has_find_data_
) {
893 // The last find FindFirstFile operation is done, prepare a new one.
894 root_path_
= pending_paths_
.top();
895 pending_paths_
.pop();
897 // Start a new find operation.
898 FilePath src
= root_path_
;
900 if (pattern_
.empty())
901 src
= src
.Append(L
"*"); // No pattern = match everything.
903 src
= src
.Append(pattern_
);
905 find_handle_
= FindFirstFile(src
.value().c_str(), &find_data_
);
906 has_find_data_
= true;
908 // Search for the next file/directory.
909 if (!FindNextFile(find_handle_
, &find_data_
)) {
910 FindClose(find_handle_
);
911 find_handle_
= INVALID_HANDLE_VALUE
;
915 if (INVALID_HANDLE_VALUE
== find_handle_
) {
916 has_find_data_
= false;
918 // This is reached when we have finished a directory and are advancing to
919 // the next one in the queue. We applied the pattern (if any) to the files
920 // in the root search directory, but for those directories which were
921 // matched, we want to enumerate all files inside them. This will happen
922 // when the handle is empty.
923 pattern_
= FilePath::StringType();
928 FilePath
cur_file(find_data_
.cFileName
);
929 if (ShouldSkip(cur_file
))
932 // Construct the absolute filename.
933 cur_file
= root_path_
.Append(find_data_
.cFileName
);
935 if (find_data_
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
) {
937 // If |cur_file| is a directory, and we are doing recursive searching,
938 // add it to pending_paths_ so we scan it after we finish scanning this
940 pending_paths_
.push(cur_file
);
942 if (file_type_
& FileEnumerator::DIRECTORIES
)
944 } else if (file_type_
& FileEnumerator::FILES
) {
952 ///////////////////////////////////////////////
955 MemoryMappedFile::MemoryMappedFile()
956 : file_(INVALID_HANDLE_VALUE
),
957 file_mapping_(INVALID_HANDLE_VALUE
),
959 length_(INVALID_FILE_SIZE
) {
962 bool MemoryMappedFile::InitializeAsImageSection(const FilePath
& file_name
) {
965 file_
= base::CreatePlatformFile(
966 file_name
, base::PLATFORM_FILE_OPEN
| base::PLATFORM_FILE_READ
,
969 if (file_
== base::kInvalidPlatformFileValue
) {
970 LOG(ERROR
) << "Couldn't open " << file_name
.value();
974 if (!MapFileToMemoryInternalEx(SEC_IMAGE
)) {
982 bool MemoryMappedFile::MapFileToMemoryInternal() {
983 return MapFileToMemoryInternalEx(0);
986 bool MemoryMappedFile::MapFileToMemoryInternalEx(int flags
) {
987 base::ThreadRestrictions::AssertIOAllowed();
989 if (file_
== INVALID_HANDLE_VALUE
)
992 length_
= ::GetFileSize(file_
, NULL
);
993 if (length_
== INVALID_FILE_SIZE
)
996 file_mapping_
= ::CreateFileMapping(file_
, NULL
, PAGE_READONLY
| flags
,
998 if (!file_mapping_
) {
999 // According to msdn, system error codes are only reserved up to 15999.
1000 // http://msdn.microsoft.com/en-us/library/ms681381(v=VS.85).aspx.
1001 UMA_HISTOGRAM_ENUMERATION("MemoryMappedFile.CreateFileMapping",
1002 logging::GetLastSystemErrorCode(), 16000);
1006 data_
= static_cast<uint8
*>(
1007 ::MapViewOfFile(file_mapping_
, FILE_MAP_READ
, 0, 0, 0));
1009 UMA_HISTOGRAM_ENUMERATION("MemoryMappedFile.MapViewOfFile",
1010 logging::GetLastSystemErrorCode(), 16000);
1012 return data_
!= NULL
;
1015 void MemoryMappedFile::CloseHandles() {
1017 ::UnmapViewOfFile(data_
);
1018 if (file_mapping_
!= INVALID_HANDLE_VALUE
)
1019 ::CloseHandle(file_mapping_
);
1020 if (file_
!= INVALID_HANDLE_VALUE
)
1021 ::CloseHandle(file_
);
1024 file_mapping_
= file_
= INVALID_HANDLE_VALUE
;
1025 length_
= INVALID_FILE_SIZE
;
1028 bool HasFileBeenModifiedSince(const FileEnumerator::FindInfo
& find_info
,
1029 const base::Time
& cutoff_time
) {
1030 base::ThreadRestrictions::AssertIOAllowed();
1031 long result
= CompareFileTime(&find_info
.ftLastWriteTime
, // NOLINT
1032 &cutoff_time
.ToFileTime());
1033 return result
== 1 || result
== 0;
1036 bool NormalizeFilePath(const FilePath
& path
, FilePath
* real_path
) {
1037 base::ThreadRestrictions::AssertIOAllowed();
1038 FilePath mapped_file
;
1039 if (!NormalizeToNativeFilePath(path
, &mapped_file
))
1041 // NormalizeToNativeFilePath() will return a path that starts with
1042 // "\Device\Harddisk...". Helper DevicePathToDriveLetterPath()
1043 // will find a drive letter which maps to the path's device, so
1044 // that we return a path starting with a drive letter.
1045 return DevicePathToDriveLetterPath(mapped_file
, real_path
);
1048 bool NormalizeToNativeFilePath(const FilePath
& path
, FilePath
* nt_path
) {
1049 base::ThreadRestrictions::AssertIOAllowed();
1050 // In Vista, GetFinalPathNameByHandle() would give us the real path
1051 // from a file handle. If we ever deprecate XP, consider changing the
1052 // code below to a call to GetFinalPathNameByHandle(). The method this
1053 // function uses is explained in the following msdn article:
1054 // http://msdn.microsoft.com/en-us/library/aa366789(VS.85).aspx
1055 base::win::ScopedHandle
file_handle(
1056 ::CreateFile(path
.value().c_str(),
1061 FILE_ATTRIBUTE_NORMAL
,
1066 // Create a file mapping object. Can't easily use MemoryMappedFile, because
1067 // we only map the first byte, and need direct access to the handle. You can
1068 // not map an empty file, this call fails in that case.
1069 base::win::ScopedHandle
file_map_handle(
1070 ::CreateFileMapping(file_handle
.Get(),
1074 1, // Just one byte. No need to look at the data.
1076 if (!file_map_handle
)
1079 // Use a view of the file to get the path to the file.
1080 void* file_view
= MapViewOfFile(file_map_handle
.Get(),
1081 FILE_MAP_READ
, 0, 0, 1);
1085 // The expansion of |path| into a full path may make it longer.
1086 // GetMappedFileName() will fail if the result is longer than MAX_PATH.
1087 // Pad a bit to be safe. If kMaxPathLength is ever changed to be less
1088 // than MAX_PATH, it would be nessisary to test that GetMappedFileName()
1089 // not return kMaxPathLength. This would mean that only part of the
1090 // path fit in |mapped_file_path|.
1091 const int kMaxPathLength
= MAX_PATH
+ 10;
1092 wchar_t mapped_file_path
[kMaxPathLength
];
1093 bool success
= false;
1094 HANDLE cp
= GetCurrentProcess();
1095 if (::GetMappedFileNameW(cp
, file_view
, mapped_file_path
, kMaxPathLength
)) {
1096 *nt_path
= FilePath(mapped_file_path
);
1099 ::UnmapViewOfFile(file_view
);
1103 bool PreReadImage(const wchar_t* file_path
, size_t size_to_read
,
1105 base::ThreadRestrictions::AssertIOAllowed();
1106 if (base::win::GetVersion() > base::win::VERSION_XP
) {
1107 // Vista+ branch. On these OSes, the forced reads through the DLL actually
1108 // slows warm starts. The solution is to sequentially read file contents
1109 // with an optional cap on total amount to read.
1110 base::win::ScopedHandle
file(
1111 CreateFile(file_path
,
1113 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
,
1116 FILE_FLAG_SEQUENTIAL_SCAN
,
1119 if (!file
.IsValid())
1122 // Default to 1MB sequential reads.
1123 const DWORD actual_step_size
= std::max(static_cast<DWORD
>(step_size
),
1124 static_cast<DWORD
>(1024*1024));
1125 LPVOID buffer
= ::VirtualAlloc(NULL
,
1134 size_t total_read
= 0;
1135 while (::ReadFile(file
, buffer
, actual_step_size
, &len
, NULL
) &&
1137 (size_to_read
? total_read
< size_to_read
: true)) {
1138 total_read
+= static_cast<size_t>(len
);
1140 ::VirtualFree(buffer
, 0, MEM_RELEASE
);
1142 // WinXP branch. Here, reading the DLL from disk doesn't do
1143 // what we want so instead we pull the pages into memory by loading
1144 // the DLL and touching pages at a stride.
1145 HMODULE dll_module
= ::LoadLibraryExW(
1148 LOAD_WITH_ALTERED_SEARCH_PATH
| DONT_RESOLVE_DLL_REFERENCES
);
1153 base::win::PEImage
pe_image(dll_module
);
1154 PIMAGE_NT_HEADERS nt_headers
= pe_image
.GetNTHeaders();
1155 size_t actual_size_to_read
= size_to_read
? size_to_read
:
1156 nt_headers
->OptionalHeader
.SizeOfImage
;
1157 volatile uint8
* touch
= reinterpret_cast<uint8
*>(dll_module
);
1159 while (offset
< actual_size_to_read
) {
1160 uint8 unused
= *(touch
+ offset
);
1161 offset
+= step_size
;
1163 FreeLibrary(dll_module
);
1169 } // namespace file_util