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