Updating trunk VERSION from 833.0 to 834.0
[chromium-blink-merge.git] / base / file_util_win.cc
blob9a138a36e33a6a1eabe5944011e58aa090b0d181
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/win/pe_image.h"
21 #include "base/win/scoped_handle.h"
22 #include "base/string_number_conversions.h"
23 #include "base/string_util.h"
24 #include "base/threading/thread_restrictions.h"
25 #include "base/time.h"
26 #include "base/utf_string_conversions.h"
27 #include "base/win/scoped_comptr.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 bool RenameFileAndResetSecurityDescriptor(const FilePath& source_file_path,
799 const FilePath& target_file_path) {
800 base::ThreadRestrictions::AssertIOAllowed();
802 // The parameters to SHFileOperation must be terminated with 2 NULL chars.
803 std::wstring source = source_file_path.value();
804 std::wstring target = target_file_path.value();
806 source.append(1, L'\0');
807 target.append(1, L'\0');
809 SHFILEOPSTRUCT move_info = {0};
810 move_info.wFunc = FO_MOVE;
811 move_info.pFrom = source.c_str();
812 move_info.pTo = target.c_str();
813 move_info.fFlags = FOF_SILENT | FOF_NOCONFIRMATION | FOF_NOERRORUI |
814 FOF_NOCONFIRMMKDIR | FOF_NOCOPYSECURITYATTRIBS;
816 if (0 != SHFileOperation(&move_info))
817 return false;
819 return true;
822 // Gets the current working directory for the process.
823 bool GetCurrentDirectory(FilePath* dir) {
824 base::ThreadRestrictions::AssertIOAllowed();
826 wchar_t system_buffer[MAX_PATH];
827 system_buffer[0] = 0;
828 DWORD len = ::GetCurrentDirectory(MAX_PATH, system_buffer);
829 if (len == 0 || len > MAX_PATH)
830 return false;
831 // TODO(evanm): the old behavior of this function was to always strip the
832 // trailing slash. We duplicate this here, but it shouldn't be necessary
833 // when everyone is using the appropriate FilePath APIs.
834 std::wstring dir_str(system_buffer);
835 *dir = FilePath(dir_str).StripTrailingSeparators();
836 return true;
839 // Sets the current working directory for the process.
840 bool SetCurrentDirectory(const FilePath& directory) {
841 base::ThreadRestrictions::AssertIOAllowed();
842 BOOL ret = ::SetCurrentDirectory(directory.value().c_str());
843 return ret != 0;
846 ///////////////////////////////////////////////
847 // FileEnumerator
849 FileEnumerator::FileEnumerator(const FilePath& root_path,
850 bool recursive,
851 FileEnumerator::FILE_TYPE file_type)
852 : recursive_(recursive),
853 file_type_(file_type),
854 has_find_data_(false),
855 find_handle_(INVALID_HANDLE_VALUE) {
856 // INCLUDE_DOT_DOT must not be specified if recursive.
857 DCHECK(!(recursive && (INCLUDE_DOT_DOT & file_type_)));
858 pending_paths_.push(root_path);
861 FileEnumerator::FileEnumerator(const FilePath& root_path,
862 bool recursive,
863 FileEnumerator::FILE_TYPE file_type,
864 const FilePath::StringType& pattern)
865 : recursive_(recursive),
866 file_type_(file_type),
867 has_find_data_(false),
868 pattern_(pattern),
869 find_handle_(INVALID_HANDLE_VALUE) {
870 // INCLUDE_DOT_DOT must not be specified if recursive.
871 DCHECK(!(recursive && (INCLUDE_DOT_DOT & file_type_)));
872 pending_paths_.push(root_path);
875 FileEnumerator::~FileEnumerator() {
876 if (find_handle_ != INVALID_HANDLE_VALUE)
877 FindClose(find_handle_);
880 void FileEnumerator::GetFindInfo(FindInfo* info) {
881 DCHECK(info);
883 if (!has_find_data_)
884 return;
886 memcpy(info, &find_data_, sizeof(*info));
889 bool FileEnumerator::IsDirectory(const FindInfo& info) {
890 return (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
893 // static
894 FilePath FileEnumerator::GetFilename(const FindInfo& find_info) {
895 return FilePath(find_info.cFileName);
898 // static
899 int64 FileEnumerator::GetFilesize(const FindInfo& find_info) {
900 ULARGE_INTEGER size;
901 size.HighPart = find_info.nFileSizeHigh;
902 size.LowPart = find_info.nFileSizeLow;
903 DCHECK_LE(size.QuadPart, std::numeric_limits<int64>::max());
904 return static_cast<int64>(size.QuadPart);
907 // static
908 base::Time FileEnumerator::GetLastModifiedTime(const FindInfo& find_info) {
909 return base::Time::FromFileTime(find_info.ftLastWriteTime);
912 FilePath FileEnumerator::Next() {
913 base::ThreadRestrictions::AssertIOAllowed();
915 while (has_find_data_ || !pending_paths_.empty()) {
916 if (!has_find_data_) {
917 // The last find FindFirstFile operation is done, prepare a new one.
918 root_path_ = pending_paths_.top();
919 pending_paths_.pop();
921 // Start a new find operation.
922 FilePath src = root_path_;
924 if (pattern_.empty())
925 src = src.Append(L"*"); // No pattern = match everything.
926 else
927 src = src.Append(pattern_);
929 find_handle_ = FindFirstFile(src.value().c_str(), &find_data_);
930 has_find_data_ = true;
931 } else {
932 // Search for the next file/directory.
933 if (!FindNextFile(find_handle_, &find_data_)) {
934 FindClose(find_handle_);
935 find_handle_ = INVALID_HANDLE_VALUE;
939 if (INVALID_HANDLE_VALUE == find_handle_) {
940 has_find_data_ = false;
942 // This is reached when we have finished a directory and are advancing to
943 // the next one in the queue. We applied the pattern (if any) to the files
944 // in the root search directory, but for those directories which were
945 // matched, we want to enumerate all files inside them. This will happen
946 // when the handle is empty.
947 pattern_ = FilePath::StringType();
949 continue;
952 FilePath cur_file(find_data_.cFileName);
953 if (ShouldSkip(cur_file))
954 continue;
956 // Construct the absolute filename.
957 cur_file = root_path_.Append(find_data_.cFileName);
959 if (find_data_.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
960 if (recursive_) {
961 // If |cur_file| is a directory, and we are doing recursive searching,
962 // add it to pending_paths_ so we scan it after we finish scanning this
963 // directory.
964 pending_paths_.push(cur_file);
966 if (file_type_ & FileEnumerator::DIRECTORIES)
967 return cur_file;
968 } else if (file_type_ & FileEnumerator::FILES) {
969 return cur_file;
973 return FilePath();
976 ///////////////////////////////////////////////
977 // MemoryMappedFile
979 MemoryMappedFile::MemoryMappedFile()
980 : file_(INVALID_HANDLE_VALUE),
981 file_mapping_(INVALID_HANDLE_VALUE),
982 data_(NULL),
983 length_(INVALID_FILE_SIZE) {
986 bool MemoryMappedFile::InitializeAsImageSection(const FilePath& file_name) {
987 if (IsValid())
988 return false;
989 file_ = base::CreatePlatformFile(
990 file_name, base::PLATFORM_FILE_OPEN | base::PLATFORM_FILE_READ,
991 NULL, NULL);
993 if (file_ == base::kInvalidPlatformFileValue) {
994 LOG(ERROR) << "Couldn't open " << file_name.value();
995 return false;
998 if (!MapFileToMemoryInternalEx(SEC_IMAGE)) {
999 CloseHandles();
1000 return false;
1003 return true;
1006 bool MemoryMappedFile::MapFileToMemoryInternal() {
1007 return MapFileToMemoryInternalEx(0);
1010 bool MemoryMappedFile::MapFileToMemoryInternalEx(int flags) {
1011 base::ThreadRestrictions::AssertIOAllowed();
1013 if (file_ == INVALID_HANDLE_VALUE)
1014 return false;
1016 length_ = ::GetFileSize(file_, NULL);
1017 if (length_ == INVALID_FILE_SIZE)
1018 return false;
1020 file_mapping_ = ::CreateFileMapping(file_, NULL, PAGE_READONLY | flags,
1021 0, 0, NULL);
1022 if (!file_mapping_) {
1023 // According to msdn, system error codes are only reserved up to 15999.
1024 // http://msdn.microsoft.com/en-us/library/ms681381(v=VS.85).aspx.
1025 UMA_HISTOGRAM_ENUMERATION("MemoryMappedFile.CreateFileMapping",
1026 logging::GetLastSystemErrorCode(), 16000);
1027 return false;
1030 data_ = static_cast<uint8*>(
1031 ::MapViewOfFile(file_mapping_, FILE_MAP_READ, 0, 0, 0));
1032 if (!data_) {
1033 UMA_HISTOGRAM_ENUMERATION("MemoryMappedFile.MapViewOfFile",
1034 logging::GetLastSystemErrorCode(), 16000);
1036 return data_ != NULL;
1039 void MemoryMappedFile::CloseHandles() {
1040 if (data_)
1041 ::UnmapViewOfFile(data_);
1042 if (file_mapping_ != INVALID_HANDLE_VALUE)
1043 ::CloseHandle(file_mapping_);
1044 if (file_ != INVALID_HANDLE_VALUE)
1045 ::CloseHandle(file_);
1047 data_ = NULL;
1048 file_mapping_ = file_ = INVALID_HANDLE_VALUE;
1049 length_ = INVALID_FILE_SIZE;
1052 bool HasFileBeenModifiedSince(const FileEnumerator::FindInfo& find_info,
1053 const base::Time& cutoff_time) {
1054 base::ThreadRestrictions::AssertIOAllowed();
1055 long result = CompareFileTime(&find_info.ftLastWriteTime, // NOLINT
1056 &cutoff_time.ToFileTime());
1057 return result == 1 || result == 0;
1060 bool NormalizeFilePath(const FilePath& path, FilePath* real_path) {
1061 base::ThreadRestrictions::AssertIOAllowed();
1062 FilePath mapped_file;
1063 if (!NormalizeToNativeFilePath(path, &mapped_file))
1064 return false;
1065 // NormalizeToNativeFilePath() will return a path that starts with
1066 // "\Device\Harddisk...". Helper DevicePathToDriveLetterPath()
1067 // will find a drive letter which maps to the path's device, so
1068 // that we return a path starting with a drive letter.
1069 return DevicePathToDriveLetterPath(mapped_file, real_path);
1072 bool NormalizeToNativeFilePath(const FilePath& path, FilePath* nt_path) {
1073 base::ThreadRestrictions::AssertIOAllowed();
1074 // In Vista, GetFinalPathNameByHandle() would give us the real path
1075 // from a file handle. If we ever deprecate XP, consider changing the
1076 // code below to a call to GetFinalPathNameByHandle(). The method this
1077 // function uses is explained in the following msdn article:
1078 // http://msdn.microsoft.com/en-us/library/aa366789(VS.85).aspx
1079 base::win::ScopedHandle file_handle(
1080 ::CreateFile(path.value().c_str(),
1081 GENERIC_READ,
1082 kFileShareAll,
1083 NULL,
1084 OPEN_EXISTING,
1085 FILE_ATTRIBUTE_NORMAL,
1086 NULL));
1087 if (!file_handle)
1088 return false;
1090 // Create a file mapping object. Can't easily use MemoryMappedFile, because
1091 // we only map the first byte, and need direct access to the handle. You can
1092 // not map an empty file, this call fails in that case.
1093 base::win::ScopedHandle file_map_handle(
1094 ::CreateFileMapping(file_handle.Get(),
1095 NULL,
1096 PAGE_READONLY,
1098 1, // Just one byte. No need to look at the data.
1099 NULL));
1100 if (!file_map_handle)
1101 return false;
1103 // Use a view of the file to get the path to the file.
1104 void* file_view = MapViewOfFile(file_map_handle.Get(),
1105 FILE_MAP_READ, 0, 0, 1);
1106 if (!file_view)
1107 return false;
1109 // The expansion of |path| into a full path may make it longer.
1110 // GetMappedFileName() will fail if the result is longer than MAX_PATH.
1111 // Pad a bit to be safe. If kMaxPathLength is ever changed to be less
1112 // than MAX_PATH, it would be nessisary to test that GetMappedFileName()
1113 // not return kMaxPathLength. This would mean that only part of the
1114 // path fit in |mapped_file_path|.
1115 const int kMaxPathLength = MAX_PATH + 10;
1116 wchar_t mapped_file_path[kMaxPathLength];
1117 bool success = false;
1118 HANDLE cp = GetCurrentProcess();
1119 if (::GetMappedFileNameW(cp, file_view, mapped_file_path, kMaxPathLength)) {
1120 *nt_path = FilePath(mapped_file_path);
1121 success = true;
1123 ::UnmapViewOfFile(file_view);
1124 return success;
1127 bool PreReadImage(const wchar_t* file_path, size_t size_to_read,
1128 size_t step_size) {
1129 base::ThreadRestrictions::AssertIOAllowed();
1130 if (base::win::GetVersion() > base::win::VERSION_XP) {
1131 // Vista+ branch. On these OSes, the forced reads through the DLL actually
1132 // slows warm starts. The solution is to sequentially read file contents
1133 // with an optional cap on total amount to read.
1134 base::win::ScopedHandle file(
1135 CreateFile(file_path,
1136 GENERIC_READ,
1137 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
1138 NULL,
1139 OPEN_EXISTING,
1140 FILE_FLAG_SEQUENTIAL_SCAN,
1141 NULL));
1143 if (!file.IsValid())
1144 return false;
1146 // Default to 1MB sequential reads.
1147 const DWORD actual_step_size = std::max(static_cast<DWORD>(step_size),
1148 static_cast<DWORD>(1024*1024));
1149 LPVOID buffer = ::VirtualAlloc(NULL,
1150 actual_step_size,
1151 MEM_COMMIT,
1152 PAGE_READWRITE);
1154 if (buffer == NULL)
1155 return false;
1157 DWORD len;
1158 size_t total_read = 0;
1159 while (::ReadFile(file, buffer, actual_step_size, &len, NULL) &&
1160 len > 0 &&
1161 (size_to_read ? total_read < size_to_read : true)) {
1162 total_read += static_cast<size_t>(len);
1164 ::VirtualFree(buffer, 0, MEM_RELEASE);
1165 } else {
1166 // WinXP branch. Here, reading the DLL from disk doesn't do
1167 // what we want so instead we pull the pages into memory by loading
1168 // the DLL and touching pages at a stride.
1169 HMODULE dll_module = ::LoadLibraryExW(
1170 file_path,
1171 NULL,
1172 LOAD_WITH_ALTERED_SEARCH_PATH | DONT_RESOLVE_DLL_REFERENCES);
1174 if (!dll_module)
1175 return false;
1177 base::win::PEImage pe_image(dll_module);
1178 PIMAGE_NT_HEADERS nt_headers = pe_image.GetNTHeaders();
1179 size_t actual_size_to_read = size_to_read ? size_to_read :
1180 nt_headers->OptionalHeader.SizeOfImage;
1181 volatile uint8* touch = reinterpret_cast<uint8*>(dll_module);
1182 size_t offset = 0;
1183 while (offset < actual_size_to_read) {
1184 uint8 unused = *(touch + offset);
1185 offset += step_size;
1187 FreeLibrary(dll_module);
1190 return true;
1193 } // namespace file_util