Add OS_IOS defines for the mobile promo.
[chromium-blink-merge.git] / base / file_util_win.cc
blobbf9dd9cb7046b2f58ce05b3215b2180afc394240
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/process_util.h"
21 #include "base/string_number_conversions.h"
22 #include "base/string_util.h"
23 #include "base/threading/thread_restrictions.h"
24 #include "base/time.h"
25 #include "base/utf_string_conversions.h"
26 #include "base/win/pe_image.h"
27 #include "base/win/scoped_comptr.h"
28 #include "base/win/scoped_handle.h"
29 #include "base/win/win_util.h"
30 #include "base/win/windows_version.h"
32 namespace file_util {
34 namespace {
36 const DWORD kFileShareAll =
37 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
39 } // namespace
41 bool AbsolutePath(FilePath* path) {
42 base::ThreadRestrictions::AssertIOAllowed();
43 wchar_t file_path_buf[MAX_PATH];
44 if (!_wfullpath(file_path_buf, path->value().c_str(), MAX_PATH))
45 return false;
46 *path = FilePath(file_path_buf);
47 return true;
50 int CountFilesCreatedAfter(const FilePath& path,
51 const base::Time& comparison_time) {
52 base::ThreadRestrictions::AssertIOAllowed();
54 int file_count = 0;
55 FILETIME comparison_filetime(comparison_time.ToFileTime());
57 WIN32_FIND_DATA find_file_data;
58 // All files in given dir
59 std::wstring filename_spec = path.Append(L"*").value();
60 HANDLE find_handle = FindFirstFile(filename_spec.c_str(), &find_file_data);
61 if (find_handle != INVALID_HANDLE_VALUE) {
62 do {
63 // Don't count current or parent directories.
64 if ((wcscmp(find_file_data.cFileName, L"..") == 0) ||
65 (wcscmp(find_file_data.cFileName, L".") == 0))
66 continue;
68 long result = CompareFileTime(&find_file_data.ftCreationTime, // NOLINT
69 &comparison_filetime);
70 // File was created after or on comparison time
71 if ((result == 1) || (result == 0))
72 ++file_count;
73 } while (FindNextFile(find_handle, &find_file_data));
74 FindClose(find_handle);
77 return file_count;
80 bool Delete(const FilePath& path, bool recursive) {
81 base::ThreadRestrictions::AssertIOAllowed();
83 if (path.value().length() >= MAX_PATH)
84 return false;
86 if (!recursive) {
87 // If not recursing, then first check to see if |path| is a directory.
88 // If it is, then remove it with RemoveDirectory.
89 base::PlatformFileInfo file_info;
90 if (GetFileInfo(path, &file_info) && file_info.is_directory)
91 return RemoveDirectory(path.value().c_str()) != 0;
93 // Otherwise, it's a file, wildcard or non-existant. Try DeleteFile first
94 // because it should be faster. If DeleteFile fails, then we fall through
95 // to SHFileOperation, which will do the right thing.
96 if (DeleteFile(path.value().c_str()) != 0)
97 return true;
100 // SHFILEOPSTRUCT wants the path to be terminated with two NULLs,
101 // so we have to use wcscpy because wcscpy_s writes non-NULLs
102 // into the rest of the buffer.
103 wchar_t double_terminated_path[MAX_PATH + 1] = {0};
104 #pragma warning(suppress:4996) // don't complain about wcscpy deprecation
105 if (g_bug108724_debug)
106 LOG(WARNING) << "copying ";
107 wcscpy(double_terminated_path, path.value().c_str());
109 SHFILEOPSTRUCT file_operation = {0};
110 file_operation.wFunc = FO_DELETE;
111 file_operation.pFrom = double_terminated_path;
112 file_operation.fFlags = FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMATION;
113 if (!recursive)
114 file_operation.fFlags |= FOF_NORECURSION | FOF_FILESONLY;
115 if (g_bug108724_debug)
116 LOG(WARNING) << "Performing shell operation";
117 int err = SHFileOperation(&file_operation);
118 if (g_bug108724_debug)
119 LOG(WARNING) << "Done: " << err;
121 // Since we're passing flags to the operation telling it to be silent,
122 // it's possible for the operation to be aborted/cancelled without err
123 // being set (although MSDN doesn't give any scenarios for how this can
124 // happen). See MSDN for SHFileOperation and SHFILEOPTSTRUCT.
125 if (file_operation.fAnyOperationsAborted)
126 return false;
128 // Some versions of Windows return ERROR_FILE_NOT_FOUND (0x2) when deleting
129 // an empty directory and some return 0x402 when they should be returning
130 // ERROR_FILE_NOT_FOUND. MSDN says Vista and up won't return 0x402.
131 return (err == 0 || err == ERROR_FILE_NOT_FOUND || err == 0x402);
134 bool DeleteAfterReboot(const FilePath& path) {
135 base::ThreadRestrictions::AssertIOAllowed();
137 if (path.value().length() >= MAX_PATH)
138 return false;
140 return MoveFileEx(path.value().c_str(), NULL,
141 MOVEFILE_DELAY_UNTIL_REBOOT |
142 MOVEFILE_REPLACE_EXISTING) != FALSE;
145 bool Move(const FilePath& from_path, const FilePath& to_path) {
146 base::ThreadRestrictions::AssertIOAllowed();
148 // NOTE: I suspect we could support longer paths, but that would involve
149 // analyzing all our usage of files.
150 if (from_path.value().length() >= MAX_PATH ||
151 to_path.value().length() >= MAX_PATH) {
152 return false;
154 if (MoveFileEx(from_path.value().c_str(), to_path.value().c_str(),
155 MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING) != 0)
156 return true;
158 // Keep the last error value from MoveFileEx around in case the below
159 // fails.
160 bool ret = false;
161 DWORD last_error = ::GetLastError();
163 if (DirectoryExists(from_path)) {
164 // MoveFileEx fails if moving directory across volumes. We will simulate
165 // the move by using Copy and Delete. Ideally we could check whether
166 // from_path and to_path are indeed in different volumes.
167 ret = CopyAndDeleteDirectory(from_path, to_path);
170 if (!ret) {
171 // Leave a clue about what went wrong so that it can be (at least) picked
172 // up by a PLOG entry.
173 ::SetLastError(last_error);
176 return ret;
179 bool ReplaceFile(const FilePath& from_path, const FilePath& to_path) {
180 base::ThreadRestrictions::AssertIOAllowed();
181 // Try a simple move first. It will only succeed when |to_path| doesn't
182 // already exist.
183 if (::MoveFile(from_path.value().c_str(), to_path.value().c_str()))
184 return true;
185 // Try the full-blown replace if the move fails, as ReplaceFile will only
186 // succeed when |to_path| does exist. When writing to a network share, we may
187 // not be able to change the ACLs. Ignore ACL errors then
188 // (REPLACEFILE_IGNORE_MERGE_ERRORS).
189 if (::ReplaceFile(to_path.value().c_str(), from_path.value().c_str(), NULL,
190 REPLACEFILE_IGNORE_MERGE_ERRORS, NULL, NULL)) {
191 return true;
193 return false;
196 bool CopyFile(const FilePath& from_path, const FilePath& to_path) {
197 base::ThreadRestrictions::AssertIOAllowed();
199 // NOTE: I suspect we could support longer paths, but that would involve
200 // analyzing all our usage of files.
201 if (from_path.value().length() >= MAX_PATH ||
202 to_path.value().length() >= MAX_PATH) {
203 return false;
205 return (::CopyFile(from_path.value().c_str(), to_path.value().c_str(),
206 false) != 0);
209 bool ShellCopy(const FilePath& from_path, const FilePath& to_path,
210 bool recursive) {
211 base::ThreadRestrictions::AssertIOAllowed();
213 // NOTE: I suspect we could support longer paths, but that would involve
214 // analyzing all our usage of files.
215 if (from_path.value().length() >= MAX_PATH ||
216 to_path.value().length() >= MAX_PATH) {
217 return false;
220 // SHFILEOPSTRUCT wants the path to be terminated with two NULLs,
221 // so we have to use wcscpy because wcscpy_s writes non-NULLs
222 // into the rest of the buffer.
223 wchar_t double_terminated_path_from[MAX_PATH + 1] = {0};
224 wchar_t double_terminated_path_to[MAX_PATH + 1] = {0};
225 #pragma warning(suppress:4996) // don't complain about wcscpy deprecation
226 wcscpy(double_terminated_path_from, from_path.value().c_str());
227 #pragma warning(suppress:4996) // don't complain about wcscpy deprecation
228 wcscpy(double_terminated_path_to, to_path.value().c_str());
230 SHFILEOPSTRUCT file_operation = {0};
231 file_operation.wFunc = FO_COPY;
232 file_operation.pFrom = double_terminated_path_from;
233 file_operation.pTo = double_terminated_path_to;
234 file_operation.fFlags = FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMATION |
235 FOF_NOCONFIRMMKDIR;
236 if (!recursive)
237 file_operation.fFlags |= FOF_NORECURSION | FOF_FILESONLY;
239 return (SHFileOperation(&file_operation) == 0);
242 bool CopyDirectory(const FilePath& from_path, const FilePath& to_path,
243 bool recursive) {
244 base::ThreadRestrictions::AssertIOAllowed();
246 if (recursive)
247 return ShellCopy(from_path, to_path, true);
249 // The following code assumes that from path is a directory.
250 DCHECK(DirectoryExists(from_path));
252 // Instead of creating a new directory, we copy the old one to include the
253 // security information of the folder as part of the copy.
254 if (!PathExists(to_path)) {
255 // Except that Vista fails to do that, and instead do a recursive copy if
256 // the target directory doesn't exist.
257 if (base::win::GetVersion() >= base::win::VERSION_VISTA)
258 CreateDirectory(to_path);
259 else
260 ShellCopy(from_path, to_path, false);
263 FilePath directory = from_path.Append(L"*.*");
264 return ShellCopy(directory, to_path, false);
267 bool CopyAndDeleteDirectory(const FilePath& from_path,
268 const FilePath& to_path) {
269 base::ThreadRestrictions::AssertIOAllowed();
270 if (CopyDirectory(from_path, to_path, true)) {
271 if (Delete(from_path, true)) {
272 return true;
274 // Like Move, this function is not transactional, so we just
275 // leave the copied bits behind if deleting from_path fails.
276 // If to_path exists previously then we have already overwritten
277 // it by now, we don't get better off by deleting the new bits.
279 return false;
283 bool PathExists(const FilePath& path) {
284 base::ThreadRestrictions::AssertIOAllowed();
285 return (GetFileAttributes(path.value().c_str()) != INVALID_FILE_ATTRIBUTES);
288 bool PathIsWritable(const FilePath& path) {
289 base::ThreadRestrictions::AssertIOAllowed();
290 HANDLE dir =
291 CreateFile(path.value().c_str(), FILE_ADD_FILE, kFileShareAll,
292 NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
294 if (dir == INVALID_HANDLE_VALUE)
295 return false;
297 CloseHandle(dir);
298 return true;
301 bool DirectoryExists(const FilePath& path) {
302 base::ThreadRestrictions::AssertIOAllowed();
303 DWORD fileattr = GetFileAttributes(path.value().c_str());
304 if (fileattr != INVALID_FILE_ATTRIBUTES)
305 return (fileattr & FILE_ATTRIBUTE_DIRECTORY) != 0;
306 return false;
309 bool GetFileCreationLocalTimeFromHandle(HANDLE file_handle,
310 LPSYSTEMTIME creation_time) {
311 base::ThreadRestrictions::AssertIOAllowed();
312 if (!file_handle)
313 return false;
315 FILETIME utc_filetime;
316 if (!GetFileTime(file_handle, &utc_filetime, NULL, NULL))
317 return false;
319 FILETIME local_filetime;
320 if (!FileTimeToLocalFileTime(&utc_filetime, &local_filetime))
321 return false;
323 return !!FileTimeToSystemTime(&local_filetime, creation_time);
326 bool GetFileCreationLocalTime(const std::wstring& filename,
327 LPSYSTEMTIME creation_time) {
328 base::ThreadRestrictions::AssertIOAllowed();
329 base::win::ScopedHandle file_handle(
330 CreateFile(filename.c_str(), GENERIC_READ, kFileShareAll, NULL,
331 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL));
332 return GetFileCreationLocalTimeFromHandle(file_handle.Get(), creation_time);
335 bool ResolveShortcut(FilePath* path) {
336 base::ThreadRestrictions::AssertIOAllowed();
338 HRESULT result;
339 base::win::ScopedComPtr<IShellLink> i_shell_link;
340 bool is_resolved = false;
342 // Get pointer to the IShellLink interface
343 result = i_shell_link.CreateInstance(CLSID_ShellLink, NULL,
344 CLSCTX_INPROC_SERVER);
345 if (SUCCEEDED(result)) {
346 base::win::ScopedComPtr<IPersistFile> persist;
347 // Query IShellLink for the IPersistFile interface
348 result = persist.QueryFrom(i_shell_link);
349 if (SUCCEEDED(result)) {
350 WCHAR temp_path[MAX_PATH];
351 // Load the shell link
352 result = persist->Load(path->value().c_str(), STGM_READ);
353 if (SUCCEEDED(result)) {
354 // Try to find the target of a shortcut
355 result = i_shell_link->Resolve(0, SLR_NO_UI);
356 if (SUCCEEDED(result)) {
357 result = i_shell_link->GetPath(temp_path, MAX_PATH,
358 NULL, SLGP_UNCPRIORITY);
359 *path = FilePath(temp_path);
360 is_resolved = true;
366 return is_resolved;
369 bool CreateOrUpdateShortcutLink(const wchar_t *source,
370 const wchar_t *destination,
371 const wchar_t *working_dir,
372 const wchar_t *arguments,
373 const wchar_t *description,
374 const wchar_t *icon,
375 int icon_index,
376 const wchar_t* app_id,
377 uint32 options) {
378 base::ThreadRestrictions::AssertIOAllowed();
380 bool create = (options & SHORTCUT_CREATE_ALWAYS) != 0;
382 // |source| is required when SHORTCUT_CREATE_ALWAYS is specified.
383 DCHECK(source || !create);
385 // Length of arguments and description must be less than MAX_PATH.
386 DCHECK(lstrlen(arguments) < MAX_PATH);
387 DCHECK(lstrlen(description) < MAX_PATH);
389 base::win::ScopedComPtr<IShellLink> i_shell_link;
390 base::win::ScopedComPtr<IPersistFile> i_persist_file;
392 // Get pointer to the IShellLink interface
393 if (FAILED(i_shell_link.CreateInstance(CLSID_ShellLink, NULL,
394 CLSCTX_INPROC_SERVER)) ||
395 FAILED(i_persist_file.QueryFrom(i_shell_link))) {
396 return false;
399 if (!create && FAILED(i_persist_file->Load(destination, STGM_READWRITE)))
400 return false;
402 if ((source || create) && FAILED(i_shell_link->SetPath(source)))
403 return false;
405 if (working_dir && FAILED(i_shell_link->SetWorkingDirectory(working_dir)))
406 return false;
408 if (arguments && FAILED(i_shell_link->SetArguments(arguments)))
409 return false;
411 if (description && FAILED(i_shell_link->SetDescription(description)))
412 return false;
414 if (icon && FAILED(i_shell_link->SetIconLocation(icon, icon_index)))
415 return false;
417 bool is_dual_mode = (options & SHORTCUT_DUAL_MODE) != 0;
418 if ((app_id || is_dual_mode) &&
419 base::win::GetVersion() >= base::win::VERSION_WIN7) {
420 base::win::ScopedComPtr<IPropertyStore> property_store;
421 if (FAILED(property_store.QueryFrom(i_shell_link)) || !property_store.get())
422 return false;
424 if (app_id && !base::win::SetAppIdForPropertyStore(property_store, app_id))
425 return false;
426 if (is_dual_mode &&
427 !base::win::SetDualModeForPropertyStore(property_store)) {
428 return false;
432 HRESULT result = i_persist_file->Save(destination, TRUE);
434 // If we successfully updated the icon, notify the shell that we have done so.
435 if (!create && SUCCEEDED(result)) {
436 // Release the interfaces in case the SHChangeNotify call below depends on
437 // the operations above being fully completed.
438 i_persist_file.Release();
439 i_shell_link.Release();
441 SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, NULL, NULL);
444 return SUCCEEDED(result);
447 bool TaskbarPinShortcutLink(const wchar_t* shortcut) {
448 base::ThreadRestrictions::AssertIOAllowed();
450 // "Pin to taskbar" is only supported after Win7.
451 if (base::win::GetVersion() < base::win::VERSION_WIN7)
452 return false;
454 int result = reinterpret_cast<int>(ShellExecute(NULL, L"taskbarpin", shortcut,
455 NULL, NULL, 0));
456 return result > 32;
459 bool TaskbarUnpinShortcutLink(const wchar_t* shortcut) {
460 base::ThreadRestrictions::AssertIOAllowed();
462 // "Unpin from taskbar" is only supported after Win7.
463 if (base::win::GetVersion() < base::win::VERSION_WIN7)
464 return false;
466 int result = reinterpret_cast<int>(ShellExecute(NULL, L"taskbarunpin",
467 shortcut, NULL, NULL, 0));
468 return result > 32;
471 bool GetTempDir(FilePath* path) {
472 base::ThreadRestrictions::AssertIOAllowed();
474 wchar_t temp_path[MAX_PATH + 1];
475 DWORD path_len = ::GetTempPath(MAX_PATH, temp_path);
476 if (path_len >= MAX_PATH || path_len <= 0)
477 return false;
478 // TODO(evanm): the old behavior of this function was to always strip the
479 // trailing slash. We duplicate this here, but it shouldn't be necessary
480 // when everyone is using the appropriate FilePath APIs.
481 *path = FilePath(temp_path).StripTrailingSeparators();
482 return true;
485 bool GetShmemTempDir(FilePath* path, bool executable) {
486 return GetTempDir(path);
489 bool CreateTemporaryFile(FilePath* path) {
490 base::ThreadRestrictions::AssertIOAllowed();
492 FilePath temp_file;
494 if (!GetTempDir(path))
495 return false;
497 if (CreateTemporaryFileInDir(*path, &temp_file)) {
498 *path = temp_file;
499 return true;
502 return false;
505 FILE* CreateAndOpenTemporaryShmemFile(FilePath* path, bool executable) {
506 base::ThreadRestrictions::AssertIOAllowed();
507 return CreateAndOpenTemporaryFile(path);
510 // On POSIX we have semantics to create and open a temporary file
511 // atomically.
512 // TODO(jrg): is there equivalent call to use on Windows instead of
513 // going 2-step?
514 FILE* CreateAndOpenTemporaryFileInDir(const FilePath& dir, FilePath* path) {
515 base::ThreadRestrictions::AssertIOAllowed();
516 if (!CreateTemporaryFileInDir(dir, path)) {
517 return NULL;
519 // Open file in binary mode, to avoid problems with fwrite. On Windows
520 // it replaces \n's with \r\n's, which may surprise you.
521 // Reference: http://msdn.microsoft.com/en-us/library/h9t88zwz(VS.71).aspx
522 return OpenFile(*path, "wb+");
525 bool CreateTemporaryFileInDir(const FilePath& dir,
526 FilePath* temp_file) {
527 base::ThreadRestrictions::AssertIOAllowed();
529 wchar_t temp_name[MAX_PATH + 1];
531 if (!GetTempFileName(dir.value().c_str(), L"", 0, temp_name)) {
532 DPLOG(WARNING) << "Failed to get temporary file name in " << dir.value();
533 return false;
536 DWORD path_len = GetLongPathName(temp_name, temp_name, MAX_PATH);
537 if (path_len > MAX_PATH + 1 || path_len == 0) {
538 DPLOG(WARNING) << "Failed to get long path name for " << temp_name;
539 return false;
542 std::wstring temp_file_str;
543 temp_file_str.assign(temp_name, path_len);
544 *temp_file = FilePath(temp_file_str);
545 return true;
548 bool CreateTemporaryDirInDir(const FilePath& base_dir,
549 const FilePath::StringType& prefix,
550 FilePath* new_dir) {
551 base::ThreadRestrictions::AssertIOAllowed();
553 FilePath path_to_create;
554 srand(static_cast<uint32>(time(NULL)));
556 for (int count = 0; count < 50; ++count) {
557 // Try create a new temporary directory with random generated name. If
558 // the one exists, keep trying another path name until we reach some limit.
559 string16 new_dir_name;
560 new_dir_name.assign(prefix);
561 new_dir_name.append(base::IntToString16(::base::GetCurrentProcId()));
562 new_dir_name.push_back('_');
563 new_dir_name.append(base::IntToString16(rand() % kint16max));
565 path_to_create = base_dir.Append(new_dir_name);
566 if (::CreateDirectory(path_to_create.value().c_str(), NULL)) {
567 *new_dir = path_to_create;
568 return true;
572 return false;
575 bool CreateNewTempDirectory(const FilePath::StringType& prefix,
576 FilePath* new_temp_path) {
577 base::ThreadRestrictions::AssertIOAllowed();
579 FilePath system_temp_dir;
580 if (!GetTempDir(&system_temp_dir))
581 return false;
583 return CreateTemporaryDirInDir(system_temp_dir, prefix, new_temp_path);
586 bool CreateDirectory(const FilePath& full_path) {
587 base::ThreadRestrictions::AssertIOAllowed();
589 // If the path exists, we've succeeded if it's a directory, failed otherwise.
590 const wchar_t* full_path_str = full_path.value().c_str();
591 DWORD fileattr = ::GetFileAttributes(full_path_str);
592 if (fileattr != INVALID_FILE_ATTRIBUTES) {
593 if ((fileattr & FILE_ATTRIBUTE_DIRECTORY) != 0) {
594 DVLOG(1) << "CreateDirectory(" << full_path_str << "), "
595 << "directory already exists.";
596 return true;
598 DLOG(WARNING) << "CreateDirectory(" << full_path_str << "), "
599 << "conflicts with existing file.";
600 return false;
603 // Invariant: Path does not exist as file or directory.
605 // Attempt to create the parent recursively. This will immediately return
606 // true if it already exists, otherwise will create all required parent
607 // directories starting with the highest-level missing parent.
608 FilePath parent_path(full_path.DirName());
609 if (parent_path.value() == full_path.value()) {
610 return false;
612 if (!CreateDirectory(parent_path)) {
613 DLOG(WARNING) << "Failed to create one of the parent directories.";
614 return false;
617 if (!::CreateDirectory(full_path_str, NULL)) {
618 DWORD error_code = ::GetLastError();
619 if (error_code == ERROR_ALREADY_EXISTS && DirectoryExists(full_path)) {
620 // This error code ERROR_ALREADY_EXISTS doesn't indicate whether we
621 // were racing with someone creating the same directory, or a file
622 // with the same path. If DirectoryExists() returns true, we lost the
623 // race to create the same directory.
624 return true;
625 } else {
626 DLOG(WARNING) << "Failed to create directory " << full_path_str
627 << ", last error is " << error_code << ".";
628 return false;
630 } else {
631 return true;
635 // TODO(rkc): Work out if we want to handle NTFS junctions here or not, handle
636 // them if we do decide to.
637 bool IsLink(const FilePath& file_path) {
638 return false;
641 bool GetFileInfo(const FilePath& file_path, base::PlatformFileInfo* results) {
642 base::ThreadRestrictions::AssertIOAllowed();
644 WIN32_FILE_ATTRIBUTE_DATA attr;
645 if (!GetFileAttributesEx(file_path.value().c_str(),
646 GetFileExInfoStandard, &attr)) {
647 return false;
650 ULARGE_INTEGER size;
651 size.HighPart = attr.nFileSizeHigh;
652 size.LowPart = attr.nFileSizeLow;
653 results->size = size.QuadPart;
655 results->is_directory =
656 (attr.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
657 results->last_modified = base::Time::FromFileTime(attr.ftLastWriteTime);
658 results->last_accessed = base::Time::FromFileTime(attr.ftLastAccessTime);
659 results->creation_time = base::Time::FromFileTime(attr.ftCreationTime);
661 return true;
664 FILE* OpenFile(const FilePath& filename, const char* mode) {
665 base::ThreadRestrictions::AssertIOAllowed();
666 std::wstring w_mode = ASCIIToWide(std::string(mode));
667 return _wfsopen(filename.value().c_str(), w_mode.c_str(), _SH_DENYNO);
670 FILE* OpenFile(const std::string& filename, const char* mode) {
671 base::ThreadRestrictions::AssertIOAllowed();
672 return _fsopen(filename.c_str(), mode, _SH_DENYNO);
675 int ReadFile(const FilePath& filename, char* data, int size) {
676 base::ThreadRestrictions::AssertIOAllowed();
677 base::win::ScopedHandle file(CreateFile(filename.value().c_str(),
678 GENERIC_READ,
679 FILE_SHARE_READ | FILE_SHARE_WRITE,
680 NULL,
681 OPEN_EXISTING,
682 FILE_FLAG_SEQUENTIAL_SCAN,
683 NULL));
684 if (!file)
685 return -1;
687 DWORD read;
688 if (::ReadFile(file, data, size, &read, NULL) &&
689 static_cast<int>(read) == size)
690 return read;
691 return -1;
694 int WriteFile(const FilePath& filename, const char* data, int size) {
695 base::ThreadRestrictions::AssertIOAllowed();
696 base::win::ScopedHandle file(CreateFile(filename.value().c_str(),
697 GENERIC_WRITE,
699 NULL,
700 CREATE_ALWAYS,
702 NULL));
703 if (!file) {
704 DLOG(WARNING) << "CreateFile failed for path " << filename.value()
705 << " error code=" << GetLastError();
706 return -1;
709 DWORD written;
710 BOOL result = ::WriteFile(file, data, size, &written, NULL);
711 if (result && static_cast<int>(written) == size)
712 return written;
714 if (!result) {
715 // WriteFile failed.
716 DLOG(WARNING) << "writing file " << filename.value()
717 << " failed, error code=" << GetLastError();
718 } else {
719 // Didn't write all the bytes.
720 DLOG(WARNING) << "wrote" << written << " bytes to "
721 << filename.value() << " expected " << size;
723 return -1;
726 int AppendToFile(const FilePath& filename, const char* data, int size) {
727 base::ThreadRestrictions::AssertIOAllowed();
728 base::win::ScopedHandle file(CreateFile(filename.value().c_str(),
729 FILE_APPEND_DATA,
731 NULL,
732 OPEN_EXISTING,
734 NULL));
735 if (!file) {
736 DLOG(WARNING) << "CreateFile failed for path " << filename.value()
737 << " error code=" << GetLastError();
738 return -1;
741 DWORD written;
742 BOOL result = ::WriteFile(file, data, size, &written, NULL);
743 if (result && static_cast<int>(written) == size)
744 return written;
746 if (!result) {
747 // WriteFile failed.
748 DLOG(WARNING) << "writing file " << filename.value()
749 << " failed, error code=" << GetLastError();
750 } else {
751 // Didn't write all the bytes.
752 DLOG(WARNING) << "wrote" << written << " bytes to "
753 << filename.value() << " expected " << size;
755 return -1;
758 // Gets the current working directory for the process.
759 bool GetCurrentDirectory(FilePath* dir) {
760 base::ThreadRestrictions::AssertIOAllowed();
762 wchar_t system_buffer[MAX_PATH];
763 system_buffer[0] = 0;
764 DWORD len = ::GetCurrentDirectory(MAX_PATH, system_buffer);
765 if (len == 0 || len > MAX_PATH)
766 return false;
767 // TODO(evanm): the old behavior of this function was to always strip the
768 // trailing slash. We duplicate this here, but it shouldn't be necessary
769 // when everyone is using the appropriate FilePath APIs.
770 std::wstring dir_str(system_buffer);
771 *dir = FilePath(dir_str).StripTrailingSeparators();
772 return true;
775 // Sets the current working directory for the process.
776 bool SetCurrentDirectory(const FilePath& directory) {
777 base::ThreadRestrictions::AssertIOAllowed();
778 BOOL ret = ::SetCurrentDirectory(directory.value().c_str());
779 return ret != 0;
782 ///////////////////////////////////////////////
783 // FileEnumerator
785 FileEnumerator::FileEnumerator(const FilePath& root_path,
786 bool recursive,
787 FileType file_type)
788 : recursive_(recursive),
789 file_type_(file_type),
790 has_find_data_(false),
791 find_handle_(INVALID_HANDLE_VALUE) {
792 // INCLUDE_DOT_DOT must not be specified if recursive.
793 DCHECK(!(recursive && (INCLUDE_DOT_DOT & file_type_)));
794 memset(&find_data_, 0, sizeof(find_data_));
795 pending_paths_.push(root_path);
798 FileEnumerator::FileEnumerator(const FilePath& root_path,
799 bool recursive,
800 FileType file_type,
801 const FilePath::StringType& pattern)
802 : recursive_(recursive),
803 file_type_(file_type),
804 has_find_data_(false),
805 pattern_(pattern),
806 find_handle_(INVALID_HANDLE_VALUE) {
807 // INCLUDE_DOT_DOT must not be specified if recursive.
808 DCHECK(!(recursive && (INCLUDE_DOT_DOT & file_type_)));
809 memset(&find_data_, 0, sizeof(find_data_));
810 pending_paths_.push(root_path);
813 FileEnumerator::~FileEnumerator() {
814 if (find_handle_ != INVALID_HANDLE_VALUE)
815 FindClose(find_handle_);
818 void FileEnumerator::GetFindInfo(FindInfo* info) {
819 DCHECK(info);
821 if (!has_find_data_)
822 return;
824 memcpy(info, &find_data_, sizeof(*info));
827 // static
828 bool FileEnumerator::IsDirectory(const FindInfo& info) {
829 return (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
832 // static
833 bool FileEnumerator::IsLink(const FindInfo& info) {
834 return false;
837 // static
838 FilePath FileEnumerator::GetFilename(const FindInfo& find_info) {
839 return FilePath(find_info.cFileName);
842 // static
843 int64 FileEnumerator::GetFilesize(const FindInfo& find_info) {
844 ULARGE_INTEGER size;
845 size.HighPart = find_info.nFileSizeHigh;
846 size.LowPart = find_info.nFileSizeLow;
847 DCHECK_LE(size.QuadPart, std::numeric_limits<int64>::max());
848 return static_cast<int64>(size.QuadPart);
851 // static
852 base::Time FileEnumerator::GetLastModifiedTime(const FindInfo& find_info) {
853 return base::Time::FromFileTime(find_info.ftLastWriteTime);
856 FilePath FileEnumerator::Next() {
857 base::ThreadRestrictions::AssertIOAllowed();
859 while (has_find_data_ || !pending_paths_.empty()) {
860 if (!has_find_data_) {
861 // The last find FindFirstFile operation is done, prepare a new one.
862 root_path_ = pending_paths_.top();
863 pending_paths_.pop();
865 // Start a new find operation.
866 FilePath src = root_path_;
868 if (pattern_.empty())
869 src = src.Append(L"*"); // No pattern = match everything.
870 else
871 src = src.Append(pattern_);
873 find_handle_ = FindFirstFile(src.value().c_str(), &find_data_);
874 has_find_data_ = true;
875 } else {
876 // Search for the next file/directory.
877 if (!FindNextFile(find_handle_, &find_data_)) {
878 FindClose(find_handle_);
879 find_handle_ = INVALID_HANDLE_VALUE;
883 if (INVALID_HANDLE_VALUE == find_handle_) {
884 has_find_data_ = false;
886 // This is reached when we have finished a directory and are advancing to
887 // the next one in the queue. We applied the pattern (if any) to the files
888 // in the root search directory, but for those directories which were
889 // matched, we want to enumerate all files inside them. This will happen
890 // when the handle is empty.
891 pattern_ = FilePath::StringType();
893 continue;
896 FilePath cur_file(find_data_.cFileName);
897 if (ShouldSkip(cur_file))
898 continue;
900 // Construct the absolute filename.
901 cur_file = root_path_.Append(find_data_.cFileName);
903 if (find_data_.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
904 if (recursive_) {
905 // If |cur_file| is a directory, and we are doing recursive searching,
906 // add it to pending_paths_ so we scan it after we finish scanning this
907 // directory.
908 pending_paths_.push(cur_file);
910 if (file_type_ & FileEnumerator::DIRECTORIES)
911 return cur_file;
912 } else if (file_type_ & FileEnumerator::FILES) {
913 return cur_file;
917 return FilePath();
920 ///////////////////////////////////////////////
921 // MemoryMappedFile
923 MemoryMappedFile::MemoryMappedFile()
924 : file_(INVALID_HANDLE_VALUE),
925 file_mapping_(INVALID_HANDLE_VALUE),
926 data_(NULL),
927 length_(INVALID_FILE_SIZE) {
930 bool MemoryMappedFile::InitializeAsImageSection(const FilePath& file_name) {
931 if (IsValid())
932 return false;
933 file_ = base::CreatePlatformFile(
934 file_name, base::PLATFORM_FILE_OPEN | base::PLATFORM_FILE_READ,
935 NULL, NULL);
937 if (file_ == base::kInvalidPlatformFileValue) {
938 DLOG(ERROR) << "Couldn't open " << file_name.value();
939 return false;
942 if (!MapFileToMemoryInternalEx(SEC_IMAGE)) {
943 CloseHandles();
944 return false;
947 return true;
950 bool MemoryMappedFile::MapFileToMemoryInternal() {
951 return MapFileToMemoryInternalEx(0);
954 bool MemoryMappedFile::MapFileToMemoryInternalEx(int flags) {
955 base::ThreadRestrictions::AssertIOAllowed();
957 if (file_ == INVALID_HANDLE_VALUE)
958 return false;
960 length_ = ::GetFileSize(file_, NULL);
961 if (length_ == INVALID_FILE_SIZE)
962 return false;
964 file_mapping_ = ::CreateFileMapping(file_, NULL, PAGE_READONLY | flags,
965 0, 0, NULL);
966 if (!file_mapping_) {
967 // According to msdn, system error codes are only reserved up to 15999.
968 // http://msdn.microsoft.com/en-us/library/ms681381(v=VS.85).aspx.
969 UMA_HISTOGRAM_ENUMERATION("MemoryMappedFile.CreateFileMapping",
970 logging::GetLastSystemErrorCode(), 16000);
971 return false;
974 data_ = static_cast<uint8*>(
975 ::MapViewOfFile(file_mapping_, FILE_MAP_READ, 0, 0, 0));
976 if (!data_) {
977 UMA_HISTOGRAM_ENUMERATION("MemoryMappedFile.MapViewOfFile",
978 logging::GetLastSystemErrorCode(), 16000);
980 return data_ != NULL;
983 void MemoryMappedFile::CloseHandles() {
984 if (data_)
985 ::UnmapViewOfFile(data_);
986 if (file_mapping_ != INVALID_HANDLE_VALUE)
987 ::CloseHandle(file_mapping_);
988 if (file_ != INVALID_HANDLE_VALUE)
989 ::CloseHandle(file_);
991 data_ = NULL;
992 file_mapping_ = file_ = INVALID_HANDLE_VALUE;
993 length_ = INVALID_FILE_SIZE;
996 bool HasFileBeenModifiedSince(const FileEnumerator::FindInfo& find_info,
997 const base::Time& cutoff_time) {
998 base::ThreadRestrictions::AssertIOAllowed();
999 FILETIME file_time = cutoff_time.ToFileTime();
1000 long result = CompareFileTime(&find_info.ftLastWriteTime, // NOLINT
1001 &file_time);
1002 return result == 1 || result == 0;
1005 bool NormalizeFilePath(const FilePath& path, FilePath* real_path) {
1006 base::ThreadRestrictions::AssertIOAllowed();
1007 FilePath mapped_file;
1008 if (!NormalizeToNativeFilePath(path, &mapped_file))
1009 return false;
1010 // NormalizeToNativeFilePath() will return a path that starts with
1011 // "\Device\Harddisk...". Helper DevicePathToDriveLetterPath()
1012 // will find a drive letter which maps to the path's device, so
1013 // that we return a path starting with a drive letter.
1014 return DevicePathToDriveLetterPath(mapped_file, real_path);
1017 bool DevicePathToDriveLetterPath(const FilePath& nt_device_path,
1018 FilePath* out_drive_letter_path) {
1019 base::ThreadRestrictions::AssertIOAllowed();
1021 // Get the mapping of drive letters to device paths.
1022 const int kDriveMappingSize = 1024;
1023 wchar_t drive_mapping[kDriveMappingSize] = {'\0'};
1024 if (!::GetLogicalDriveStrings(kDriveMappingSize - 1, drive_mapping)) {
1025 DLOG(ERROR) << "Failed to get drive mapping.";
1026 return false;
1029 // The drive mapping is a sequence of null terminated strings.
1030 // The last string is empty.
1031 wchar_t* drive_map_ptr = drive_mapping;
1032 wchar_t device_path_as_string[MAX_PATH];
1033 wchar_t drive[] = L" :";
1035 // For each string in the drive mapping, get the junction that links
1036 // to it. If that junction is a prefix of |device_path|, then we
1037 // know that |drive| is the real path prefix.
1038 while (*drive_map_ptr) {
1039 drive[0] = drive_map_ptr[0]; // Copy the drive letter.
1041 if (QueryDosDevice(drive, device_path_as_string, MAX_PATH)) {
1042 FilePath device_path(device_path_as_string);
1043 if (device_path == nt_device_path ||
1044 device_path.IsParent(nt_device_path)) {
1045 *out_drive_letter_path = FilePath(drive +
1046 nt_device_path.value().substr(wcslen(device_path_as_string)));
1047 return true;
1050 // Move to the next drive letter string, which starts one
1051 // increment after the '\0' that terminates the current string.
1052 while (*drive_map_ptr++);
1055 // No drive matched. The path does not start with a device junction
1056 // that is mounted as a drive letter. This means there is no drive
1057 // letter path to the volume that holds |device_path|, so fail.
1058 return false;
1061 bool NormalizeToNativeFilePath(const FilePath& path, FilePath* nt_path) {
1062 base::ThreadRestrictions::AssertIOAllowed();
1063 // In Vista, GetFinalPathNameByHandle() would give us the real path
1064 // from a file handle. If we ever deprecate XP, consider changing the
1065 // code below to a call to GetFinalPathNameByHandle(). The method this
1066 // function uses is explained in the following msdn article:
1067 // http://msdn.microsoft.com/en-us/library/aa366789(VS.85).aspx
1068 base::win::ScopedHandle file_handle(
1069 ::CreateFile(path.value().c_str(),
1070 GENERIC_READ,
1071 kFileShareAll,
1072 NULL,
1073 OPEN_EXISTING,
1074 FILE_ATTRIBUTE_NORMAL,
1075 NULL));
1076 if (!file_handle)
1077 return false;
1079 // Create a file mapping object. Can't easily use MemoryMappedFile, because
1080 // we only map the first byte, and need direct access to the handle. You can
1081 // not map an empty file, this call fails in that case.
1082 base::win::ScopedHandle file_map_handle(
1083 ::CreateFileMapping(file_handle.Get(),
1084 NULL,
1085 PAGE_READONLY,
1087 1, // Just one byte. No need to look at the data.
1088 NULL));
1089 if (!file_map_handle)
1090 return false;
1092 // Use a view of the file to get the path to the file.
1093 void* file_view = MapViewOfFile(file_map_handle.Get(),
1094 FILE_MAP_READ, 0, 0, 1);
1095 if (!file_view)
1096 return false;
1098 // The expansion of |path| into a full path may make it longer.
1099 // GetMappedFileName() will fail if the result is longer than MAX_PATH.
1100 // Pad a bit to be safe. If kMaxPathLength is ever changed to be less
1101 // than MAX_PATH, it would be nessisary to test that GetMappedFileName()
1102 // not return kMaxPathLength. This would mean that only part of the
1103 // path fit in |mapped_file_path|.
1104 const int kMaxPathLength = MAX_PATH + 10;
1105 wchar_t mapped_file_path[kMaxPathLength];
1106 bool success = false;
1107 HANDLE cp = GetCurrentProcess();
1108 if (::GetMappedFileNameW(cp, file_view, mapped_file_path, kMaxPathLength)) {
1109 *nt_path = FilePath(mapped_file_path);
1110 success = true;
1112 ::UnmapViewOfFile(file_view);
1113 return success;
1116 } // namespace file_util