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"
17 #include "base/files/file_enumerator.h"
18 #include "base/files/file_path.h"
19 #include "base/logging.h"
20 #include "base/metrics/histogram.h"
21 #include "base/process/process_handle.h"
22 #include "base/rand_util.h"
23 #include "base/strings/string_number_conversions.h"
24 #include "base/strings/string_util.h"
25 #include "base/strings/utf_string_conversions.h"
26 #include "base/threading/thread_restrictions.h"
27 #include "base/time/time.h"
28 #include "base/win/scoped_handle.h"
29 #include "base/win/windows_version.h"
35 const DWORD kFileShareAll
=
36 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
;
40 FilePath
MakeAbsoluteFilePath(const FilePath
& input
) {
41 ThreadRestrictions::AssertIOAllowed();
42 wchar_t file_path
[MAX_PATH
];
43 if (!_wfullpath(file_path
, input
.value().c_str(), MAX_PATH
))
45 return FilePath(file_path
);
48 bool DeleteFile(const FilePath
& path
, bool recursive
) {
49 ThreadRestrictions::AssertIOAllowed();
51 if (path
.value().length() >= MAX_PATH
)
54 // On XP SHFileOperation will return ERROR_ACCESS_DENIED instead of
55 // ERROR_FILE_NOT_FOUND, so just shortcut this here.
60 // If not recursing, then first check to see if |path| is a directory.
61 // If it is, then remove it with RemoveDirectory.
63 if (GetFileInfo(path
, &file_info
) && file_info
.is_directory
)
64 return RemoveDirectory(path
.value().c_str()) != 0;
66 // Otherwise, it's a file, wildcard or non-existant. Try DeleteFile first
67 // because it should be faster. If DeleteFile fails, then we fall through
68 // to SHFileOperation, which will do the right thing.
69 if (::DeleteFile(path
.value().c_str()) != 0)
73 // SHFILEOPSTRUCT wants the path to be terminated with two NULLs,
74 // so we have to use wcscpy because wcscpy_s writes non-NULLs
75 // into the rest of the buffer.
76 wchar_t double_terminated_path
[MAX_PATH
+ 1] = {0};
77 #pragma warning(suppress:4996) // don't complain about wcscpy deprecation
78 wcscpy(double_terminated_path
, path
.value().c_str());
80 SHFILEOPSTRUCT file_operation
= {0};
81 file_operation
.wFunc
= FO_DELETE
;
82 file_operation
.pFrom
= double_terminated_path
;
83 file_operation
.fFlags
= FOF_NOERRORUI
| FOF_SILENT
| FOF_NOCONFIRMATION
;
85 file_operation
.fFlags
|= FOF_NORECURSION
| FOF_FILESONLY
;
86 int err
= SHFileOperation(&file_operation
);
88 // Since we're passing flags to the operation telling it to be silent,
89 // it's possible for the operation to be aborted/cancelled without err
90 // being set (although MSDN doesn't give any scenarios for how this can
91 // happen). See MSDN for SHFileOperation and SHFILEOPTSTRUCT.
92 if (file_operation
.fAnyOperationsAborted
)
95 // Some versions of Windows return ERROR_FILE_NOT_FOUND (0x2) when deleting
96 // an empty directory and some return 0x402 when they should be returning
97 // ERROR_FILE_NOT_FOUND. MSDN says Vista and up won't return 0x402.
98 return (err
== 0 || err
== ERROR_FILE_NOT_FOUND
|| err
== 0x402);
101 bool DeleteFileAfterReboot(const FilePath
& path
) {
102 ThreadRestrictions::AssertIOAllowed();
104 if (path
.value().length() >= MAX_PATH
)
107 return MoveFileEx(path
.value().c_str(), NULL
,
108 MOVEFILE_DELAY_UNTIL_REBOOT
|
109 MOVEFILE_REPLACE_EXISTING
) != FALSE
;
112 bool ReplaceFile(const FilePath
& from_path
,
113 const FilePath
& to_path
,
114 File::Error
* error
) {
115 ThreadRestrictions::AssertIOAllowed();
116 // Try a simple move first. It will only succeed when |to_path| doesn't
118 if (::MoveFile(from_path
.value().c_str(), to_path
.value().c_str()))
120 // Try the full-blown replace if the move fails, as ReplaceFile will only
121 // succeed when |to_path| does exist. When writing to a network share, we may
122 // not be able to change the ACLs. Ignore ACL errors then
123 // (REPLACEFILE_IGNORE_MERGE_ERRORS).
124 if (::ReplaceFile(to_path
.value().c_str(), from_path
.value().c_str(), NULL
,
125 REPLACEFILE_IGNORE_MERGE_ERRORS
, NULL
, NULL
)) {
129 *error
= File::OSErrorToFileError(GetLastError());
133 bool CopyDirectory(const FilePath
& from_path
, const FilePath
& to_path
,
135 // NOTE(maruel): Previous version of this function used to call
136 // SHFileOperation(). This used to copy the file attributes and extended
137 // attributes, OLE structured storage, NTFS file system alternate data
138 // streams, SECURITY_DESCRIPTOR. In practice, this is not what we want, we
139 // want the containing directory to propagate its SECURITY_DESCRIPTOR.
140 ThreadRestrictions::AssertIOAllowed();
142 // NOTE: I suspect we could support longer paths, but that would involve
143 // analyzing all our usage of files.
144 if (from_path
.value().length() >= MAX_PATH
||
145 to_path
.value().length() >= MAX_PATH
) {
149 // This function does not properly handle destinations within the source.
150 FilePath real_to_path
= to_path
;
151 if (PathExists(real_to_path
)) {
152 real_to_path
= MakeAbsoluteFilePath(real_to_path
);
153 if (real_to_path
.empty())
156 real_to_path
= MakeAbsoluteFilePath(real_to_path
.DirName());
157 if (real_to_path
.empty())
160 FilePath real_from_path
= MakeAbsoluteFilePath(from_path
);
161 if (real_from_path
.empty())
163 if (real_to_path
.value().size() >= real_from_path
.value().size() &&
164 real_to_path
.value().compare(0, real_from_path
.value().size(),
165 real_from_path
.value()) == 0) {
169 int traverse_type
= FileEnumerator::FILES
;
171 traverse_type
|= FileEnumerator::DIRECTORIES
;
172 FileEnumerator
traversal(from_path
, recursive
, traverse_type
);
174 if (!PathExists(from_path
)) {
175 DLOG(ERROR
) << "CopyDirectory() couldn't stat source directory: "
176 << from_path
.value().c_str();
179 // TODO(maruel): This is not necessary anymore.
180 DCHECK(recursive
|| DirectoryExists(from_path
));
182 FilePath current
= from_path
;
183 bool from_is_dir
= DirectoryExists(from_path
);
185 FilePath from_path_base
= from_path
;
186 if (recursive
&& DirectoryExists(to_path
)) {
187 // If the destination already exists and is a directory, then the
188 // top level of source needs to be copied.
189 from_path_base
= from_path
.DirName();
192 while (success
&& !current
.empty()) {
193 // current is the source path, including from_path, so append
194 // the suffix after from_path to to_path to create the target_path.
195 FilePath
target_path(to_path
);
196 if (from_path_base
!= current
) {
197 if (!from_path_base
.AppendRelativePath(current
, &target_path
)) {
204 if (!DirectoryExists(target_path
) &&
205 !::CreateDirectory(target_path
.value().c_str(), NULL
)) {
206 DLOG(ERROR
) << "CopyDirectory() couldn't create directory: "
207 << target_path
.value().c_str();
210 } else if (!internal::CopyFileUnsafe(current
, target_path
)) {
211 DLOG(ERROR
) << "CopyDirectory() couldn't create file: "
212 << target_path
.value().c_str();
216 current
= traversal
.Next();
217 if (!current
.empty())
218 from_is_dir
= traversal
.GetInfo().IsDirectory();
224 bool PathExists(const FilePath
& path
) {
225 ThreadRestrictions::AssertIOAllowed();
226 return (GetFileAttributes(path
.value().c_str()) != INVALID_FILE_ATTRIBUTES
);
229 bool PathIsWritable(const FilePath
& path
) {
230 ThreadRestrictions::AssertIOAllowed();
232 CreateFile(path
.value().c_str(), FILE_ADD_FILE
, kFileShareAll
,
233 NULL
, OPEN_EXISTING
, FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
235 if (dir
== INVALID_HANDLE_VALUE
)
242 bool DirectoryExists(const FilePath
& path
) {
243 ThreadRestrictions::AssertIOAllowed();
244 DWORD fileattr
= GetFileAttributes(path
.value().c_str());
245 if (fileattr
!= INVALID_FILE_ATTRIBUTES
)
246 return (fileattr
& FILE_ATTRIBUTE_DIRECTORY
) != 0;
250 bool GetTempDir(FilePath
* path
) {
251 wchar_t temp_path
[MAX_PATH
+ 1];
252 DWORD path_len
= ::GetTempPath(MAX_PATH
, temp_path
);
253 if (path_len
>= MAX_PATH
|| path_len
<= 0)
255 // TODO(evanm): the old behavior of this function was to always strip the
256 // trailing slash. We duplicate this here, but it shouldn't be necessary
257 // when everyone is using the appropriate FilePath APIs.
258 *path
= FilePath(temp_path
).StripTrailingSeparators();
262 FilePath
GetHomeDir() {
263 char16 result
[MAX_PATH
];
264 if (SUCCEEDED(SHGetFolderPath(NULL
, CSIDL_PROFILE
, NULL
, SHGFP_TYPE_CURRENT
,
267 return FilePath(result
);
270 // Fall back to the temporary directory on failure.
272 if (GetTempDir(&temp
))
276 return FilePath(L
"C:\\");
279 bool CreateTemporaryFile(FilePath
* path
) {
280 ThreadRestrictions::AssertIOAllowed();
284 if (!GetTempDir(path
))
287 if (CreateTemporaryFileInDir(*path
, &temp_file
)) {
295 // On POSIX we have semantics to create and open a temporary file
297 // TODO(jrg): is there equivalent call to use on Windows instead of
299 FILE* CreateAndOpenTemporaryFileInDir(const FilePath
& dir
, FilePath
* path
) {
300 ThreadRestrictions::AssertIOAllowed();
301 if (!CreateTemporaryFileInDir(dir
, path
)) {
304 // Open file in binary mode, to avoid problems with fwrite. On Windows
305 // it replaces \n's with \r\n's, which may surprise you.
306 // Reference: http://msdn.microsoft.com/en-us/library/h9t88zwz(VS.71).aspx
307 return OpenFile(*path
, "wb+");
310 bool CreateTemporaryFileInDir(const FilePath
& dir
, FilePath
* temp_file
) {
311 ThreadRestrictions::AssertIOAllowed();
313 wchar_t temp_name
[MAX_PATH
+ 1];
315 if (!GetTempFileName(dir
.value().c_str(), L
"", 0, temp_name
)) {
316 DPLOG(WARNING
) << "Failed to get temporary file name in "
317 << UTF16ToUTF8(dir
.value());
321 wchar_t long_temp_name
[MAX_PATH
+ 1];
322 DWORD long_name_len
= GetLongPathName(temp_name
, long_temp_name
, MAX_PATH
);
323 if (long_name_len
> MAX_PATH
|| long_name_len
== 0) {
324 // GetLongPathName() failed, but we still have a temporary file.
325 *temp_file
= FilePath(temp_name
);
329 FilePath::StringType long_temp_name_str
;
330 long_temp_name_str
.assign(long_temp_name
, long_name_len
);
331 *temp_file
= FilePath(long_temp_name_str
);
335 bool CreateTemporaryDirInDir(const FilePath
& base_dir
,
336 const FilePath::StringType
& prefix
,
338 ThreadRestrictions::AssertIOAllowed();
340 FilePath path_to_create
;
342 for (int count
= 0; count
< 50; ++count
) {
343 // Try create a new temporary directory with random generated name. If
344 // the one exists, keep trying another path name until we reach some limit.
345 string16 new_dir_name
;
346 new_dir_name
.assign(prefix
);
347 new_dir_name
.append(IntToString16(GetCurrentProcId()));
348 new_dir_name
.push_back('_');
349 new_dir_name
.append(IntToString16(RandInt(0, kint16max
)));
351 path_to_create
= base_dir
.Append(new_dir_name
);
352 if (::CreateDirectory(path_to_create
.value().c_str(), NULL
)) {
353 *new_dir
= path_to_create
;
361 bool CreateNewTempDirectory(const FilePath::StringType
& prefix
,
362 FilePath
* new_temp_path
) {
363 ThreadRestrictions::AssertIOAllowed();
365 FilePath system_temp_dir
;
366 if (!GetTempDir(&system_temp_dir
))
369 return CreateTemporaryDirInDir(system_temp_dir
, prefix
, new_temp_path
);
372 bool CreateDirectoryAndGetError(const FilePath
& full_path
,
373 File::Error
* error
) {
374 ThreadRestrictions::AssertIOAllowed();
376 // If the path exists, we've succeeded if it's a directory, failed otherwise.
377 const wchar_t* full_path_str
= full_path
.value().c_str();
378 DWORD fileattr
= ::GetFileAttributes(full_path_str
);
379 if (fileattr
!= INVALID_FILE_ATTRIBUTES
) {
380 if ((fileattr
& FILE_ATTRIBUTE_DIRECTORY
) != 0) {
381 DVLOG(1) << "CreateDirectory(" << full_path_str
<< "), "
382 << "directory already exists.";
385 DLOG(WARNING
) << "CreateDirectory(" << full_path_str
<< "), "
386 << "conflicts with existing file.";
388 *error
= File::FILE_ERROR_NOT_A_DIRECTORY
;
393 // Invariant: Path does not exist as file or directory.
395 // Attempt to create the parent recursively. This will immediately return
396 // true if it already exists, otherwise will create all required parent
397 // directories starting with the highest-level missing parent.
398 FilePath
parent_path(full_path
.DirName());
399 if (parent_path
.value() == full_path
.value()) {
401 *error
= File::FILE_ERROR_NOT_FOUND
;
405 if (!CreateDirectoryAndGetError(parent_path
, error
)) {
406 DLOG(WARNING
) << "Failed to create one of the parent directories.";
408 DCHECK(*error
!= File::FILE_OK
);
413 if (!::CreateDirectory(full_path_str
, NULL
)) {
414 DWORD error_code
= ::GetLastError();
415 if (error_code
== ERROR_ALREADY_EXISTS
&& DirectoryExists(full_path
)) {
416 // This error code ERROR_ALREADY_EXISTS doesn't indicate whether we
417 // were racing with someone creating the same directory, or a file
418 // with the same path. If DirectoryExists() returns true, we lost the
419 // race to create the same directory.
423 *error
= File::OSErrorToFileError(error_code
);
424 DLOG(WARNING
) << "Failed to create directory " << full_path_str
425 << ", last error is " << error_code
<< ".";
433 bool NormalizeFilePath(const FilePath
& path
, FilePath
* real_path
) {
434 ThreadRestrictions::AssertIOAllowed();
435 FilePath mapped_file
;
436 if (!NormalizeToNativeFilePath(path
, &mapped_file
))
438 // NormalizeToNativeFilePath() will return a path that starts with
439 // "\Device\Harddisk...". Helper DevicePathToDriveLetterPath()
440 // will find a drive letter which maps to the path's device, so
441 // that we return a path starting with a drive letter.
442 return DevicePathToDriveLetterPath(mapped_file
, real_path
);
445 bool DevicePathToDriveLetterPath(const FilePath
& nt_device_path
,
446 FilePath
* out_drive_letter_path
) {
447 ThreadRestrictions::AssertIOAllowed();
449 // Get the mapping of drive letters to device paths.
450 const int kDriveMappingSize
= 1024;
451 wchar_t drive_mapping
[kDriveMappingSize
] = {'\0'};
452 if (!::GetLogicalDriveStrings(kDriveMappingSize
- 1, drive_mapping
)) {
453 DLOG(ERROR
) << "Failed to get drive mapping.";
457 // The drive mapping is a sequence of null terminated strings.
458 // The last string is empty.
459 wchar_t* drive_map_ptr
= drive_mapping
;
460 wchar_t device_path_as_string
[MAX_PATH
];
461 wchar_t drive
[] = L
" :";
463 // For each string in the drive mapping, get the junction that links
464 // to it. If that junction is a prefix of |device_path|, then we
465 // know that |drive| is the real path prefix.
466 while (*drive_map_ptr
) {
467 drive
[0] = drive_map_ptr
[0]; // Copy the drive letter.
469 if (QueryDosDevice(drive
, device_path_as_string
, MAX_PATH
)) {
470 FilePath
device_path(device_path_as_string
);
471 if (device_path
== nt_device_path
||
472 device_path
.IsParent(nt_device_path
)) {
473 *out_drive_letter_path
= FilePath(drive
+
474 nt_device_path
.value().substr(wcslen(device_path_as_string
)));
478 // Move to the next drive letter string, which starts one
479 // increment after the '\0' that terminates the current string.
480 while (*drive_map_ptr
++);
483 // No drive matched. The path does not start with a device junction
484 // that is mounted as a drive letter. This means there is no drive
485 // letter path to the volume that holds |device_path|, so fail.
489 bool NormalizeToNativeFilePath(const FilePath
& path
, FilePath
* nt_path
) {
490 ThreadRestrictions::AssertIOAllowed();
491 // In Vista, GetFinalPathNameByHandle() would give us the real path
492 // from a file handle. If we ever deprecate XP, consider changing the
493 // code below to a call to GetFinalPathNameByHandle(). The method this
494 // function uses is explained in the following msdn article:
495 // http://msdn.microsoft.com/en-us/library/aa366789(VS.85).aspx
496 base::win::ScopedHandle
file_handle(
497 ::CreateFile(path
.value().c_str(),
502 FILE_ATTRIBUTE_NORMAL
,
507 // Create a file mapping object. Can't easily use MemoryMappedFile, because
508 // we only map the first byte, and need direct access to the handle. You can
509 // not map an empty file, this call fails in that case.
510 base::win::ScopedHandle
file_map_handle(
511 ::CreateFileMapping(file_handle
.Get(),
515 1, // Just one byte. No need to look at the data.
517 if (!file_map_handle
)
520 // Use a view of the file to get the path to the file.
521 void* file_view
= MapViewOfFile(file_map_handle
.Get(),
522 FILE_MAP_READ
, 0, 0, 1);
526 // The expansion of |path| into a full path may make it longer.
527 // GetMappedFileName() will fail if the result is longer than MAX_PATH.
528 // Pad a bit to be safe. If kMaxPathLength is ever changed to be less
529 // than MAX_PATH, it would be nessisary to test that GetMappedFileName()
530 // not return kMaxPathLength. This would mean that only part of the
531 // path fit in |mapped_file_path|.
532 const int kMaxPathLength
= MAX_PATH
+ 10;
533 wchar_t mapped_file_path
[kMaxPathLength
];
534 bool success
= false;
535 HANDLE cp
= GetCurrentProcess();
536 if (::GetMappedFileNameW(cp
, file_view
, mapped_file_path
, kMaxPathLength
)) {
537 *nt_path
= FilePath(mapped_file_path
);
540 ::UnmapViewOfFile(file_view
);
544 // TODO(rkc): Work out if we want to handle NTFS junctions here or not, handle
545 // them if we do decide to.
546 bool IsLink(const FilePath
& file_path
) {
550 bool GetFileInfo(const FilePath
& file_path
, File::Info
* results
) {
551 ThreadRestrictions::AssertIOAllowed();
553 WIN32_FILE_ATTRIBUTE_DATA attr
;
554 if (!GetFileAttributesEx(file_path
.value().c_str(),
555 GetFileExInfoStandard
, &attr
)) {
560 size
.HighPart
= attr
.nFileSizeHigh
;
561 size
.LowPart
= attr
.nFileSizeLow
;
562 results
->size
= size
.QuadPart
;
564 results
->is_directory
=
565 (attr
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
) != 0;
566 results
->last_modified
= Time::FromFileTime(attr
.ftLastWriteTime
);
567 results
->last_accessed
= Time::FromFileTime(attr
.ftLastAccessTime
);
568 results
->creation_time
= Time::FromFileTime(attr
.ftCreationTime
);
573 FILE* OpenFile(const FilePath
& filename
, const char* mode
) {
574 ThreadRestrictions::AssertIOAllowed();
575 std::wstring w_mode
= ASCIIToWide(std::string(mode
));
576 return _wfsopen(filename
.value().c_str(), w_mode
.c_str(), _SH_DENYNO
);
579 int ReadFile(const FilePath
& filename
, char* data
, int max_size
) {
580 ThreadRestrictions::AssertIOAllowed();
581 base::win::ScopedHandle
file(CreateFile(filename
.value().c_str(),
583 FILE_SHARE_READ
| FILE_SHARE_WRITE
,
586 FILE_FLAG_SEQUENTIAL_SCAN
,
592 if (::ReadFile(file
, data
, max_size
, &read
, NULL
))
598 int WriteFile(const FilePath
& filename
, const char* data
, int size
) {
599 ThreadRestrictions::AssertIOAllowed();
600 base::win::ScopedHandle
file(CreateFile(filename
.value().c_str(),
608 DLOG_GETLASTERROR(WARNING
) << "CreateFile failed for path "
609 << UTF16ToUTF8(filename
.value());
614 BOOL result
= ::WriteFile(file
, data
, size
, &written
, NULL
);
615 if (result
&& static_cast<int>(written
) == size
)
620 DLOG_GETLASTERROR(WARNING
) << "writing file "
621 << UTF16ToUTF8(filename
.value()) << " failed";
623 // Didn't write all the bytes.
624 DLOG(WARNING
) << "wrote" << written
<< " bytes to "
625 << UTF16ToUTF8(filename
.value()) << " expected " << size
;
630 int AppendToFile(const FilePath
& filename
, const char* data
, int size
) {
631 ThreadRestrictions::AssertIOAllowed();
632 base::win::ScopedHandle
file(CreateFile(filename
.value().c_str(),
640 DLOG_GETLASTERROR(WARNING
) << "CreateFile failed for path "
641 << UTF16ToUTF8(filename
.value());
646 BOOL result
= ::WriteFile(file
, data
, size
, &written
, NULL
);
647 if (result
&& static_cast<int>(written
) == size
)
652 DLOG_GETLASTERROR(WARNING
) << "writing file "
653 << UTF16ToUTF8(filename
.value())
656 // Didn't write all the bytes.
657 DLOG(WARNING
) << "wrote" << written
<< " bytes to "
658 << UTF16ToUTF8(filename
.value()) << " expected " << size
;
663 // Gets the current working directory for the process.
664 bool GetCurrentDirectory(FilePath
* dir
) {
665 ThreadRestrictions::AssertIOAllowed();
667 wchar_t system_buffer
[MAX_PATH
];
668 system_buffer
[0] = 0;
669 DWORD len
= ::GetCurrentDirectory(MAX_PATH
, system_buffer
);
670 if (len
== 0 || len
> MAX_PATH
)
672 // TODO(evanm): the old behavior of this function was to always strip the
673 // trailing slash. We duplicate this here, but it shouldn't be necessary
674 // when everyone is using the appropriate FilePath APIs.
675 std::wstring
dir_str(system_buffer
);
676 *dir
= FilePath(dir_str
).StripTrailingSeparators();
680 // Sets the current working directory for the process.
681 bool SetCurrentDirectory(const FilePath
& directory
) {
682 ThreadRestrictions::AssertIOAllowed();
683 BOOL ret
= ::SetCurrentDirectory(directory
.value().c_str());
687 int GetMaximumPathComponentLength(const FilePath
& path
) {
688 ThreadRestrictions::AssertIOAllowed();
690 wchar_t volume_path
[MAX_PATH
];
691 if (!GetVolumePathNameW(path
.NormalizePathSeparators().value().c_str(),
693 arraysize(volume_path
))) {
697 DWORD max_length
= 0;
698 if (!GetVolumeInformationW(volume_path
, NULL
, 0, NULL
, &max_length
, NULL
,
703 // Length of |path| with path separator appended.
704 size_t prefix
= path
.StripTrailingSeparators().value().size() + 1;
705 // The whole path string must be shorter than MAX_PATH. That is, it must be
706 // prefix + component_length < MAX_PATH (or equivalently, <= MAX_PATH - 1).
707 int whole_path_limit
= std::max(0, MAX_PATH
- 1 - static_cast<int>(prefix
));
708 return std::min(whole_path_limit
, static_cast<int>(max_length
));
711 // -----------------------------------------------------------------------------
715 bool MoveUnsafe(const FilePath
& from_path
, const FilePath
& to_path
) {
716 ThreadRestrictions::AssertIOAllowed();
718 // NOTE: I suspect we could support longer paths, but that would involve
719 // analyzing all our usage of files.
720 if (from_path
.value().length() >= MAX_PATH
||
721 to_path
.value().length() >= MAX_PATH
) {
724 if (MoveFileEx(from_path
.value().c_str(), to_path
.value().c_str(),
725 MOVEFILE_COPY_ALLOWED
| MOVEFILE_REPLACE_EXISTING
) != 0)
728 // Keep the last error value from MoveFileEx around in case the below
731 DWORD last_error
= ::GetLastError();
733 if (DirectoryExists(from_path
)) {
734 // MoveFileEx fails if moving directory across volumes. We will simulate
735 // the move by using Copy and Delete. Ideally we could check whether
736 // from_path and to_path are indeed in different volumes.
737 ret
= internal::CopyAndDeleteDirectory(from_path
, to_path
);
741 // Leave a clue about what went wrong so that it can be (at least) picked
742 // up by a PLOG entry.
743 ::SetLastError(last_error
);
749 bool CopyFileUnsafe(const FilePath
& from_path
, const FilePath
& to_path
) {
750 ThreadRestrictions::AssertIOAllowed();
752 // NOTE: I suspect we could support longer paths, but that would involve
753 // analyzing all our usage of files.
754 if (from_path
.value().length() >= MAX_PATH
||
755 to_path
.value().length() >= MAX_PATH
) {
759 // Unlike the posix implementation that copies the file manually and discards
760 // the ACL bits, CopyFile() copies the complete SECURITY_DESCRIPTOR and access
761 // bits, which is usually not what we want. We can't do much about the
762 // SECURITY_DESCRIPTOR but at least remove the read only bit.
763 const wchar_t* dest
= to_path
.value().c_str();
764 if (!::CopyFile(from_path
.value().c_str(), dest
, false)) {
768 DWORD attrs
= GetFileAttributes(dest
);
769 if (attrs
== INVALID_FILE_ATTRIBUTES
) {
772 if (attrs
& FILE_ATTRIBUTE_READONLY
) {
773 SetFileAttributes(dest
, attrs
& ~FILE_ATTRIBUTE_READONLY
);
778 bool CopyAndDeleteDirectory(const FilePath
& from_path
,
779 const FilePath
& to_path
) {
780 ThreadRestrictions::AssertIOAllowed();
781 if (CopyDirectory(from_path
, to_path
, true)) {
782 if (DeleteFile(from_path
, true))
785 // Like Move, this function is not transactional, so we just
786 // leave the copied bits behind if deleting from_path fails.
787 // If to_path exists previously then we have already overwritten
788 // it by now, we don't get better off by deleting the new bits.
793 } // namespace internal