- add sources.
[platform/framework/web/crosswalk.git] / src / base / file_util_win.cc
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.
4
5 #include "base/file_util.h"
6
7 #include <windows.h>
8 #include <psapi.h>
9 #include <shellapi.h>
10 #include <shlobj.h>
11 #include <time.h>
12
13 #include <algorithm>
14 #include <limits>
15 #include <string>
16
17 #include "base/files/file_path.h"
18 #include "base/logging.h"
19 #include "base/metrics/histogram.h"
20 #include "base/process/process_handle.h"
21 #include "base/rand_util.h"
22 #include "base/strings/string_number_conversions.h"
23 #include "base/strings/string_util.h"
24 #include "base/strings/utf_string_conversions.h"
25 #include "base/threading/thread_restrictions.h"
26 #include "base/time/time.h"
27 #include "base/win/scoped_handle.h"
28 #include "base/win/windows_version.h"
29
30 namespace base {
31
32 namespace {
33
34 const DWORD kFileShareAll =
35     FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
36
37 bool ShellCopy(const FilePath& from_path,
38                const FilePath& to_path,
39                bool recursive) {
40   // WinXP SHFileOperation doesn't like trailing separators.
41   FilePath stripped_from = from_path.StripTrailingSeparators();
42   FilePath stripped_to = to_path.StripTrailingSeparators();
43
44   ThreadRestrictions::AssertIOAllowed();
45
46   // NOTE: I suspect we could support longer paths, but that would involve
47   // analyzing all our usage of files.
48   if (stripped_from.value().length() >= MAX_PATH ||
49       stripped_to.value().length() >= MAX_PATH) {
50     return false;
51   }
52
53   // SHFILEOPSTRUCT wants the path to be terminated with two NULLs,
54   // so we have to use wcscpy because wcscpy_s writes non-NULLs
55   // into the rest of the buffer.
56   wchar_t double_terminated_path_from[MAX_PATH + 1] = {0};
57   wchar_t double_terminated_path_to[MAX_PATH + 1] = {0};
58 #pragma warning(suppress:4996)  // don't complain about wcscpy deprecation
59   wcscpy(double_terminated_path_from, stripped_from.value().c_str());
60 #pragma warning(suppress:4996)  // don't complain about wcscpy deprecation
61   wcscpy(double_terminated_path_to, stripped_to.value().c_str());
62
63   SHFILEOPSTRUCT file_operation = {0};
64   file_operation.wFunc = FO_COPY;
65   file_operation.pFrom = double_terminated_path_from;
66   file_operation.pTo = double_terminated_path_to;
67   file_operation.fFlags = FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMATION |
68                           FOF_NOCONFIRMMKDIR;
69   if (!recursive)
70     file_operation.fFlags |= FOF_NORECURSION | FOF_FILESONLY;
71
72   return (SHFileOperation(&file_operation) == 0);
73 }
74
75 }  // namespace
76
77 FilePath MakeAbsoluteFilePath(const FilePath& input) {
78   ThreadRestrictions::AssertIOAllowed();
79   wchar_t file_path[MAX_PATH];
80   if (!_wfullpath(file_path, input.value().c_str(), MAX_PATH))
81     return FilePath();
82   return FilePath(file_path);
83 }
84
85 bool DeleteFile(const FilePath& path, bool recursive) {
86   ThreadRestrictions::AssertIOAllowed();
87
88   if (path.value().length() >= MAX_PATH)
89     return false;
90
91   if (!recursive) {
92     // If not recursing, then first check to see if |path| is a directory.
93     // If it is, then remove it with RemoveDirectory.
94     PlatformFileInfo file_info;
95     if (file_util::GetFileInfo(path, &file_info) && file_info.is_directory)
96       return RemoveDirectory(path.value().c_str()) != 0;
97
98     // Otherwise, it's a file, wildcard or non-existant. Try DeleteFile first
99     // because it should be faster. If DeleteFile fails, then we fall through
100     // to SHFileOperation, which will do the right thing.
101     if (::DeleteFile(path.value().c_str()) != 0)
102       return true;
103   }
104
105   // SHFILEOPSTRUCT wants the path to be terminated with two NULLs,
106   // so we have to use wcscpy because wcscpy_s writes non-NULLs
107   // into the rest of the buffer.
108   wchar_t double_terminated_path[MAX_PATH + 1] = {0};
109 #pragma warning(suppress:4996)  // don't complain about wcscpy deprecation
110   wcscpy(double_terminated_path, path.value().c_str());
111
112   SHFILEOPSTRUCT file_operation = {0};
113   file_operation.wFunc = FO_DELETE;
114   file_operation.pFrom = double_terminated_path;
115   file_operation.fFlags = FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMATION;
116   if (!recursive)
117     file_operation.fFlags |= FOF_NORECURSION | FOF_FILESONLY;
118   int err = SHFileOperation(&file_operation);
119
120   // Since we're passing flags to the operation telling it to be silent,
121   // it's possible for the operation to be aborted/cancelled without err
122   // being set (although MSDN doesn't give any scenarios for how this can
123   // happen).  See MSDN for SHFileOperation and SHFILEOPTSTRUCT.
124   if (file_operation.fAnyOperationsAborted)
125     return false;
126
127   // Some versions of Windows return ERROR_FILE_NOT_FOUND (0x2) when deleting
128   // an empty directory and some return 0x402 when they should be returning
129   // ERROR_FILE_NOT_FOUND. MSDN says Vista and up won't return 0x402.
130   return (err == 0 || err == ERROR_FILE_NOT_FOUND || err == 0x402);
131 }
132
133 bool DeleteFileAfterReboot(const FilePath& path) {
134   ThreadRestrictions::AssertIOAllowed();
135
136   if (path.value().length() >= MAX_PATH)
137     return false;
138
139   return MoveFileEx(path.value().c_str(), NULL,
140                     MOVEFILE_DELAY_UNTIL_REBOOT |
141                         MOVEFILE_REPLACE_EXISTING) != FALSE;
142 }
143
144 bool ReplaceFile(const FilePath& from_path,
145                  const FilePath& to_path,
146                  PlatformFileError* error) {
147   ThreadRestrictions::AssertIOAllowed();
148   // Try a simple move first.  It will only succeed when |to_path| doesn't
149   // already exist.
150   if (::MoveFile(from_path.value().c_str(), to_path.value().c_str()))
151     return true;
152   // Try the full-blown replace if the move fails, as ReplaceFile will only
153   // succeed when |to_path| does exist. When writing to a network share, we may
154   // not be able to change the ACLs. Ignore ACL errors then
155   // (REPLACEFILE_IGNORE_MERGE_ERRORS).
156   if (::ReplaceFile(to_path.value().c_str(), from_path.value().c_str(), NULL,
157                     REPLACEFILE_IGNORE_MERGE_ERRORS, NULL, NULL)) {
158     return true;
159   }
160   if (error)
161     *error = LastErrorToPlatformFileError(GetLastError());
162   return false;
163 }
164
165 bool CopyDirectory(const FilePath& from_path, const FilePath& to_path,
166                    bool recursive) {
167   ThreadRestrictions::AssertIOAllowed();
168
169   if (recursive)
170     return ShellCopy(from_path, to_path, true);
171
172   // The following code assumes that from path is a directory.
173   DCHECK(DirectoryExists(from_path));
174
175   // Instead of creating a new directory, we copy the old one to include the
176   // security information of the folder as part of the copy.
177   if (!PathExists(to_path)) {
178     // Except that Vista fails to do that, and instead do a recursive copy if
179     // the target directory doesn't exist.
180     if (base::win::GetVersion() >= base::win::VERSION_VISTA)
181       file_util::CreateDirectory(to_path);
182     else
183       ShellCopy(from_path, to_path, false);
184   }
185
186   FilePath directory = from_path.Append(L"*.*");
187   return ShellCopy(directory, to_path, false);
188 }
189
190 bool PathExists(const FilePath& path) {
191   ThreadRestrictions::AssertIOAllowed();
192   return (GetFileAttributes(path.value().c_str()) != INVALID_FILE_ATTRIBUTES);
193 }
194
195 bool PathIsWritable(const FilePath& path) {
196   ThreadRestrictions::AssertIOAllowed();
197   HANDLE dir =
198       CreateFile(path.value().c_str(), FILE_ADD_FILE, kFileShareAll,
199                  NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
200
201   if (dir == INVALID_HANDLE_VALUE)
202     return false;
203
204   CloseHandle(dir);
205   return true;
206 }
207
208 bool DirectoryExists(const FilePath& path) {
209   ThreadRestrictions::AssertIOAllowed();
210   DWORD fileattr = GetFileAttributes(path.value().c_str());
211   if (fileattr != INVALID_FILE_ATTRIBUTES)
212     return (fileattr & FILE_ATTRIBUTE_DIRECTORY) != 0;
213   return false;
214 }
215
216 }  // namespace base
217
218 // -----------------------------------------------------------------------------
219
220 namespace file_util {
221
222 using base::DirectoryExists;
223 using base::FilePath;
224 using base::kFileShareAll;
225
226 bool GetTempDir(FilePath* path) {
227   base::ThreadRestrictions::AssertIOAllowed();
228
229   wchar_t temp_path[MAX_PATH + 1];
230   DWORD path_len = ::GetTempPath(MAX_PATH, temp_path);
231   if (path_len >= MAX_PATH || path_len <= 0)
232     return false;
233   // TODO(evanm): the old behavior of this function was to always strip the
234   // trailing slash.  We duplicate this here, but it shouldn't be necessary
235   // when everyone is using the appropriate FilePath APIs.
236   *path = FilePath(temp_path).StripTrailingSeparators();
237   return true;
238 }
239
240 bool GetShmemTempDir(FilePath* path, bool executable) {
241   return GetTempDir(path);
242 }
243
244 bool CreateTemporaryFile(FilePath* path) {
245   base::ThreadRestrictions::AssertIOAllowed();
246
247   FilePath temp_file;
248
249   if (!GetTempDir(path))
250     return false;
251
252   if (CreateTemporaryFileInDir(*path, &temp_file)) {
253     *path = temp_file;
254     return true;
255   }
256
257   return false;
258 }
259
260 FILE* CreateAndOpenTemporaryShmemFile(FilePath* path, bool executable) {
261   base::ThreadRestrictions::AssertIOAllowed();
262   return CreateAndOpenTemporaryFile(path);
263 }
264
265 // On POSIX we have semantics to create and open a temporary file
266 // atomically.
267 // TODO(jrg): is there equivalent call to use on Windows instead of
268 // going 2-step?
269 FILE* CreateAndOpenTemporaryFileInDir(const FilePath& dir, FilePath* path) {
270   base::ThreadRestrictions::AssertIOAllowed();
271   if (!CreateTemporaryFileInDir(dir, path)) {
272     return NULL;
273   }
274   // Open file in binary mode, to avoid problems with fwrite. On Windows
275   // it replaces \n's with \r\n's, which may surprise you.
276   // Reference: http://msdn.microsoft.com/en-us/library/h9t88zwz(VS.71).aspx
277   return OpenFile(*path, "wb+");
278 }
279
280 bool CreateTemporaryFileInDir(const FilePath& dir,
281                               FilePath* temp_file) {
282   base::ThreadRestrictions::AssertIOAllowed();
283
284   wchar_t temp_name[MAX_PATH + 1];
285
286   if (!GetTempFileName(dir.value().c_str(), L"", 0, temp_name)) {
287     DPLOG(WARNING) << "Failed to get temporary file name in " << dir.value();
288     return false;
289   }
290
291   wchar_t long_temp_name[MAX_PATH + 1];
292   DWORD long_name_len = GetLongPathName(temp_name, long_temp_name, MAX_PATH);
293   if (long_name_len > MAX_PATH || long_name_len == 0) {
294     // GetLongPathName() failed, but we still have a temporary file.
295     *temp_file = FilePath(temp_name);
296     return true;
297   }
298
299   FilePath::StringType long_temp_name_str;
300   long_temp_name_str.assign(long_temp_name, long_name_len);
301   *temp_file = FilePath(long_temp_name_str);
302   return true;
303 }
304
305 bool CreateTemporaryDirInDir(const FilePath& base_dir,
306                              const FilePath::StringType& prefix,
307                              FilePath* new_dir) {
308   base::ThreadRestrictions::AssertIOAllowed();
309
310   FilePath path_to_create;
311
312   for (int count = 0; count < 50; ++count) {
313     // Try create a new temporary directory with random generated name. If
314     // the one exists, keep trying another path name until we reach some limit.
315     string16 new_dir_name;
316     new_dir_name.assign(prefix);
317     new_dir_name.append(base::IntToString16(::base::GetCurrentProcId()));
318     new_dir_name.push_back('_');
319     new_dir_name.append(base::IntToString16(base::RandInt(0, kint16max)));
320
321     path_to_create = base_dir.Append(new_dir_name);
322     if (::CreateDirectory(path_to_create.value().c_str(), NULL)) {
323       *new_dir = path_to_create;
324       return true;
325     }
326   }
327
328   return false;
329 }
330
331 bool CreateNewTempDirectory(const FilePath::StringType& prefix,
332                             FilePath* new_temp_path) {
333   base::ThreadRestrictions::AssertIOAllowed();
334
335   FilePath system_temp_dir;
336   if (!GetTempDir(&system_temp_dir))
337     return false;
338
339   return CreateTemporaryDirInDir(system_temp_dir, prefix, new_temp_path);
340 }
341
342 bool CreateDirectoryAndGetError(const FilePath& full_path,
343                                 base::PlatformFileError* error) {
344   base::ThreadRestrictions::AssertIOAllowed();
345
346   // If the path exists, we've succeeded if it's a directory, failed otherwise.
347   const wchar_t* full_path_str = full_path.value().c_str();
348   DWORD fileattr = ::GetFileAttributes(full_path_str);
349   if (fileattr != INVALID_FILE_ATTRIBUTES) {
350     if ((fileattr & FILE_ATTRIBUTE_DIRECTORY) != 0) {
351       DVLOG(1) << "CreateDirectory(" << full_path_str << "), "
352                << "directory already exists.";
353       return true;
354     }
355     DLOG(WARNING) << "CreateDirectory(" << full_path_str << "), "
356                   << "conflicts with existing file.";
357     if (error) {
358       *error = base::PLATFORM_FILE_ERROR_NOT_A_DIRECTORY;
359     }
360     return false;
361   }
362
363   // Invariant:  Path does not exist as file or directory.
364
365   // Attempt to create the parent recursively.  This will immediately return
366   // true if it already exists, otherwise will create all required parent
367   // directories starting with the highest-level missing parent.
368   FilePath parent_path(full_path.DirName());
369   if (parent_path.value() == full_path.value()) {
370     if (error) {
371       *error = base::PLATFORM_FILE_ERROR_NOT_FOUND;
372     }
373     return false;
374   }
375   if (!CreateDirectoryAndGetError(parent_path, error)) {
376     DLOG(WARNING) << "Failed to create one of the parent directories.";
377     if (error) {
378       DCHECK(*error != base::PLATFORM_FILE_OK);
379     }
380     return false;
381   }
382
383   if (!::CreateDirectory(full_path_str, NULL)) {
384     DWORD error_code = ::GetLastError();
385     if (error_code == ERROR_ALREADY_EXISTS && DirectoryExists(full_path)) {
386       // This error code ERROR_ALREADY_EXISTS doesn't indicate whether we
387       // were racing with someone creating the same directory, or a file
388       // with the same path.  If DirectoryExists() returns true, we lost the
389       // race to create the same directory.
390       return true;
391     } else {
392       if (error)
393         *error = base::LastErrorToPlatformFileError(error_code);
394       DLOG(WARNING) << "Failed to create directory " << full_path_str
395                     << ", last error is " << error_code << ".";
396       return false;
397     }
398   } else {
399     return true;
400   }
401 }
402
403 // TODO(rkc): Work out if we want to handle NTFS junctions here or not, handle
404 // them if we do decide to.
405 bool IsLink(const FilePath& file_path) {
406   return false;
407 }
408
409 bool GetFileInfo(const FilePath& file_path, base::PlatformFileInfo* results) {
410   base::ThreadRestrictions::AssertIOAllowed();
411
412   WIN32_FILE_ATTRIBUTE_DATA attr;
413   if (!GetFileAttributesEx(file_path.value().c_str(),
414                            GetFileExInfoStandard, &attr)) {
415     return false;
416   }
417
418   ULARGE_INTEGER size;
419   size.HighPart = attr.nFileSizeHigh;
420   size.LowPart = attr.nFileSizeLow;
421   results->size = size.QuadPart;
422
423   results->is_directory =
424       (attr.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
425   results->last_modified = base::Time::FromFileTime(attr.ftLastWriteTime);
426   results->last_accessed = base::Time::FromFileTime(attr.ftLastAccessTime);
427   results->creation_time = base::Time::FromFileTime(attr.ftCreationTime);
428
429   return true;
430 }
431
432 FILE* OpenFile(const FilePath& filename, const char* mode) {
433   base::ThreadRestrictions::AssertIOAllowed();
434   std::wstring w_mode = ASCIIToWide(std::string(mode));
435   return _wfsopen(filename.value().c_str(), w_mode.c_str(), _SH_DENYNO);
436 }
437
438 FILE* OpenFile(const std::string& filename, const char* mode) {
439   base::ThreadRestrictions::AssertIOAllowed();
440   return _fsopen(filename.c_str(), mode, _SH_DENYNO);
441 }
442
443 int ReadFile(const FilePath& filename, char* data, int size) {
444   base::ThreadRestrictions::AssertIOAllowed();
445   base::win::ScopedHandle file(CreateFile(filename.value().c_str(),
446                                           GENERIC_READ,
447                                           FILE_SHARE_READ | FILE_SHARE_WRITE,
448                                           NULL,
449                                           OPEN_EXISTING,
450                                           FILE_FLAG_SEQUENTIAL_SCAN,
451                                           NULL));
452   if (!file)
453     return -1;
454
455   DWORD read;
456   if (::ReadFile(file, data, size, &read, NULL) &&
457       static_cast<int>(read) == size)
458     return read;
459   return -1;
460 }
461
462 int WriteFile(const FilePath& filename, const char* data, int size) {
463   base::ThreadRestrictions::AssertIOAllowed();
464   base::win::ScopedHandle file(CreateFile(filename.value().c_str(),
465                                           GENERIC_WRITE,
466                                           0,
467                                           NULL,
468                                           CREATE_ALWAYS,
469                                           0,
470                                           NULL));
471   if (!file) {
472     DLOG_GETLASTERROR(WARNING) << "CreateFile failed for path "
473                                << filename.value();
474     return -1;
475   }
476
477   DWORD written;
478   BOOL result = ::WriteFile(file, data, size, &written, NULL);
479   if (result && static_cast<int>(written) == size)
480     return written;
481
482   if (!result) {
483     // WriteFile failed.
484     DLOG_GETLASTERROR(WARNING) << "writing file " << filename.value()
485                                << " failed";
486   } else {
487     // Didn't write all the bytes.
488     DLOG(WARNING) << "wrote" << written << " bytes to "
489                   << filename.value() << " expected " << size;
490   }
491   return -1;
492 }
493
494 int AppendToFile(const FilePath& filename, const char* data, int size) {
495   base::ThreadRestrictions::AssertIOAllowed();
496   base::win::ScopedHandle file(CreateFile(filename.value().c_str(),
497                                           FILE_APPEND_DATA,
498                                           0,
499                                           NULL,
500                                           OPEN_EXISTING,
501                                           0,
502                                           NULL));
503   if (!file) {
504     DLOG_GETLASTERROR(WARNING) << "CreateFile failed for path "
505                                << filename.value();
506     return -1;
507   }
508
509   DWORD written;
510   BOOL result = ::WriteFile(file, data, size, &written, NULL);
511   if (result && static_cast<int>(written) == size)
512     return written;
513
514   if (!result) {
515     // WriteFile failed.
516     DLOG_GETLASTERROR(WARNING) << "writing file " << filename.value()
517                                << " failed";
518   } else {
519     // Didn't write all the bytes.
520     DLOG(WARNING) << "wrote" << written << " bytes to "
521                   << filename.value() << " expected " << size;
522   }
523   return -1;
524 }
525
526 // Gets the current working directory for the process.
527 bool GetCurrentDirectory(FilePath* dir) {
528   base::ThreadRestrictions::AssertIOAllowed();
529
530   wchar_t system_buffer[MAX_PATH];
531   system_buffer[0] = 0;
532   DWORD len = ::GetCurrentDirectory(MAX_PATH, system_buffer);
533   if (len == 0 || len > MAX_PATH)
534     return false;
535   // TODO(evanm): the old behavior of this function was to always strip the
536   // trailing slash.  We duplicate this here, but it shouldn't be necessary
537   // when everyone is using the appropriate FilePath APIs.
538   std::wstring dir_str(system_buffer);
539   *dir = FilePath(dir_str).StripTrailingSeparators();
540   return true;
541 }
542
543 // Sets the current working directory for the process.
544 bool SetCurrentDirectory(const FilePath& directory) {
545   base::ThreadRestrictions::AssertIOAllowed();
546   BOOL ret = ::SetCurrentDirectory(directory.value().c_str());
547   return ret != 0;
548 }
549
550 bool NormalizeFilePath(const FilePath& path, FilePath* real_path) {
551   base::ThreadRestrictions::AssertIOAllowed();
552   FilePath mapped_file;
553   if (!NormalizeToNativeFilePath(path, &mapped_file))
554     return false;
555   // NormalizeToNativeFilePath() will return a path that starts with
556   // "\Device\Harddisk...".  Helper DevicePathToDriveLetterPath()
557   // will find a drive letter which maps to the path's device, so
558   // that we return a path starting with a drive letter.
559   return DevicePathToDriveLetterPath(mapped_file, real_path);
560 }
561
562 bool DevicePathToDriveLetterPath(const FilePath& nt_device_path,
563                                  FilePath* out_drive_letter_path) {
564   base::ThreadRestrictions::AssertIOAllowed();
565
566   // Get the mapping of drive letters to device paths.
567   const int kDriveMappingSize = 1024;
568   wchar_t drive_mapping[kDriveMappingSize] = {'\0'};
569   if (!::GetLogicalDriveStrings(kDriveMappingSize - 1, drive_mapping)) {
570     DLOG(ERROR) << "Failed to get drive mapping.";
571     return false;
572   }
573
574   // The drive mapping is a sequence of null terminated strings.
575   // The last string is empty.
576   wchar_t* drive_map_ptr = drive_mapping;
577   wchar_t device_path_as_string[MAX_PATH];
578   wchar_t drive[] = L" :";
579
580   // For each string in the drive mapping, get the junction that links
581   // to it.  If that junction is a prefix of |device_path|, then we
582   // know that |drive| is the real path prefix.
583   while (*drive_map_ptr) {
584     drive[0] = drive_map_ptr[0];  // Copy the drive letter.
585
586     if (QueryDosDevice(drive, device_path_as_string, MAX_PATH)) {
587       FilePath device_path(device_path_as_string);
588       if (device_path == nt_device_path ||
589           device_path.IsParent(nt_device_path)) {
590         *out_drive_letter_path = FilePath(drive +
591             nt_device_path.value().substr(wcslen(device_path_as_string)));
592         return true;
593       }
594     }
595     // Move to the next drive letter string, which starts one
596     // increment after the '\0' that terminates the current string.
597     while (*drive_map_ptr++);
598   }
599
600   // No drive matched.  The path does not start with a device junction
601   // that is mounted as a drive letter.  This means there is no drive
602   // letter path to the volume that holds |device_path|, so fail.
603   return false;
604 }
605
606 bool NormalizeToNativeFilePath(const FilePath& path, FilePath* nt_path) {
607   base::ThreadRestrictions::AssertIOAllowed();
608   // In Vista, GetFinalPathNameByHandle() would give us the real path
609   // from a file handle.  If we ever deprecate XP, consider changing the
610   // code below to a call to GetFinalPathNameByHandle().  The method this
611   // function uses is explained in the following msdn article:
612   // http://msdn.microsoft.com/en-us/library/aa366789(VS.85).aspx
613   base::win::ScopedHandle file_handle(
614       ::CreateFile(path.value().c_str(),
615                    GENERIC_READ,
616                    kFileShareAll,
617                    NULL,
618                    OPEN_EXISTING,
619                    FILE_ATTRIBUTE_NORMAL,
620                    NULL));
621   if (!file_handle)
622     return false;
623
624   // Create a file mapping object.  Can't easily use MemoryMappedFile, because
625   // we only map the first byte, and need direct access to the handle. You can
626   // not map an empty file, this call fails in that case.
627   base::win::ScopedHandle file_map_handle(
628       ::CreateFileMapping(file_handle.Get(),
629                           NULL,
630                           PAGE_READONLY,
631                           0,
632                           1,  // Just one byte.  No need to look at the data.
633                           NULL));
634   if (!file_map_handle)
635     return false;
636
637   // Use a view of the file to get the path to the file.
638   void* file_view = MapViewOfFile(file_map_handle.Get(),
639                                   FILE_MAP_READ, 0, 0, 1);
640   if (!file_view)
641     return false;
642
643   // The expansion of |path| into a full path may make it longer.
644   // GetMappedFileName() will fail if the result is longer than MAX_PATH.
645   // Pad a bit to be safe.  If kMaxPathLength is ever changed to be less
646   // than MAX_PATH, it would be nessisary to test that GetMappedFileName()
647   // not return kMaxPathLength.  This would mean that only part of the
648   // path fit in |mapped_file_path|.
649   const int kMaxPathLength = MAX_PATH + 10;
650   wchar_t mapped_file_path[kMaxPathLength];
651   bool success = false;
652   HANDLE cp = GetCurrentProcess();
653   if (::GetMappedFileNameW(cp, file_view, mapped_file_path, kMaxPathLength)) {
654     *nt_path = FilePath(mapped_file_path);
655     success = true;
656   }
657   ::UnmapViewOfFile(file_view);
658   return success;
659 }
660
661 int GetMaximumPathComponentLength(const FilePath& path) {
662   base::ThreadRestrictions::AssertIOAllowed();
663
664   wchar_t volume_path[MAX_PATH];
665   if (!GetVolumePathNameW(path.NormalizePathSeparators().value().c_str(),
666                           volume_path,
667                           arraysize(volume_path))) {
668     return -1;
669   }
670
671   DWORD max_length = 0;
672   if (!GetVolumeInformationW(volume_path, NULL, 0, NULL, &max_length, NULL,
673                              NULL, 0)) {
674     return -1;
675   }
676
677   // Length of |path| with path separator appended.
678   size_t prefix = path.StripTrailingSeparators().value().size() + 1;
679   // The whole path string must be shorter than MAX_PATH. That is, it must be
680   // prefix + component_length < MAX_PATH (or equivalently, <= MAX_PATH - 1).
681   int whole_path_limit = std::max(0, MAX_PATH - 1 - static_cast<int>(prefix));
682   return std::min(whole_path_limit, static_cast<int>(max_length));
683 }
684
685 }  // namespace file_util
686
687 namespace base {
688 namespace internal {
689
690 bool MoveUnsafe(const FilePath& from_path, const FilePath& to_path) {
691   ThreadRestrictions::AssertIOAllowed();
692
693   // NOTE: I suspect we could support longer paths, but that would involve
694   // analyzing all our usage of files.
695   if (from_path.value().length() >= MAX_PATH ||
696       to_path.value().length() >= MAX_PATH) {
697     return false;
698   }
699   if (MoveFileEx(from_path.value().c_str(), to_path.value().c_str(),
700                  MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING) != 0)
701     return true;
702
703   // Keep the last error value from MoveFileEx around in case the below
704   // fails.
705   bool ret = false;
706   DWORD last_error = ::GetLastError();
707
708   if (DirectoryExists(from_path)) {
709     // MoveFileEx fails if moving directory across volumes. We will simulate
710     // the move by using Copy and Delete. Ideally we could check whether
711     // from_path and to_path are indeed in different volumes.
712     ret = internal::CopyAndDeleteDirectory(from_path, to_path);
713   }
714
715   if (!ret) {
716     // Leave a clue about what went wrong so that it can be (at least) picked
717     // up by a PLOG entry.
718     ::SetLastError(last_error);
719   }
720
721   return ret;
722 }
723
724 bool CopyFileUnsafe(const FilePath& from_path, const FilePath& to_path) {
725   ThreadRestrictions::AssertIOAllowed();
726
727   // NOTE: I suspect we could support longer paths, but that would involve
728   // analyzing all our usage of files.
729   if (from_path.value().length() >= MAX_PATH ||
730       to_path.value().length() >= MAX_PATH) {
731     return false;
732   }
733   return (::CopyFile(from_path.value().c_str(), to_path.value().c_str(),
734                      false) != 0);
735 }
736
737 bool CopyAndDeleteDirectory(const FilePath& from_path,
738                             const FilePath& to_path) {
739   ThreadRestrictions::AssertIOAllowed();
740   if (CopyDirectory(from_path, to_path, true)) {
741     if (DeleteFile(from_path, true))
742       return true;
743
744     // Like Move, this function is not transactional, so we just
745     // leave the copied bits behind if deleting from_path fails.
746     // If to_path exists previously then we have already overwritten
747     // it by now, we don't get better off by deleting the new bits.
748   }
749   return false;
750 }
751
752 }  // namespace internal
753 }  // namespace base