WebKit merge 94748:94770
[chromium-blink-merge.git] / base / file_util_win.cc
blob19e15fce0fa296b259512d60e383c76c529684e6
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"
7 #include <windows.h>
8 #include <propvarutil.h>
9 #include <psapi.h>
10 #include <shellapi.h>
11 #include <shlobj.h>
12 #include <time.h>
14 #include <limits>
15 #include <string>
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"
31 namespace file_util {
33 namespace {
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.";
48 return false;
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)));
67 return true;
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.
77 return false;
80 } // namespace
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))
86 return false;
87 *path = FilePath(file_path_buf);
88 return true;
91 int CountFilesCreatedAfter(const FilePath& path,
92 const base::Time& comparison_time) {
93 base::ThreadRestrictions::AssertIOAllowed();
95 int file_count = 0;
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) {
103 do {
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))
107 continue;
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))
113 ++file_count;
114 } while (FindNextFile(find_handle, &find_file_data));
115 FindClose(find_handle);
118 return file_count;
121 bool Delete(const FilePath& path, bool recursive) {
122 base::ThreadRestrictions::AssertIOAllowed();
124 if (path.value().length() >= MAX_PATH)
125 return false;
127 if (!recursive) {
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)
138 return true;
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;
152 if (!recursive)
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)
161 return false;
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)
173 return false;
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) {
187 return false;
189 if (MoveFileEx(from_path.value().c_str(), to_path.value().c_str(),
190 MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING) != 0)
191 return true;
193 // Keep the last error value from MoveFileEx around in case the below
194 // fails.
195 bool ret = false;
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);
205 if (!ret) {
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);
211 return ret;
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,
222 NULL,
223 CREATE_NEW,
224 FILE_ATTRIBUTE_NORMAL,
225 NULL);
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) {
242 return false;
244 return (::CopyFile(from_path.value().c_str(), to_path.value().c_str(),
245 false) != 0);
248 bool ShellCopy(const FilePath& from_path, const FilePath& to_path,
249 bool recursive) {
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) {
256 return false;
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 |
274 FOF_NOCONFIRMMKDIR;
275 if (!recursive)
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,
282 bool recursive) {
283 base::ThreadRestrictions::AssertIOAllowed();
285 if (recursive)
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);
298 else
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)) {
311 return 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.
318 return false;
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();
329 HANDLE dir =
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)
334 return false;
336 CloseHandle(dir);
337 return true;
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;
345 return false;
348 bool GetFileCreationLocalTimeFromHandle(HANDLE file_handle,
349 LPSYSTEMTIME creation_time) {
350 base::ThreadRestrictions::AssertIOAllowed();
351 if (!file_handle)
352 return false;
354 FILETIME utc_filetime;
355 if (!GetFileTime(file_handle, &utc_filetime, NULL, NULL))
356 return false;
358 FILETIME local_filetime;
359 if (!FileTimeToLocalFileTime(&utc_filetime, &local_filetime))
360 return false;
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();
377 HRESULT result;
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);
399 is_resolved = true;
405 return is_resolved;
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);
424 if (FAILED(result))
425 return false;
427 // Query IShellLink for the IPersistFile interface
428 result = i_persist_file.QueryFrom(i_shell_link);
429 if (FAILED(result))
430 return false;
432 if (FAILED(i_shell_link->SetPath(source)))
433 return false;
435 if (working_dir && FAILED(i_shell_link->SetWorkingDirectory(working_dir)))
436 return false;
438 if (arguments && FAILED(i_shell_link->SetArguments(arguments)))
439 return false;
441 if (description && FAILED(i_shell_link->SetDescription(description)))
442 return false;
444 if (icon && FAILED(i_shell_link->SetIconLocation(icon, icon_index)))
445 return false;
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)))
450 return false;
452 if (!base::win::SetAppIdForPropertyStore(property_store, app_id))
453 return false;
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)))
474 return false;
476 base::win::ScopedComPtr<IPersistFile> i_persist_file;
477 if (FAILED(i_persist_file.QueryFrom(i_shell_link)))
478 return false;
480 if (FAILED(i_persist_file->Load(destination, STGM_READWRITE)))
481 return false;
483 if (source && FAILED(i_shell_link->SetPath(source)))
484 return false;
486 if (working_dir && FAILED(i_shell_link->SetWorkingDirectory(working_dir)))
487 return false;
489 if (arguments && FAILED(i_shell_link->SetArguments(arguments)))
490 return false;
492 if (description && FAILED(i_shell_link->SetDescription(description)))
493 return false;
495 if (icon && FAILED(i_shell_link->SetIconLocation(icon, icon_index)))
496 return false;
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)))
501 return false;
503 if (!base::win::SetAppIdForPropertyStore(property_store, app_id))
504 return false;
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,
515 NULL, NULL);
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)
526 return false;
528 int result = reinterpret_cast<int>(ShellExecute(NULL, L"taskbarpin", shortcut,
529 NULL, NULL, 0));
530 return result > 32;
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)
538 return false;
540 int result = reinterpret_cast<int>(ShellExecute(NULL, L"taskbarunpin",
541 shortcut, NULL, NULL, 0));
542 return result > 32;
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)
551 return false;
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();
556 return true;
559 bool GetShmemTempDir(FilePath* path) {
560 return GetTempDir(path);
563 bool CreateTemporaryFile(FilePath* path) {
564 base::ThreadRestrictions::AssertIOAllowed();
566 FilePath temp_file;
568 if (!GetTempDir(path))
569 return false;
571 if (CreateTemporaryFileInDir(*path, &temp_file)) {
572 *path = temp_file;
573 return true;
576 return false;
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
585 // atomically.
586 // TODO(jrg): is there equivalent call to use on Windows instead of
587 // going 2-step?
588 FILE* CreateAndOpenTemporaryFileInDir(const FilePath& dir, FilePath* path) {
589 base::ThreadRestrictions::AssertIOAllowed();
590 if (!CreateTemporaryFileInDir(dir, path)) {
591 return NULL;
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();
607 return false;
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;
613 return false;
616 std::wstring temp_file_str;
617 temp_file_str.assign(temp_name, path_len);
618 *temp_file = FilePath(temp_file_str);
619 return true;
622 bool CreateTemporaryDirInDir(const FilePath& base_dir,
623 const FilePath::StringType& prefix,
624 FilePath* new_dir) {
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;
640 return true;
644 return false;
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))
653 return false;
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.";
668 return true;
670 LOG(WARNING) << "CreateDirectory(" << full_path_str << "), "
671 << "conflicts with existing file.";
672 return false;
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()) {
682 return false;
684 if (!CreateDirectory(parent_path)) {
685 DLOG(WARNING) << "Failed to create one of the parent directories.";
686 return false;
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.
696 return true;
697 } else {
698 LOG(WARNING) << "Failed to create directory " << full_path_str
699 << ", last error is " << error_code << ".";
700 return false;
702 } else {
703 return true;
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) {
710 return false;
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)) {
719 return false;
722 ULARGE_INTEGER size;
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);
733 return true;
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(),
750 GENERIC_READ,
751 FILE_SHARE_READ | FILE_SHARE_WRITE,
752 NULL,
753 OPEN_EXISTING,
754 FILE_FLAG_SEQUENTIAL_SCAN,
755 NULL));
756 if (!file)
757 return -1;
759 DWORD read;
760 if (::ReadFile(file, data, size, &read, NULL) &&
761 static_cast<int>(read) == size)
762 return read;
763 return -1;
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(),
769 GENERIC_WRITE,
771 NULL,
772 CREATE_ALWAYS,
774 NULL));
775 if (!file) {
776 LOG(WARNING) << "CreateFile failed for path " << filename.value()
777 << " error code=" << GetLastError();
778 return -1;
781 DWORD written;
782 BOOL result = ::WriteFile(file, data, size, &written, NULL);
783 if (result && static_cast<int>(written) == size)
784 return written;
786 if (!result) {
787 // WriteFile failed.
788 LOG(WARNING) << "writing file " << filename.value()
789 << " failed, error code=" << GetLastError();
790 } else {
791 // Didn't write all the bytes.
792 LOG(WARNING) << "wrote" << written << " bytes to " <<
793 filename.value() << " expected " << size;
795 return -1;
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)
806 return false;
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();
812 return true;
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());
819 return ret != 0;
822 ///////////////////////////////////////////////
823 // FileEnumerator
825 FileEnumerator::FileEnumerator(const FilePath& root_path,
826 bool recursive,
827 FileType file_type)
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,
838 bool recursive,
839 FileType file_type,
840 const FilePath::StringType& pattern)
841 : recursive_(recursive),
842 file_type_(file_type),
843 has_find_data_(false),
844 pattern_(pattern),
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) {
857 DCHECK(info);
859 if (!has_find_data_)
860 return;
862 memcpy(info, &find_data_, sizeof(*info));
865 bool FileEnumerator::IsDirectory(const FindInfo& info) {
866 return (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
869 // static
870 FilePath FileEnumerator::GetFilename(const FindInfo& find_info) {
871 return FilePath(find_info.cFileName);
874 // static
875 int64 FileEnumerator::GetFilesize(const FindInfo& find_info) {
876 ULARGE_INTEGER size;
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);
883 // static
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.
902 else
903 src = src.Append(pattern_);
905 find_handle_ = FindFirstFile(src.value().c_str(), &find_data_);
906 has_find_data_ = true;
907 } else {
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();
925 continue;
928 FilePath cur_file(find_data_.cFileName);
929 if (ShouldSkip(cur_file))
930 continue;
932 // Construct the absolute filename.
933 cur_file = root_path_.Append(find_data_.cFileName);
935 if (find_data_.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
936 if (recursive_) {
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
939 // directory.
940 pending_paths_.push(cur_file);
942 if (file_type_ & FileEnumerator::DIRECTORIES)
943 return cur_file;
944 } else if (file_type_ & FileEnumerator::FILES) {
945 return cur_file;
949 return FilePath();
952 ///////////////////////////////////////////////
953 // MemoryMappedFile
955 MemoryMappedFile::MemoryMappedFile()
956 : file_(INVALID_HANDLE_VALUE),
957 file_mapping_(INVALID_HANDLE_VALUE),
958 data_(NULL),
959 length_(INVALID_FILE_SIZE) {
962 bool MemoryMappedFile::InitializeAsImageSection(const FilePath& file_name) {
963 if (IsValid())
964 return false;
965 file_ = base::CreatePlatformFile(
966 file_name, base::PLATFORM_FILE_OPEN | base::PLATFORM_FILE_READ,
967 NULL, NULL);
969 if (file_ == base::kInvalidPlatformFileValue) {
970 LOG(ERROR) << "Couldn't open " << file_name.value();
971 return false;
974 if (!MapFileToMemoryInternalEx(SEC_IMAGE)) {
975 CloseHandles();
976 return false;
979 return true;
982 bool MemoryMappedFile::MapFileToMemoryInternal() {
983 return MapFileToMemoryInternalEx(0);
986 bool MemoryMappedFile::MapFileToMemoryInternalEx(int flags) {
987 base::ThreadRestrictions::AssertIOAllowed();
989 if (file_ == INVALID_HANDLE_VALUE)
990 return false;
992 length_ = ::GetFileSize(file_, NULL);
993 if (length_ == INVALID_FILE_SIZE)
994 return false;
996 file_mapping_ = ::CreateFileMapping(file_, NULL, PAGE_READONLY | flags,
997 0, 0, NULL);
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);
1003 return false;
1006 data_ = static_cast<uint8*>(
1007 ::MapViewOfFile(file_mapping_, FILE_MAP_READ, 0, 0, 0));
1008 if (!data_) {
1009 UMA_HISTOGRAM_ENUMERATION("MemoryMappedFile.MapViewOfFile",
1010 logging::GetLastSystemErrorCode(), 16000);
1012 return data_ != NULL;
1015 void MemoryMappedFile::CloseHandles() {
1016 if (data_)
1017 ::UnmapViewOfFile(data_);
1018 if (file_mapping_ != INVALID_HANDLE_VALUE)
1019 ::CloseHandle(file_mapping_);
1020 if (file_ != INVALID_HANDLE_VALUE)
1021 ::CloseHandle(file_);
1023 data_ = NULL;
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))
1040 return false;
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(),
1057 GENERIC_READ,
1058 kFileShareAll,
1059 NULL,
1060 OPEN_EXISTING,
1061 FILE_ATTRIBUTE_NORMAL,
1062 NULL));
1063 if (!file_handle)
1064 return false;
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(),
1071 NULL,
1072 PAGE_READONLY,
1074 1, // Just one byte. No need to look at the data.
1075 NULL));
1076 if (!file_map_handle)
1077 return false;
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);
1082 if (!file_view)
1083 return false;
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);
1097 success = true;
1099 ::UnmapViewOfFile(file_view);
1100 return success;
1103 bool PreReadImage(const wchar_t* file_path, size_t size_to_read,
1104 size_t step_size) {
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,
1112 GENERIC_READ,
1113 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
1114 NULL,
1115 OPEN_EXISTING,
1116 FILE_FLAG_SEQUENTIAL_SCAN,
1117 NULL));
1119 if (!file.IsValid())
1120 return false;
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,
1126 actual_step_size,
1127 MEM_COMMIT,
1128 PAGE_READWRITE);
1130 if (buffer == NULL)
1131 return false;
1133 DWORD len;
1134 size_t total_read = 0;
1135 while (::ReadFile(file, buffer, actual_step_size, &len, NULL) &&
1136 len > 0 &&
1137 (size_to_read ? total_read < size_to_read : true)) {
1138 total_read += static_cast<size_t>(len);
1140 ::VirtualFree(buffer, 0, MEM_RELEASE);
1141 } else {
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(
1146 file_path,
1147 NULL,
1148 LOAD_WITH_ALTERED_SEARCH_PATH | DONT_RESOLVE_DLL_REFERENCES);
1150 if (!dll_module)
1151 return false;
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);
1158 size_t offset = 0;
1159 while (offset < actual_size_to_read) {
1160 uint8 unused = *(touch + offset);
1161 offset += step_size;
1163 FreeLibrary(dll_module);
1166 return true;
1169 } // namespace file_util