file_util_win.cc revision 513209b27ff55e2841eac0e4120199c23acce758
1// Copyright (c) 2010 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.
4
5#include "base/file_util.h"
6
7#include <windows.h>
8#include <propvarutil.h>
9#include <psapi.h>
10#include <shellapi.h>
11#include <shlobj.h>
12#include <time.h>
13#include <string>
14
15#include "base/file_path.h"
16#include "base/logging.h"
17#include "base/metrics/histogram.h"
18#include "base/win/pe_image.h"
19#include "base/win/scoped_handle.h"
20#include "base/string_number_conversions.h"
21#include "base/string_util.h"
22#include "base/thread_restrictions.h"
23#include "base/time.h"
24#include "base/utf_string_conversions.h"
25#include "base/win_util.h"
26#include "base/win/scoped_comptr.h"
27#include "base/win/windows_version.h"
28
29namespace file_util {
30
31namespace {
32
33const DWORD kFileShareAll =
34    FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
35
36// Helper for NormalizeFilePath(), defined below.
37bool DevicePathToDriveLetterPath(const FilePath& device_path,
38                                 FilePath* drive_letter_path) {
39  base::ThreadRestrictions::AssertIOAllowed();
40
41  // Get the mapping of drive letters to device paths.
42  const int kDriveMappingSize = 1024;
43  wchar_t drive_mapping[kDriveMappingSize] = {'\0'};
44  if (!::GetLogicalDriveStrings(kDriveMappingSize - 1, drive_mapping)) {
45    LOG(ERROR) << "Failed to get drive mapping.";
46    return false;
47  }
48
49  // The drive mapping is a sequence of null terminated strings.
50  // The last string is empty.
51  wchar_t* drive_map_ptr = drive_mapping;
52  wchar_t device_name[MAX_PATH];
53  wchar_t drive[] = L" :";
54
55  // For each string in the drive mapping, get the junction that links
56  // to it.  If that junction is a prefix of |device_path|, then we
57  // know that |drive| is the real path prefix.
58  while(*drive_map_ptr) {
59    drive[0] = drive_map_ptr[0];  // Copy the drive letter.
60
61    if (QueryDosDevice(drive, device_name, MAX_PATH) &&
62        StartsWith(device_path.value(), device_name, true)) {
63      *drive_letter_path = FilePath(drive +
64          device_path.value().substr(wcslen(device_name)));
65      return true;
66    }
67    // Move to the next drive letter string, which starts one
68    // increment after the '\0' that terminates the current string.
69    while(*drive_map_ptr++);
70  }
71
72  // No drive matched.  The path does not start with a device junction
73  // that is mounted as a drive letter.  This means there is no drive
74  // letter path to the volume that holds |device_path|, so fail.
75  return false;
76}
77
78}  // namespace
79
80std::wstring GetDirectoryFromPath(const std::wstring& path) {
81  base::ThreadRestrictions::AssertIOAllowed();
82  wchar_t path_buffer[MAX_PATH];
83  wchar_t* file_ptr = NULL;
84  if (GetFullPathName(path.c_str(), MAX_PATH, path_buffer, &file_ptr) == 0)
85    return L"";
86
87  std::wstring::size_type length =
88      file_ptr ? file_ptr - path_buffer : path.length();
89  std::wstring directory(path, 0, length);
90  return FilePath(directory).StripTrailingSeparators().value();
91}
92
93bool AbsolutePath(FilePath* path) {
94  base::ThreadRestrictions::AssertIOAllowed();
95  wchar_t file_path_buf[MAX_PATH];
96  if (!_wfullpath(file_path_buf, path->value().c_str(), MAX_PATH))
97    return false;
98  *path = FilePath(file_path_buf);
99  return true;
100}
101
102int CountFilesCreatedAfter(const FilePath& path,
103                           const base::Time& comparison_time) {
104  base::ThreadRestrictions::AssertIOAllowed();
105
106  int file_count = 0;
107  FILETIME comparison_filetime(comparison_time.ToFileTime());
108
109  WIN32_FIND_DATA find_file_data;
110  // All files in given dir
111  std::wstring filename_spec = path.Append(L"*").value();
112  HANDLE find_handle = FindFirstFile(filename_spec.c_str(), &find_file_data);
113  if (find_handle != INVALID_HANDLE_VALUE) {
114    do {
115      // Don't count current or parent directories.
116      if ((wcscmp(find_file_data.cFileName, L"..") == 0) ||
117          (wcscmp(find_file_data.cFileName, L".") == 0))
118        continue;
119
120      long result = CompareFileTime(&find_file_data.ftCreationTime,
121                                    &comparison_filetime);
122      // File was created after or on comparison time
123      if ((result == 1) || (result == 0))
124        ++file_count;
125    } while (FindNextFile(find_handle,  &find_file_data));
126    FindClose(find_handle);
127  }
128
129  return file_count;
130}
131
132bool Delete(const FilePath& path, bool recursive) {
133  base::ThreadRestrictions::AssertIOAllowed();
134
135  if (path.value().length() >= MAX_PATH)
136    return false;
137
138  if (!recursive) {
139    // If not recursing, then first check to see if |path| is a directory.
140    // If it is, then remove it with RemoveDirectory.
141    base::PlatformFileInfo file_info;
142    if (GetFileInfo(path, &file_info) && file_info.is_directory)
143      return RemoveDirectory(path.value().c_str()) != 0;
144
145    // Otherwise, it's a file, wildcard or non-existant. Try DeleteFile first
146    // because it should be faster. If DeleteFile fails, then we fall through
147    // to SHFileOperation, which will do the right thing.
148    if (DeleteFile(path.value().c_str()) != 0)
149      return true;
150  }
151
152  // SHFILEOPSTRUCT wants the path to be terminated with two NULLs,
153  // so we have to use wcscpy because wcscpy_s writes non-NULLs
154  // into the rest of the buffer.
155  wchar_t double_terminated_path[MAX_PATH + 1] = {0};
156#pragma warning(suppress:4996)  // don't complain about wcscpy deprecation
157  wcscpy(double_terminated_path, path.value().c_str());
158
159  SHFILEOPSTRUCT file_operation = {0};
160  file_operation.wFunc = FO_DELETE;
161  file_operation.pFrom = double_terminated_path;
162  file_operation.fFlags = FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMATION;
163  if (!recursive)
164    file_operation.fFlags |= FOF_NORECURSION | FOF_FILESONLY;
165  int err = SHFileOperation(&file_operation);
166  // Some versions of Windows return ERROR_FILE_NOT_FOUND (0x2) when deleting
167  // an empty directory and some return 0x402 when they should be returning
168  // ERROR_FILE_NOT_FOUND. MSDN says Vista and up won't return 0x402.
169  return (err == 0 || err == ERROR_FILE_NOT_FOUND || err == 0x402);
170}
171
172bool DeleteAfterReboot(const FilePath& path) {
173  base::ThreadRestrictions::AssertIOAllowed();
174
175  if (path.value().length() >= MAX_PATH)
176    return false;
177
178  return MoveFileEx(path.value().c_str(), NULL,
179                    MOVEFILE_DELAY_UNTIL_REBOOT |
180                        MOVEFILE_REPLACE_EXISTING) != FALSE;
181}
182
183bool Move(const FilePath& from_path, const FilePath& to_path) {
184  base::ThreadRestrictions::AssertIOAllowed();
185
186  // NOTE: I suspect we could support longer paths, but that would involve
187  // analyzing all our usage of files.
188  if (from_path.value().length() >= MAX_PATH ||
189      to_path.value().length() >= MAX_PATH) {
190    return false;
191  }
192  if (MoveFileEx(from_path.value().c_str(), to_path.value().c_str(),
193                 MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING) != 0)
194    return true;
195  if (DirectoryExists(from_path)) {
196    // MoveFileEx fails if moving directory across volumes. We will simulate
197    // the move by using Copy and Delete. Ideally we could check whether
198    // from_path and to_path are indeed in different volumes.
199    return CopyAndDeleteDirectory(from_path, to_path);
200  }
201  return false;
202}
203
204bool ReplaceFile(const FilePath& from_path, const FilePath& to_path) {
205  base::ThreadRestrictions::AssertIOAllowed();
206
207  // Make sure that the target file exists.
208  HANDLE target_file = ::CreateFile(
209      to_path.value().c_str(),
210      0,
211      FILE_SHARE_READ | FILE_SHARE_WRITE,
212      NULL,
213      CREATE_NEW,
214      FILE_ATTRIBUTE_NORMAL,
215      NULL);
216  if (target_file != INVALID_HANDLE_VALUE)
217    ::CloseHandle(target_file);
218  // When writing to a network share, we may not be able to change the ACLs.
219  // Ignore ACL errors then (REPLACEFILE_IGNORE_MERGE_ERRORS).
220  return ::ReplaceFile(to_path.value().c_str(),
221      from_path.value().c_str(), NULL,
222      REPLACEFILE_IGNORE_MERGE_ERRORS, NULL, NULL) ? true : false;
223}
224
225bool CopyFile(const FilePath& from_path, const FilePath& to_path) {
226  base::ThreadRestrictions::AssertIOAllowed();
227
228  // NOTE: I suspect we could support longer paths, but that would involve
229  // analyzing all our usage of files.
230  if (from_path.value().length() >= MAX_PATH ||
231      to_path.value().length() >= MAX_PATH) {
232    return false;
233  }
234  return (::CopyFile(from_path.value().c_str(), to_path.value().c_str(),
235                     false) != 0);
236}
237
238bool ShellCopy(const FilePath& from_path, const FilePath& to_path,
239               bool recursive) {
240  base::ThreadRestrictions::AssertIOAllowed();
241
242  // NOTE: I suspect we could support longer paths, but that would involve
243  // analyzing all our usage of files.
244  if (from_path.value().length() >= MAX_PATH ||
245      to_path.value().length() >= MAX_PATH) {
246    return false;
247  }
248
249  // SHFILEOPSTRUCT wants the path to be terminated with two NULLs,
250  // so we have to use wcscpy because wcscpy_s writes non-NULLs
251  // into the rest of the buffer.
252  wchar_t double_terminated_path_from[MAX_PATH + 1] = {0};
253  wchar_t double_terminated_path_to[MAX_PATH + 1] = {0};
254#pragma warning(suppress:4996)  // don't complain about wcscpy deprecation
255  wcscpy(double_terminated_path_from, from_path.value().c_str());
256#pragma warning(suppress:4996)  // don't complain about wcscpy deprecation
257  wcscpy(double_terminated_path_to, to_path.value().c_str());
258
259  SHFILEOPSTRUCT file_operation = {0};
260  file_operation.wFunc = FO_COPY;
261  file_operation.pFrom = double_terminated_path_from;
262  file_operation.pTo = double_terminated_path_to;
263  file_operation.fFlags = FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMATION |
264                          FOF_NOCONFIRMMKDIR;
265  if (!recursive)
266    file_operation.fFlags |= FOF_NORECURSION | FOF_FILESONLY;
267
268  return (SHFileOperation(&file_operation) == 0);
269}
270
271bool CopyDirectory(const FilePath& from_path, const FilePath& to_path,
272                   bool recursive) {
273  base::ThreadRestrictions::AssertIOAllowed();
274
275  if (recursive)
276    return ShellCopy(from_path, to_path, true);
277
278  // The following code assumes that from path is a directory.
279  DCHECK(DirectoryExists(from_path));
280
281  // Instead of creating a new directory, we copy the old one to include the
282  // security information of the folder as part of the copy.
283  if (!PathExists(to_path)) {
284    // Except that Vista fails to do that, and instead do a recursive copy if
285    // the target directory doesn't exist.
286    if (base::win::GetVersion() >= base::win::VERSION_VISTA)
287      CreateDirectory(to_path);
288    else
289      ShellCopy(from_path, to_path, false);
290  }
291
292  FilePath directory = from_path.Append(L"*.*");
293  return ShellCopy(directory, to_path, false);
294}
295
296bool CopyAndDeleteDirectory(const FilePath& from_path,
297                            const FilePath& to_path) {
298  base::ThreadRestrictions::AssertIOAllowed();
299  if (CopyDirectory(from_path, to_path, true)) {
300    if (Delete(from_path, true)) {
301      return true;
302    }
303    // Like Move, this function is not transactional, so we just
304    // leave the copied bits behind if deleting from_path fails.
305    // If to_path exists previously then we have already overwritten
306    // it by now, we don't get better off by deleting the new bits.
307  }
308  return false;
309}
310
311
312bool PathExists(const FilePath& path) {
313  base::ThreadRestrictions::AssertIOAllowed();
314  return (GetFileAttributes(path.value().c_str()) != INVALID_FILE_ATTRIBUTES);
315}
316
317bool PathIsWritable(const FilePath& path) {
318  base::ThreadRestrictions::AssertIOAllowed();
319  HANDLE dir =
320      CreateFile(path.value().c_str(), FILE_ADD_FILE, kFileShareAll,
321                 NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
322
323  if (dir == INVALID_HANDLE_VALUE)
324    return false;
325
326  CloseHandle(dir);
327  return true;
328}
329
330bool DirectoryExists(const FilePath& path) {
331  base::ThreadRestrictions::AssertIOAllowed();
332  DWORD fileattr = GetFileAttributes(path.value().c_str());
333  if (fileattr != INVALID_FILE_ATTRIBUTES)
334    return (fileattr & FILE_ATTRIBUTE_DIRECTORY) != 0;
335  return false;
336}
337
338bool GetFileCreationLocalTimeFromHandle(HANDLE file_handle,
339                                        LPSYSTEMTIME creation_time) {
340  base::ThreadRestrictions::AssertIOAllowed();
341  if (!file_handle)
342    return false;
343
344  FILETIME utc_filetime;
345  if (!GetFileTime(file_handle, &utc_filetime, NULL, NULL))
346    return false;
347
348  FILETIME local_filetime;
349  if (!FileTimeToLocalFileTime(&utc_filetime, &local_filetime))
350    return false;
351
352  return !!FileTimeToSystemTime(&local_filetime, creation_time);
353}
354
355bool GetFileCreationLocalTime(const std::wstring& filename,
356                              LPSYSTEMTIME creation_time) {
357  base::ThreadRestrictions::AssertIOAllowed();
358  base::win::ScopedHandle file_handle(
359      CreateFile(filename.c_str(), GENERIC_READ, kFileShareAll, NULL,
360                 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL));
361  return GetFileCreationLocalTimeFromHandle(file_handle.Get(), creation_time);
362}
363
364bool ResolveShortcut(FilePath* path) {
365  base::ThreadRestrictions::AssertIOAllowed();
366
367  HRESULT result;
368  base::win::ScopedComPtr<IShellLink> i_shell_link;
369  bool is_resolved = false;
370
371  // Get pointer to the IShellLink interface
372  result = i_shell_link.CreateInstance(CLSID_ShellLink, NULL,
373                                       CLSCTX_INPROC_SERVER);
374  if (SUCCEEDED(result)) {
375    base::win::ScopedComPtr<IPersistFile> persist;
376    // Query IShellLink for the IPersistFile interface
377    result = persist.QueryFrom(i_shell_link);
378    if (SUCCEEDED(result)) {
379      WCHAR temp_path[MAX_PATH];
380      // Load the shell link
381      result = persist->Load(path->value().c_str(), STGM_READ);
382      if (SUCCEEDED(result)) {
383        // Try to find the target of a shortcut
384        result = i_shell_link->Resolve(0, SLR_NO_UI);
385        if (SUCCEEDED(result)) {
386          result = i_shell_link->GetPath(temp_path, MAX_PATH,
387                                  NULL, SLGP_UNCPRIORITY);
388          *path = FilePath(temp_path);
389          is_resolved = true;
390        }
391      }
392    }
393  }
394
395  return is_resolved;
396}
397
398bool CreateShortcutLink(const wchar_t *source, const wchar_t *destination,
399                        const wchar_t *working_dir, const wchar_t *arguments,
400                        const wchar_t *description, const wchar_t *icon,
401                        int icon_index, const wchar_t* app_id) {
402  base::ThreadRestrictions::AssertIOAllowed();
403
404  // Length of arguments and description must be less than MAX_PATH.
405  DCHECK(lstrlen(arguments) < MAX_PATH);
406  DCHECK(lstrlen(description) < MAX_PATH);
407
408  base::win::ScopedComPtr<IShellLink> i_shell_link;
409  base::win::ScopedComPtr<IPersistFile> i_persist_file;
410
411  // Get pointer to the IShellLink interface
412  HRESULT result = i_shell_link.CreateInstance(CLSID_ShellLink, NULL,
413                                               CLSCTX_INPROC_SERVER);
414  if (FAILED(result))
415    return false;
416
417  // Query IShellLink for the IPersistFile interface
418  result = i_persist_file.QueryFrom(i_shell_link);
419  if (FAILED(result))
420    return false;
421
422  if (FAILED(i_shell_link->SetPath(source)))
423    return false;
424
425  if (working_dir && FAILED(i_shell_link->SetWorkingDirectory(working_dir)))
426    return false;
427
428  if (arguments && FAILED(i_shell_link->SetArguments(arguments)))
429    return false;
430
431  if (description && FAILED(i_shell_link->SetDescription(description)))
432    return false;
433
434  if (icon && FAILED(i_shell_link->SetIconLocation(icon, icon_index)))
435    return false;
436
437  if (app_id && (base::win::GetVersion() >= base::win::VERSION_WIN7)) {
438    base::win::ScopedComPtr<IPropertyStore> property_store;
439    if (FAILED(property_store.QueryFrom(i_shell_link)))
440      return false;
441
442    if (!win_util::SetAppIdForPropertyStore(property_store, app_id))
443      return false;
444  }
445
446  result = i_persist_file->Save(destination, TRUE);
447  return SUCCEEDED(result);
448}
449
450
451bool UpdateShortcutLink(const wchar_t *source, const wchar_t *destination,
452                        const wchar_t *working_dir, const wchar_t *arguments,
453                        const wchar_t *description, const wchar_t *icon,
454                        int icon_index, const wchar_t* app_id) {
455  base::ThreadRestrictions::AssertIOAllowed();
456
457  // Length of arguments and description must be less than MAX_PATH.
458  DCHECK(lstrlen(arguments) < MAX_PATH);
459  DCHECK(lstrlen(description) < MAX_PATH);
460
461  // Get pointer to the IPersistFile interface and load existing link
462  base::win::ScopedComPtr<IShellLink> i_shell_link;
463  if (FAILED(i_shell_link.CreateInstance(CLSID_ShellLink, NULL,
464                                         CLSCTX_INPROC_SERVER)))
465    return false;
466
467  base::win::ScopedComPtr<IPersistFile> i_persist_file;
468  if (FAILED(i_persist_file.QueryFrom(i_shell_link)))
469    return false;
470
471  if (FAILED(i_persist_file->Load(destination, STGM_READWRITE)))
472    return false;
473
474  if (source && FAILED(i_shell_link->SetPath(source)))
475    return false;
476
477  if (working_dir && FAILED(i_shell_link->SetWorkingDirectory(working_dir)))
478    return false;
479
480  if (arguments && FAILED(i_shell_link->SetArguments(arguments)))
481    return false;
482
483  if (description && FAILED(i_shell_link->SetDescription(description)))
484    return false;
485
486  if (icon && FAILED(i_shell_link->SetIconLocation(icon, icon_index)))
487    return false;
488
489  if (app_id && base::win::GetVersion() >= base::win::VERSION_WIN7) {
490    base::win::ScopedComPtr<IPropertyStore> property_store;
491    if (FAILED(property_store.QueryFrom(i_shell_link)))
492      return false;
493
494    if (!win_util::SetAppIdForPropertyStore(property_store, app_id))
495      return false;
496  }
497
498  HRESULT result = i_persist_file->Save(destination, TRUE);
499  return SUCCEEDED(result);
500}
501
502bool TaskbarPinShortcutLink(const wchar_t* shortcut) {
503  base::ThreadRestrictions::AssertIOAllowed();
504
505  // "Pin to taskbar" is only supported after Win7.
506  if (base::win::GetVersion() < base::win::VERSION_WIN7)
507    return false;
508
509  int result = reinterpret_cast<int>(ShellExecute(NULL, L"taskbarpin", shortcut,
510      NULL, NULL, 0));
511  return result > 32;
512}
513
514bool TaskbarUnpinShortcutLink(const wchar_t* shortcut) {
515  base::ThreadRestrictions::AssertIOAllowed();
516
517  // "Unpin from taskbar" is only supported after Win7.
518  if (base::win::GetVersion() < base::win::VERSION_WIN7)
519    return false;
520
521  int result = reinterpret_cast<int>(ShellExecute(NULL, L"taskbarunpin",
522      shortcut, NULL, NULL, 0));
523  return result > 32;
524}
525
526bool GetTempDir(FilePath* path) {
527  base::ThreadRestrictions::AssertIOAllowed();
528
529  wchar_t temp_path[MAX_PATH + 1];
530  DWORD path_len = ::GetTempPath(MAX_PATH, temp_path);
531  if (path_len >= MAX_PATH || path_len <= 0)
532    return false;
533  // TODO(evanm): the old behavior of this function was to always strip the
534  // trailing slash.  We duplicate this here, but it shouldn't be necessary
535  // when everyone is using the appropriate FilePath APIs.
536  *path = FilePath(temp_path).StripTrailingSeparators();
537  return true;
538}
539
540bool GetShmemTempDir(FilePath* path) {
541  return GetTempDir(path);
542}
543
544bool CreateTemporaryFile(FilePath* path) {
545  base::ThreadRestrictions::AssertIOAllowed();
546
547  FilePath temp_file;
548
549  if (!GetTempDir(path))
550    return false;
551
552  if (CreateTemporaryFileInDir(*path, &temp_file)) {
553    *path = temp_file;
554    return true;
555  }
556
557  return false;
558}
559
560FILE* CreateAndOpenTemporaryShmemFile(FilePath* path) {
561  base::ThreadRestrictions::AssertIOAllowed();
562  return CreateAndOpenTemporaryFile(path);
563}
564
565// On POSIX we have semantics to create and open a temporary file
566// atomically.
567// TODO(jrg): is there equivalent call to use on Windows instead of
568// going 2-step?
569FILE* CreateAndOpenTemporaryFileInDir(const FilePath& dir, FilePath* path) {
570  base::ThreadRestrictions::AssertIOAllowed();
571  if (!CreateTemporaryFileInDir(dir, path)) {
572    return NULL;
573  }
574  // Open file in binary mode, to avoid problems with fwrite. On Windows
575  // it replaces \n's with \r\n's, which may surprise you.
576  // Reference: http://msdn.microsoft.com/en-us/library/h9t88zwz(VS.71).aspx
577  return OpenFile(*path, "wb+");
578}
579
580bool CreateTemporaryFileInDir(const FilePath& dir,
581                              FilePath* temp_file) {
582  base::ThreadRestrictions::AssertIOAllowed();
583
584  wchar_t temp_name[MAX_PATH + 1];
585
586  if (!GetTempFileName(dir.value().c_str(), L"", 0, temp_name)) {
587    PLOG(WARNING) << "Failed to get temporary file name in " << dir.value();
588    return false;
589  }
590
591  DWORD path_len = GetLongPathName(temp_name, temp_name, MAX_PATH);
592  if (path_len > MAX_PATH + 1 || path_len == 0) {
593    PLOG(WARNING) << "Failed to get long path name for " << temp_name;
594    return false;
595  }
596
597  std::wstring temp_file_str;
598  temp_file_str.assign(temp_name, path_len);
599  *temp_file = FilePath(temp_file_str);
600  return true;
601}
602
603bool CreateTemporaryDirInDir(const FilePath& base_dir,
604                             const FilePath::StringType& prefix,
605                             FilePath* new_dir) {
606  base::ThreadRestrictions::AssertIOAllowed();
607
608  FilePath path_to_create;
609  srand(static_cast<uint32>(time(NULL)));
610
611  for (int count = 0; count < 50; ++count) {
612    // Try create a new temporary directory with random generated name. If
613    // the one exists, keep trying another path name until we reach some limit.
614    path_to_create = base_dir;
615
616    string16 new_dir_name;
617    new_dir_name.assign(prefix);
618    new_dir_name.append(base::IntToString16(rand() % kint16max));
619
620    path_to_create = path_to_create.Append(new_dir_name);
621    if (::CreateDirectory(path_to_create.value().c_str(), NULL)) {
622      *new_dir = path_to_create;
623      return true;
624    }
625  }
626
627  return false;
628}
629
630bool CreateNewTempDirectory(const FilePath::StringType& prefix,
631                            FilePath* new_temp_path) {
632  base::ThreadRestrictions::AssertIOAllowed();
633
634  FilePath system_temp_dir;
635  if (!GetTempDir(&system_temp_dir))
636    return false;
637
638  return CreateTemporaryDirInDir(system_temp_dir, prefix, new_temp_path);
639}
640
641bool CreateDirectory(const FilePath& full_path) {
642  base::ThreadRestrictions::AssertIOAllowed();
643
644  // If the path exists, we've succeeded if it's a directory, failed otherwise.
645  const wchar_t* full_path_str = full_path.value().c_str();
646  DWORD fileattr = ::GetFileAttributes(full_path_str);
647  if (fileattr != INVALID_FILE_ATTRIBUTES) {
648    if ((fileattr & FILE_ATTRIBUTE_DIRECTORY) != 0) {
649      DVLOG(1) << "CreateDirectory(" << full_path_str << "), "
650               << "directory already exists.";
651      return true;
652    }
653    LOG(WARNING) << "CreateDirectory(" << full_path_str << "), "
654                 << "conflicts with existing file.";
655    return false;
656  }
657
658  // Invariant:  Path does not exist as file or directory.
659
660  // Attempt to create the parent recursively.  This will immediately return
661  // true if it already exists, otherwise will create all required parent
662  // directories starting with the highest-level missing parent.
663  FilePath parent_path(full_path.DirName());
664  if (parent_path.value() == full_path.value()) {
665    return false;
666  }
667  if (!CreateDirectory(parent_path)) {
668    DLOG(WARNING) << "Failed to create one of the parent directories.";
669    return false;
670  }
671
672  if (!::CreateDirectory(full_path_str, NULL)) {
673    DWORD error_code = ::GetLastError();
674    if (error_code == ERROR_ALREADY_EXISTS && DirectoryExists(full_path)) {
675      // This error code doesn't indicate whether we were racing with someone
676      // creating the same directory, or a file with the same path, therefore
677      // we check.
678      return true;
679    } else {
680      LOG(WARNING) << "Failed to create directory " << full_path_str
681                   << ", last error is " << error_code << ".";
682      return false;
683    }
684  } else {
685    return true;
686  }
687}
688
689bool GetFileInfo(const FilePath& file_path, base::PlatformFileInfo* results) {
690  base::ThreadRestrictions::AssertIOAllowed();
691
692  WIN32_FILE_ATTRIBUTE_DATA attr;
693  if (!GetFileAttributesEx(file_path.value().c_str(),
694                           GetFileExInfoStandard, &attr)) {
695    return false;
696  }
697
698  ULARGE_INTEGER size;
699  size.HighPart = attr.nFileSizeHigh;
700  size.LowPart = attr.nFileSizeLow;
701  results->size = size.QuadPart;
702
703  results->is_directory =
704      (attr.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
705  results->last_modified = base::Time::FromFileTime(attr.ftLastWriteTime);
706  results->last_accessed = base::Time::FromFileTime(attr.ftLastAccessTime);
707  results->creation_time = base::Time::FromFileTime(attr.ftCreationTime);
708
709  return true;
710}
711
712FILE* OpenFile(const FilePath& filename, const char* mode) {
713  base::ThreadRestrictions::AssertIOAllowed();
714  std::wstring w_mode = ASCIIToWide(std::string(mode));
715  return _wfsopen(filename.value().c_str(), w_mode.c_str(), _SH_DENYNO);
716}
717
718FILE* OpenFile(const std::string& filename, const char* mode) {
719  base::ThreadRestrictions::AssertIOAllowed();
720  return _fsopen(filename.c_str(), mode, _SH_DENYNO);
721}
722
723int ReadFile(const FilePath& filename, char* data, int size) {
724  base::ThreadRestrictions::AssertIOAllowed();
725  base::win::ScopedHandle file(CreateFile(filename.value().c_str(),
726                                          GENERIC_READ,
727                                          FILE_SHARE_READ | FILE_SHARE_WRITE,
728                                          NULL,
729                                          OPEN_EXISTING,
730                                          FILE_FLAG_SEQUENTIAL_SCAN,
731                                          NULL));
732  if (!file)
733    return -1;
734
735  DWORD read;
736  if (::ReadFile(file, data, size, &read, NULL) &&
737      static_cast<int>(read) == size)
738    return read;
739  return -1;
740}
741
742int WriteFile(const FilePath& filename, const char* data, int size) {
743  base::ThreadRestrictions::AssertIOAllowed();
744  base::win::ScopedHandle file(CreateFile(filename.value().c_str(),
745                                          GENERIC_WRITE,
746                                          0,
747                                          NULL,
748                                          CREATE_ALWAYS,
749                                          0,
750                                          NULL));
751  if (!file) {
752    LOG(WARNING) << "CreateFile failed for path " << filename.value() <<
753        " error code=" << GetLastError() <<
754        " error text=" << win_util::FormatLastWin32Error();
755    return -1;
756  }
757
758  DWORD written;
759  BOOL result = ::WriteFile(file, data, size, &written, NULL);
760  if (result && static_cast<int>(written) == size)
761    return written;
762
763  if (!result) {
764    // WriteFile failed.
765    LOG(WARNING) << "writing file " << filename.value() <<
766        " failed, error code=" << GetLastError() <<
767        " description=" << win_util::FormatLastWin32Error();
768  } else {
769    // Didn't write all the bytes.
770    LOG(WARNING) << "wrote" << written << " bytes to " <<
771        filename.value() << " expected " << size;
772  }
773  return -1;
774}
775
776bool RenameFileAndResetSecurityDescriptor(const FilePath& source_file_path,
777                                          const FilePath& target_file_path) {
778  base::ThreadRestrictions::AssertIOAllowed();
779
780  // The parameters to SHFileOperation must be terminated with 2 NULL chars.
781  std::wstring source = source_file_path.value();
782  std::wstring target = target_file_path.value();
783
784  source.append(1, L'\0');
785  target.append(1, L'\0');
786
787  SHFILEOPSTRUCT move_info = {0};
788  move_info.wFunc = FO_MOVE;
789  move_info.pFrom = source.c_str();
790  move_info.pTo = target.c_str();
791  move_info.fFlags = FOF_SILENT | FOF_NOCONFIRMATION | FOF_NOERRORUI |
792                     FOF_NOCONFIRMMKDIR | FOF_NOCOPYSECURITYATTRIBS;
793
794  if (0 != SHFileOperation(&move_info))
795    return false;
796
797  return true;
798}
799
800// Gets the current working directory for the process.
801bool GetCurrentDirectory(FilePath* dir) {
802  base::ThreadRestrictions::AssertIOAllowed();
803
804  wchar_t system_buffer[MAX_PATH];
805  system_buffer[0] = 0;
806  DWORD len = ::GetCurrentDirectory(MAX_PATH, system_buffer);
807  if (len == 0 || len > MAX_PATH)
808    return false;
809  // TODO(evanm): the old behavior of this function was to always strip the
810  // trailing slash.  We duplicate this here, but it shouldn't be necessary
811  // when everyone is using the appropriate FilePath APIs.
812  std::wstring dir_str(system_buffer);
813  *dir = FilePath(dir_str).StripTrailingSeparators();
814  return true;
815}
816
817// Sets the current working directory for the process.
818bool SetCurrentDirectory(const FilePath& directory) {
819  base::ThreadRestrictions::AssertIOAllowed();
820  BOOL ret = ::SetCurrentDirectory(directory.value().c_str());
821  return ret != 0;
822}
823
824///////////////////////////////////////////////
825// FileEnumerator
826
827FileEnumerator::FileEnumerator(const FilePath& root_path,
828                               bool recursive,
829                               FileEnumerator::FILE_TYPE file_type)
830    : recursive_(recursive),
831      file_type_(file_type),
832      has_find_data_(false),
833      find_handle_(INVALID_HANDLE_VALUE) {
834  // INCLUDE_DOT_DOT must not be specified if recursive.
835  DCHECK(!(recursive && (INCLUDE_DOT_DOT & file_type_)));
836  pending_paths_.push(root_path);
837}
838
839FileEnumerator::FileEnumerator(const FilePath& root_path,
840                               bool recursive,
841                               FileEnumerator::FILE_TYPE file_type,
842                               const FilePath::StringType& pattern)
843    : recursive_(recursive),
844      file_type_(file_type),
845      has_find_data_(false),
846      pattern_(pattern),
847      find_handle_(INVALID_HANDLE_VALUE) {
848  // INCLUDE_DOT_DOT must not be specified if recursive.
849  DCHECK(!(recursive && (INCLUDE_DOT_DOT & file_type_)));
850  pending_paths_.push(root_path);
851}
852
853FileEnumerator::~FileEnumerator() {
854  if (find_handle_ != INVALID_HANDLE_VALUE)
855    FindClose(find_handle_);
856}
857
858void FileEnumerator::GetFindInfo(FindInfo* info) {
859  DCHECK(info);
860
861  if (!has_find_data_)
862    return;
863
864  memcpy(info, &find_data_, sizeof(*info));
865}
866
867bool FileEnumerator::IsDirectory(const FindInfo& info) {
868  return (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
869}
870
871// static
872FilePath FileEnumerator::GetFilename(const FindInfo& find_info) {
873  return FilePath(find_info.cFileName);
874}
875
876FilePath FileEnumerator::Next() {
877  base::ThreadRestrictions::AssertIOAllowed();
878
879  while (has_find_data_ || !pending_paths_.empty()) {
880    if (!has_find_data_) {
881      // The last find FindFirstFile operation is done, prepare a new one.
882      root_path_ = pending_paths_.top();
883      pending_paths_.pop();
884
885      // Start a new find operation.
886      FilePath src = root_path_;
887
888      if (pattern_.empty())
889        src = src.Append(L"*");  // No pattern = match everything.
890      else
891        src = src.Append(pattern_);
892
893      find_handle_ = FindFirstFile(src.value().c_str(), &find_data_);
894      has_find_data_ = true;
895    } else {
896      // Search for the next file/directory.
897      if (!FindNextFile(find_handle_, &find_data_)) {
898        FindClose(find_handle_);
899        find_handle_ = INVALID_HANDLE_VALUE;
900      }
901    }
902
903    if (INVALID_HANDLE_VALUE == find_handle_) {
904      has_find_data_ = false;
905
906      // This is reached when we have finished a directory and are advancing to
907      // the next one in the queue. We applied the pattern (if any) to the files
908      // in the root search directory, but for those directories which were
909      // matched, we want to enumerate all files inside them. This will happen
910      // when the handle is empty.
911      pattern_ = FilePath::StringType();
912
913      continue;
914    }
915
916    FilePath cur_file(find_data_.cFileName);
917    if (ShouldSkip(cur_file))
918      continue;
919
920    // Construct the absolute filename.
921    cur_file = root_path_.Append(find_data_.cFileName);
922
923    if (find_data_.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
924      if (recursive_) {
925        // If |cur_file| is a directory, and we are doing recursive searching,
926        // add it to pending_paths_ so we scan it after we finish scanning this
927        // directory.
928        pending_paths_.push(cur_file);
929      }
930      if (file_type_ & FileEnumerator::DIRECTORIES)
931        return cur_file;
932    } else if (file_type_ & FileEnumerator::FILES)
933      return cur_file;
934  }
935
936  return FilePath();
937}
938
939///////////////////////////////////////////////
940// MemoryMappedFile
941
942MemoryMappedFile::MemoryMappedFile()
943    : file_(INVALID_HANDLE_VALUE),
944      file_mapping_(INVALID_HANDLE_VALUE),
945      data_(NULL),
946      length_(INVALID_FILE_SIZE) {
947}
948
949bool MemoryMappedFile::MapFileToMemoryInternal() {
950  base::ThreadRestrictions::AssertIOAllowed();
951
952  if (file_ == INVALID_HANDLE_VALUE)
953    return false;
954
955  length_ = ::GetFileSize(file_, NULL);
956  if (length_ == INVALID_FILE_SIZE)
957    return false;
958
959  // length_ value comes from GetFileSize() above. GetFileSize() returns DWORD,
960  // therefore the cast here is safe.
961  file_mapping_ = ::CreateFileMapping(file_, NULL, PAGE_READONLY,
962                                      0, static_cast<DWORD>(length_), NULL);
963  if (!file_mapping_) {
964    // According to msdn, system error codes are only reserved up to 15999.
965    // http://msdn.microsoft.com/en-us/library/ms681381(v=VS.85).aspx.
966    UMA_HISTOGRAM_ENUMERATION("MemoryMappedFile.CreateFileMapping",
967                              logging::GetLastSystemErrorCode(), 16000);
968    return false;
969  }
970
971  data_ = static_cast<uint8*>(
972      ::MapViewOfFile(file_mapping_, FILE_MAP_READ, 0, 0, length_));
973  if (!data_) {
974    UMA_HISTOGRAM_ENUMERATION("MemoryMappedFile.MapViewOfFile",
975                              logging::GetLastSystemErrorCode(), 16000);
976  }
977  return data_ != NULL;
978}
979
980void MemoryMappedFile::CloseHandles() {
981  if (data_)
982    ::UnmapViewOfFile(data_);
983  if (file_mapping_ != INVALID_HANDLE_VALUE)
984    ::CloseHandle(file_mapping_);
985  if (file_ != INVALID_HANDLE_VALUE)
986    ::CloseHandle(file_);
987
988  data_ = NULL;
989  file_mapping_ = file_ = INVALID_HANDLE_VALUE;
990  length_ = INVALID_FILE_SIZE;
991}
992
993bool HasFileBeenModifiedSince(const FileEnumerator::FindInfo& find_info,
994                              const base::Time& cutoff_time) {
995  base::ThreadRestrictions::AssertIOAllowed();
996  long result = CompareFileTime(&find_info.ftLastWriteTime,
997                                &cutoff_time.ToFileTime());
998  return result == 1 || result == 0;
999}
1000
1001bool NormalizeFilePath(const FilePath& path, FilePath* real_path) {
1002  base::ThreadRestrictions::AssertIOAllowed();
1003  FilePath mapped_file;
1004  if (!NormalizeToNativeFilePath(path, &mapped_file))
1005    return false;
1006  // NormalizeToNativeFilePath() will return a path that starts with
1007  // "\Device\Harddisk...".  Helper DevicePathToDriveLetterPath()
1008  // will find a drive letter which maps to the path's device, so
1009  // that we return a path starting with a drive letter.
1010  return DevicePathToDriveLetterPath(mapped_file, real_path);
1011}
1012
1013bool NormalizeToNativeFilePath(const FilePath& path, FilePath* nt_path) {
1014  base::ThreadRestrictions::AssertIOAllowed();
1015  // In Vista, GetFinalPathNameByHandle() would give us the real path
1016  // from a file handle.  If we ever deprecate XP, consider changing the
1017  // code below to a call to GetFinalPathNameByHandle().  The method this
1018  // function uses is explained in the following msdn article:
1019  // http://msdn.microsoft.com/en-us/library/aa366789(VS.85).aspx
1020  base::win::ScopedHandle file_handle(
1021      ::CreateFile(path.value().c_str(),
1022                   GENERIC_READ,
1023                   kFileShareAll,
1024                   NULL,
1025                   OPEN_EXISTING,
1026                   FILE_ATTRIBUTE_NORMAL,
1027                   NULL));
1028  if (!file_handle)
1029    return false;
1030
1031  // Create a file mapping object.  Can't easily use MemoryMappedFile, because
1032  // we only map the first byte, and need direct access to the handle. You can
1033  // not map an empty file, this call fails in that case.
1034  base::win::ScopedHandle file_map_handle(
1035      ::CreateFileMapping(file_handle.Get(),
1036                          NULL,
1037                          PAGE_READONLY,
1038                          0,
1039                          1, // Just one byte.  No need to look at the data.
1040                          NULL));
1041  if (!file_map_handle)
1042    return false;
1043
1044  // Use a view of the file to get the path to the file.
1045  void* file_view = MapViewOfFile(file_map_handle.Get(),
1046                                  FILE_MAP_READ, 0, 0, 1);
1047  if (!file_view)
1048    return false;
1049
1050  // The expansion of |path| into a full path may make it longer.
1051  // GetMappedFileName() will fail if the result is longer than MAX_PATH.
1052  // Pad a bit to be safe.  If kMaxPathLength is ever changed to be less
1053  // than MAX_PATH, it would be nessisary to test that GetMappedFileName()
1054  // not return kMaxPathLength.  This would mean that only part of the
1055  // path fit in |mapped_file_path|.
1056  const int kMaxPathLength = MAX_PATH + 10;
1057  wchar_t mapped_file_path[kMaxPathLength];
1058  bool success = false;
1059  HANDLE cp = GetCurrentProcess();
1060  if (::GetMappedFileNameW(cp, file_view, mapped_file_path, kMaxPathLength)) {
1061    *nt_path = FilePath(mapped_file_path);
1062    success = true;
1063  }
1064  ::UnmapViewOfFile(file_view);
1065  return success;
1066}
1067
1068bool PreReadImage(const wchar_t* file_path, size_t size_to_read,
1069                  size_t step_size) {
1070  base::ThreadRestrictions::AssertIOAllowed();
1071  if (base::win::GetVersion() > base::win::VERSION_XP) {
1072    // Vista+ branch. On these OSes, the forced reads through the DLL actually
1073    // slows warm starts. The solution is to sequentially read file contents
1074    // with an optional cap on total amount to read.
1075    base::win::ScopedHandle file(
1076        CreateFile(file_path,
1077                   GENERIC_READ,
1078                   FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
1079                   NULL,
1080                   OPEN_EXISTING,
1081                   FILE_FLAG_SEQUENTIAL_SCAN,
1082                   NULL));
1083
1084    if (!file.IsValid())
1085      return false;
1086
1087    // Default to 1MB sequential reads.
1088    const DWORD actual_step_size = std::max(static_cast<DWORD>(step_size),
1089                                            static_cast<DWORD>(1024*1024));
1090    LPVOID buffer = ::VirtualAlloc(NULL,
1091                                   actual_step_size,
1092                                   MEM_COMMIT,
1093                                   PAGE_READWRITE);
1094
1095    if (buffer == NULL)
1096      return false;
1097
1098    DWORD len;
1099    size_t total_read = 0;
1100    while (::ReadFile(file, buffer, actual_step_size, &len, NULL) &&
1101           len > 0 &&
1102           (size_to_read ? total_read < size_to_read : true)) {
1103      total_read += static_cast<size_t>(len);
1104    }
1105    ::VirtualFree(buffer, 0, MEM_RELEASE);
1106  } else {
1107    // WinXP branch. Here, reading the DLL from disk doesn't do
1108    // what we want so instead we pull the pages into memory by loading
1109    // the DLL and touching pages at a stride.
1110    HMODULE dll_module = ::LoadLibraryExW(
1111        file_path,
1112        NULL,
1113        LOAD_WITH_ALTERED_SEARCH_PATH | DONT_RESOLVE_DLL_REFERENCES);
1114
1115    if (!dll_module)
1116      return false;
1117
1118    base::win::PEImage pe_image(dll_module);
1119    PIMAGE_NT_HEADERS nt_headers = pe_image.GetNTHeaders();
1120    size_t actual_size_to_read = size_to_read ? size_to_read :
1121                                 nt_headers->OptionalHeader.SizeOfImage;
1122    volatile uint8* touch = reinterpret_cast<uint8*>(dll_module);
1123    size_t offset = 0;
1124    while (offset < actual_size_to_read) {
1125      uint8 unused = *(touch + offset);
1126      offset += step_size;
1127    }
1128    FreeLibrary(dll_module);
1129  }
1130
1131  return true;
1132}
1133
1134}  // namespace file_util
1135