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
)
55 // If not recursing, then first check to see if |path| is a directory.
56 // If it is, then remove it with RemoveDirectory.
58 if (GetFileInfo(path
, &file_info
) && file_info
.is_directory
)
59 return RemoveDirectory(path
.value().c_str()) != 0;
61 // Otherwise, it's a file, wildcard or non-existant. Try DeleteFile first
62 // because it should be faster. If DeleteFile fails, then we fall through
63 // to SHFileOperation, which will do the right thing.
64 if (::DeleteFile(path
.value().c_str()) != 0)
68 // SHFILEOPSTRUCT wants the path to be terminated with two NULLs,
69 // so we have to use wcscpy because wcscpy_s writes non-NULLs
70 // into the rest of the buffer.
71 wchar_t double_terminated_path
[MAX_PATH
+ 1] = {0};
72 #pragma warning(suppress:4996) // don't complain about wcscpy deprecation
73 wcscpy(double_terminated_path
, path
.value().c_str());
75 SHFILEOPSTRUCT file_operation
= {0};
76 file_operation
.wFunc
= FO_DELETE
;
77 file_operation
.pFrom
= double_terminated_path
;
78 file_operation
.fFlags
= FOF_NOERRORUI
| FOF_SILENT
| FOF_NOCONFIRMATION
;
80 file_operation
.fFlags
|= FOF_NORECURSION
| FOF_FILESONLY
;
81 int err
= SHFileOperation(&file_operation
);
83 // Since we're passing flags to the operation telling it to be silent,
84 // it's possible for the operation to be aborted/cancelled without err
85 // being set (although MSDN doesn't give any scenarios for how this can
86 // happen). See MSDN for SHFileOperation and SHFILEOPTSTRUCT.
87 if (file_operation
.fAnyOperationsAborted
)
90 // Some versions of Windows return ERROR_FILE_NOT_FOUND (0x2) when deleting
91 // an empty directory and some return 0x402 when they should be returning
92 // ERROR_FILE_NOT_FOUND. MSDN says Vista and up won't return 0x402.
93 return (err
== 0 || err
== ERROR_FILE_NOT_FOUND
|| err
== 0x402);
96 bool DeleteFileAfterReboot(const FilePath
& path
) {
97 ThreadRestrictions::AssertIOAllowed();
99 if (path
.value().length() >= MAX_PATH
)
102 return MoveFileEx(path
.value().c_str(), NULL
,
103 MOVEFILE_DELAY_UNTIL_REBOOT
|
104 MOVEFILE_REPLACE_EXISTING
) != FALSE
;
107 bool ReplaceFile(const FilePath
& from_path
,
108 const FilePath
& to_path
,
109 File::Error
* error
) {
110 ThreadRestrictions::AssertIOAllowed();
111 // Try a simple move first. It will only succeed when |to_path| doesn't
113 if (::MoveFile(from_path
.value().c_str(), to_path
.value().c_str()))
115 // Try the full-blown replace if the move fails, as ReplaceFile will only
116 // succeed when |to_path| does exist. When writing to a network share, we may
117 // not be able to change the ACLs. Ignore ACL errors then
118 // (REPLACEFILE_IGNORE_MERGE_ERRORS).
119 if (::ReplaceFile(to_path
.value().c_str(), from_path
.value().c_str(), NULL
,
120 REPLACEFILE_IGNORE_MERGE_ERRORS
, NULL
, NULL
)) {
124 *error
= File::OSErrorToFileError(GetLastError());
128 bool CopyDirectory(const FilePath
& from_path
, const FilePath
& to_path
,
130 // NOTE(maruel): Previous version of this function used to call
131 // SHFileOperation(). This used to copy the file attributes and extended
132 // attributes, OLE structured storage, NTFS file system alternate data
133 // streams, SECURITY_DESCRIPTOR. In practice, this is not what we want, we
134 // want the containing directory to propagate its SECURITY_DESCRIPTOR.
135 ThreadRestrictions::AssertIOAllowed();
137 // NOTE: I suspect we could support longer paths, but that would involve
138 // analyzing all our usage of files.
139 if (from_path
.value().length() >= MAX_PATH
||
140 to_path
.value().length() >= MAX_PATH
) {
144 // This function does not properly handle destinations within the source.
145 FilePath real_to_path
= to_path
;
146 if (PathExists(real_to_path
)) {
147 real_to_path
= MakeAbsoluteFilePath(real_to_path
);
148 if (real_to_path
.empty())
151 real_to_path
= MakeAbsoluteFilePath(real_to_path
.DirName());
152 if (real_to_path
.empty())
155 FilePath real_from_path
= MakeAbsoluteFilePath(from_path
);
156 if (real_from_path
.empty())
158 if (real_to_path
.value().size() >= real_from_path
.value().size() &&
159 real_to_path
.value().compare(0, real_from_path
.value().size(),
160 real_from_path
.value()) == 0) {
164 int traverse_type
= FileEnumerator::FILES
;
166 traverse_type
|= FileEnumerator::DIRECTORIES
;
167 FileEnumerator
traversal(from_path
, recursive
, traverse_type
);
169 if (!PathExists(from_path
)) {
170 DLOG(ERROR
) << "CopyDirectory() couldn't stat source directory: "
171 << from_path
.value().c_str();
174 // TODO(maruel): This is not necessary anymore.
175 DCHECK(recursive
|| DirectoryExists(from_path
));
177 FilePath current
= from_path
;
178 bool from_is_dir
= DirectoryExists(from_path
);
180 FilePath from_path_base
= from_path
;
181 if (recursive
&& DirectoryExists(to_path
)) {
182 // If the destination already exists and is a directory, then the
183 // top level of source needs to be copied.
184 from_path_base
= from_path
.DirName();
187 while (success
&& !current
.empty()) {
188 // current is the source path, including from_path, so append
189 // the suffix after from_path to to_path to create the target_path.
190 FilePath
target_path(to_path
);
191 if (from_path_base
!= current
) {
192 if (!from_path_base
.AppendRelativePath(current
, &target_path
)) {
199 if (!DirectoryExists(target_path
) &&
200 !::CreateDirectory(target_path
.value().c_str(), NULL
)) {
201 DLOG(ERROR
) << "CopyDirectory() couldn't create directory: "
202 << target_path
.value().c_str();
205 } else if (!internal::CopyFileUnsafe(current
, target_path
)) {
206 DLOG(ERROR
) << "CopyDirectory() couldn't create file: "
207 << target_path
.value().c_str();
211 current
= traversal
.Next();
212 if (!current
.empty())
213 from_is_dir
= traversal
.GetInfo().IsDirectory();
219 bool PathExists(const FilePath
& path
) {
220 ThreadRestrictions::AssertIOAllowed();
221 return (GetFileAttributes(path
.value().c_str()) != INVALID_FILE_ATTRIBUTES
);
224 bool PathIsWritable(const FilePath
& path
) {
225 ThreadRestrictions::AssertIOAllowed();
227 CreateFile(path
.value().c_str(), FILE_ADD_FILE
, kFileShareAll
,
228 NULL
, OPEN_EXISTING
, FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
230 if (dir
== INVALID_HANDLE_VALUE
)
237 bool DirectoryExists(const FilePath
& path
) {
238 ThreadRestrictions::AssertIOAllowed();
239 DWORD fileattr
= GetFileAttributes(path
.value().c_str());
240 if (fileattr
!= INVALID_FILE_ATTRIBUTES
)
241 return (fileattr
& FILE_ATTRIBUTE_DIRECTORY
) != 0;
245 bool GetTempDir(FilePath
* path
) {
246 wchar_t temp_path
[MAX_PATH
+ 1];
247 DWORD path_len
= ::GetTempPath(MAX_PATH
, temp_path
);
248 if (path_len
>= MAX_PATH
|| path_len
<= 0)
250 // TODO(evanm): the old behavior of this function was to always strip the
251 // trailing slash. We duplicate this here, but it shouldn't be necessary
252 // when everyone is using the appropriate FilePath APIs.
253 *path
= FilePath(temp_path
).StripTrailingSeparators();
257 FilePath
GetHomeDir() {
258 char16 result
[MAX_PATH
];
259 if (SUCCEEDED(SHGetFolderPath(NULL
, CSIDL_PROFILE
, NULL
, SHGFP_TYPE_CURRENT
,
262 return FilePath(result
);
265 // Fall back to the temporary directory on failure.
267 if (GetTempDir(&temp
))
271 return FilePath(L
"C:\\");
274 bool CreateTemporaryFile(FilePath
* path
) {
275 ThreadRestrictions::AssertIOAllowed();
279 if (!GetTempDir(path
))
282 if (CreateTemporaryFileInDir(*path
, &temp_file
)) {
290 // On POSIX we have semantics to create and open a temporary file
292 // TODO(jrg): is there equivalent call to use on Windows instead of
294 FILE* CreateAndOpenTemporaryFileInDir(const FilePath
& dir
, FilePath
* path
) {
295 ThreadRestrictions::AssertIOAllowed();
296 if (!CreateTemporaryFileInDir(dir
, path
)) {
299 // Open file in binary mode, to avoid problems with fwrite. On Windows
300 // it replaces \n's with \r\n's, which may surprise you.
301 // Reference: http://msdn.microsoft.com/en-us/library/h9t88zwz(VS.71).aspx
302 return OpenFile(*path
, "wb+");
305 bool CreateTemporaryFileInDir(const FilePath
& dir
, FilePath
* temp_file
) {
306 ThreadRestrictions::AssertIOAllowed();
308 wchar_t temp_name
[MAX_PATH
+ 1];
310 if (!GetTempFileName(dir
.value().c_str(), L
"", 0, temp_name
)) {
311 DPLOG(WARNING
) << "Failed to get temporary file name in "
312 << UTF16ToUTF8(dir
.value());
316 wchar_t long_temp_name
[MAX_PATH
+ 1];
317 DWORD long_name_len
= GetLongPathName(temp_name
, long_temp_name
, MAX_PATH
);
318 if (long_name_len
> MAX_PATH
|| long_name_len
== 0) {
319 // GetLongPathName() failed, but we still have a temporary file.
320 *temp_file
= FilePath(temp_name
);
324 FilePath::StringType long_temp_name_str
;
325 long_temp_name_str
.assign(long_temp_name
, long_name_len
);
326 *temp_file
= FilePath(long_temp_name_str
);
330 bool CreateTemporaryDirInDir(const FilePath
& base_dir
,
331 const FilePath::StringType
& prefix
,
333 ThreadRestrictions::AssertIOAllowed();
335 FilePath path_to_create
;
337 for (int count
= 0; count
< 50; ++count
) {
338 // Try create a new temporary directory with random generated name. If
339 // the one exists, keep trying another path name until we reach some limit.
340 string16 new_dir_name
;
341 new_dir_name
.assign(prefix
);
342 new_dir_name
.append(IntToString16(GetCurrentProcId()));
343 new_dir_name
.push_back('_');
344 new_dir_name
.append(IntToString16(RandInt(0, kint16max
)));
346 path_to_create
= base_dir
.Append(new_dir_name
);
347 if (::CreateDirectory(path_to_create
.value().c_str(), NULL
)) {
348 *new_dir
= path_to_create
;
356 bool CreateNewTempDirectory(const FilePath::StringType
& prefix
,
357 FilePath
* new_temp_path
) {
358 ThreadRestrictions::AssertIOAllowed();
360 FilePath system_temp_dir
;
361 if (!GetTempDir(&system_temp_dir
))
364 return CreateTemporaryDirInDir(system_temp_dir
, prefix
, new_temp_path
);
367 bool CreateDirectoryAndGetError(const FilePath
& full_path
,
368 File::Error
* error
) {
369 ThreadRestrictions::AssertIOAllowed();
371 // If the path exists, we've succeeded if it's a directory, failed otherwise.
372 const wchar_t* full_path_str
= full_path
.value().c_str();
373 DWORD fileattr
= ::GetFileAttributes(full_path_str
);
374 if (fileattr
!= INVALID_FILE_ATTRIBUTES
) {
375 if ((fileattr
& FILE_ATTRIBUTE_DIRECTORY
) != 0) {
376 DVLOG(1) << "CreateDirectory(" << full_path_str
<< "), "
377 << "directory already exists.";
380 DLOG(WARNING
) << "CreateDirectory(" << full_path_str
<< "), "
381 << "conflicts with existing file.";
383 *error
= File::FILE_ERROR_NOT_A_DIRECTORY
;
388 // Invariant: Path does not exist as file or directory.
390 // Attempt to create the parent recursively. This will immediately return
391 // true if it already exists, otherwise will create all required parent
392 // directories starting with the highest-level missing parent.
393 FilePath
parent_path(full_path
.DirName());
394 if (parent_path
.value() == full_path
.value()) {
396 *error
= File::FILE_ERROR_NOT_FOUND
;
400 if (!CreateDirectoryAndGetError(parent_path
, error
)) {
401 DLOG(WARNING
) << "Failed to create one of the parent directories.";
403 DCHECK(*error
!= File::FILE_OK
);
408 if (!::CreateDirectory(full_path_str
, NULL
)) {
409 DWORD error_code
= ::GetLastError();
410 if (error_code
== ERROR_ALREADY_EXISTS
&& DirectoryExists(full_path
)) {
411 // This error code ERROR_ALREADY_EXISTS doesn't indicate whether we
412 // were racing with someone creating the same directory, or a file
413 // with the same path. If DirectoryExists() returns true, we lost the
414 // race to create the same directory.
418 *error
= File::OSErrorToFileError(error_code
);
419 DLOG(WARNING
) << "Failed to create directory " << full_path_str
420 << ", last error is " << error_code
<< ".";
428 bool NormalizeFilePath(const FilePath
& path
, FilePath
* real_path
) {
429 ThreadRestrictions::AssertIOAllowed();
430 FilePath mapped_file
;
431 if (!NormalizeToNativeFilePath(path
, &mapped_file
))
433 // NormalizeToNativeFilePath() will return a path that starts with
434 // "\Device\Harddisk...". Helper DevicePathToDriveLetterPath()
435 // will find a drive letter which maps to the path's device, so
436 // that we return a path starting with a drive letter.
437 return DevicePathToDriveLetterPath(mapped_file
, real_path
);
440 bool DevicePathToDriveLetterPath(const FilePath
& nt_device_path
,
441 FilePath
* out_drive_letter_path
) {
442 ThreadRestrictions::AssertIOAllowed();
444 // Get the mapping of drive letters to device paths.
445 const int kDriveMappingSize
= 1024;
446 wchar_t drive_mapping
[kDriveMappingSize
] = {'\0'};
447 if (!::GetLogicalDriveStrings(kDriveMappingSize
- 1, drive_mapping
)) {
448 DLOG(ERROR
) << "Failed to get drive mapping.";
452 // The drive mapping is a sequence of null terminated strings.
453 // The last string is empty.
454 wchar_t* drive_map_ptr
= drive_mapping
;
455 wchar_t device_path_as_string
[MAX_PATH
];
456 wchar_t drive
[] = L
" :";
458 // For each string in the drive mapping, get the junction that links
459 // to it. If that junction is a prefix of |device_path|, then we
460 // know that |drive| is the real path prefix.
461 while (*drive_map_ptr
) {
462 drive
[0] = drive_map_ptr
[0]; // Copy the drive letter.
464 if (QueryDosDevice(drive
, device_path_as_string
, MAX_PATH
)) {
465 FilePath
device_path(device_path_as_string
);
466 if (device_path
== nt_device_path
||
467 device_path
.IsParent(nt_device_path
)) {
468 *out_drive_letter_path
= FilePath(drive
+
469 nt_device_path
.value().substr(wcslen(device_path_as_string
)));
473 // Move to the next drive letter string, which starts one
474 // increment after the '\0' that terminates the current string.
475 while (*drive_map_ptr
++);
478 // No drive matched. The path does not start with a device junction
479 // that is mounted as a drive letter. This means there is no drive
480 // letter path to the volume that holds |device_path|, so fail.
484 bool NormalizeToNativeFilePath(const FilePath
& path
, FilePath
* nt_path
) {
485 ThreadRestrictions::AssertIOAllowed();
486 // In Vista, GetFinalPathNameByHandle() would give us the real path
487 // from a file handle. If we ever deprecate XP, consider changing the
488 // code below to a call to GetFinalPathNameByHandle(). The method this
489 // function uses is explained in the following msdn article:
490 // http://msdn.microsoft.com/en-us/library/aa366789(VS.85).aspx
491 base::win::ScopedHandle
file_handle(
492 ::CreateFile(path
.value().c_str(),
497 FILE_ATTRIBUTE_NORMAL
,
502 // Create a file mapping object. Can't easily use MemoryMappedFile, because
503 // we only map the first byte, and need direct access to the handle. You can
504 // not map an empty file, this call fails in that case.
505 base::win::ScopedHandle
file_map_handle(
506 ::CreateFileMapping(file_handle
.Get(),
510 1, // Just one byte. No need to look at the data.
512 if (!file_map_handle
)
515 // Use a view of the file to get the path to the file.
516 void* file_view
= MapViewOfFile(file_map_handle
.Get(),
517 FILE_MAP_READ
, 0, 0, 1);
521 // The expansion of |path| into a full path may make it longer.
522 // GetMappedFileName() will fail if the result is longer than MAX_PATH.
523 // Pad a bit to be safe. If kMaxPathLength is ever changed to be less
524 // than MAX_PATH, it would be nessisary to test that GetMappedFileName()
525 // not return kMaxPathLength. This would mean that only part of the
526 // path fit in |mapped_file_path|.
527 const int kMaxPathLength
= MAX_PATH
+ 10;
528 wchar_t mapped_file_path
[kMaxPathLength
];
529 bool success
= false;
530 HANDLE cp
= GetCurrentProcess();
531 if (::GetMappedFileNameW(cp
, file_view
, mapped_file_path
, kMaxPathLength
)) {
532 *nt_path
= FilePath(mapped_file_path
);
535 ::UnmapViewOfFile(file_view
);
539 // TODO(rkc): Work out if we want to handle NTFS junctions here or not, handle
540 // them if we do decide to.
541 bool IsLink(const FilePath
& file_path
) {
545 bool GetFileInfo(const FilePath
& file_path
, File::Info
* results
) {
546 ThreadRestrictions::AssertIOAllowed();
548 WIN32_FILE_ATTRIBUTE_DATA attr
;
549 if (!GetFileAttributesEx(file_path
.value().c_str(),
550 GetFileExInfoStandard
, &attr
)) {
555 size
.HighPart
= attr
.nFileSizeHigh
;
556 size
.LowPart
= attr
.nFileSizeLow
;
557 results
->size
= size
.QuadPart
;
559 results
->is_directory
=
560 (attr
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
) != 0;
561 results
->last_modified
= Time::FromFileTime(attr
.ftLastWriteTime
);
562 results
->last_accessed
= Time::FromFileTime(attr
.ftLastAccessTime
);
563 results
->creation_time
= Time::FromFileTime(attr
.ftCreationTime
);
568 FILE* OpenFile(const FilePath
& filename
, const char* mode
) {
569 ThreadRestrictions::AssertIOAllowed();
570 std::wstring w_mode
= ASCIIToWide(std::string(mode
));
571 return _wfsopen(filename
.value().c_str(), w_mode
.c_str(), _SH_DENYNO
);
574 int ReadFile(const FilePath
& filename
, char* data
, int size
) {
575 ThreadRestrictions::AssertIOAllowed();
576 base::win::ScopedHandle
file(CreateFile(filename
.value().c_str(),
578 FILE_SHARE_READ
| FILE_SHARE_WRITE
,
581 FILE_FLAG_SEQUENTIAL_SCAN
,
587 if (::ReadFile(file
, data
, size
, &read
, NULL
) &&
588 static_cast<int>(read
) == size
)
593 int WriteFile(const FilePath
& filename
, const char* data
, int size
) {
594 ThreadRestrictions::AssertIOAllowed();
595 base::win::ScopedHandle
file(CreateFile(filename
.value().c_str(),
603 DLOG_GETLASTERROR(WARNING
) << "CreateFile failed for path "
604 << UTF16ToUTF8(filename
.value());
609 BOOL result
= ::WriteFile(file
, data
, size
, &written
, NULL
);
610 if (result
&& static_cast<int>(written
) == size
)
615 DLOG_GETLASTERROR(WARNING
) << "writing file "
616 << UTF16ToUTF8(filename
.value()) << " failed";
618 // Didn't write all the bytes.
619 DLOG(WARNING
) << "wrote" << written
<< " bytes to "
620 << UTF16ToUTF8(filename
.value()) << " expected " << size
;
625 int AppendToFile(const FilePath
& filename
, const char* data
, int size
) {
626 ThreadRestrictions::AssertIOAllowed();
627 base::win::ScopedHandle
file(CreateFile(filename
.value().c_str(),
635 DLOG_GETLASTERROR(WARNING
) << "CreateFile failed for path "
636 << UTF16ToUTF8(filename
.value());
641 BOOL result
= ::WriteFile(file
, data
, size
, &written
, NULL
);
642 if (result
&& static_cast<int>(written
) == size
)
647 DLOG_GETLASTERROR(WARNING
) << "writing file "
648 << UTF16ToUTF8(filename
.value())
651 // Didn't write all the bytes.
652 DLOG(WARNING
) << "wrote" << written
<< " bytes to "
653 << UTF16ToUTF8(filename
.value()) << " expected " << size
;
658 // Gets the current working directory for the process.
659 bool GetCurrentDirectory(FilePath
* dir
) {
660 ThreadRestrictions::AssertIOAllowed();
662 wchar_t system_buffer
[MAX_PATH
];
663 system_buffer
[0] = 0;
664 DWORD len
= ::GetCurrentDirectory(MAX_PATH
, system_buffer
);
665 if (len
== 0 || len
> MAX_PATH
)
667 // TODO(evanm): the old behavior of this function was to always strip the
668 // trailing slash. We duplicate this here, but it shouldn't be necessary
669 // when everyone is using the appropriate FilePath APIs.
670 std::wstring
dir_str(system_buffer
);
671 *dir
= FilePath(dir_str
).StripTrailingSeparators();
675 // Sets the current working directory for the process.
676 bool SetCurrentDirectory(const FilePath
& directory
) {
677 ThreadRestrictions::AssertIOAllowed();
678 BOOL ret
= ::SetCurrentDirectory(directory
.value().c_str());
682 int GetMaximumPathComponentLength(const FilePath
& path
) {
683 ThreadRestrictions::AssertIOAllowed();
685 wchar_t volume_path
[MAX_PATH
];
686 if (!GetVolumePathNameW(path
.NormalizePathSeparators().value().c_str(),
688 arraysize(volume_path
))) {
692 DWORD max_length
= 0;
693 if (!GetVolumeInformationW(volume_path
, NULL
, 0, NULL
, &max_length
, NULL
,
698 // Length of |path| with path separator appended.
699 size_t prefix
= path
.StripTrailingSeparators().value().size() + 1;
700 // The whole path string must be shorter than MAX_PATH. That is, it must be
701 // prefix + component_length < MAX_PATH (or equivalently, <= MAX_PATH - 1).
702 int whole_path_limit
= std::max(0, MAX_PATH
- 1 - static_cast<int>(prefix
));
703 return std::min(whole_path_limit
, static_cast<int>(max_length
));
706 // -----------------------------------------------------------------------------
710 bool MoveUnsafe(const FilePath
& from_path
, const FilePath
& to_path
) {
711 ThreadRestrictions::AssertIOAllowed();
713 // NOTE: I suspect we could support longer paths, but that would involve
714 // analyzing all our usage of files.
715 if (from_path
.value().length() >= MAX_PATH
||
716 to_path
.value().length() >= MAX_PATH
) {
719 if (MoveFileEx(from_path
.value().c_str(), to_path
.value().c_str(),
720 MOVEFILE_COPY_ALLOWED
| MOVEFILE_REPLACE_EXISTING
) != 0)
723 // Keep the last error value from MoveFileEx around in case the below
726 DWORD last_error
= ::GetLastError();
728 if (DirectoryExists(from_path
)) {
729 // MoveFileEx fails if moving directory across volumes. We will simulate
730 // the move by using Copy and Delete. Ideally we could check whether
731 // from_path and to_path are indeed in different volumes.
732 ret
= internal::CopyAndDeleteDirectory(from_path
, to_path
);
736 // Leave a clue about what went wrong so that it can be (at least) picked
737 // up by a PLOG entry.
738 ::SetLastError(last_error
);
744 bool CopyFileUnsafe(const FilePath
& from_path
, const FilePath
& to_path
) {
745 ThreadRestrictions::AssertIOAllowed();
747 // NOTE: I suspect we could support longer paths, but that would involve
748 // analyzing all our usage of files.
749 if (from_path
.value().length() >= MAX_PATH
||
750 to_path
.value().length() >= MAX_PATH
) {
754 // Unlike the posix implementation that copies the file manually and discards
755 // the ACL bits, CopyFile() copies the complete SECURITY_DESCRIPTOR and access
756 // bits, which is usually not what we want. We can't do much about the
757 // SECURITY_DESCRIPTOR but at least remove the read only bit.
758 const wchar_t* dest
= to_path
.value().c_str();
759 if (!::CopyFile(from_path
.value().c_str(), dest
, false)) {
763 DWORD attrs
= GetFileAttributes(dest
);
764 if (attrs
== INVALID_FILE_ATTRIBUTES
) {
767 if (attrs
& FILE_ATTRIBUTE_READONLY
) {
768 SetFileAttributes(dest
, attrs
& ~FILE_ATTRIBUTE_READONLY
);
773 bool CopyAndDeleteDirectory(const FilePath
& from_path
,
774 const FilePath
& to_path
) {
775 ThreadRestrictions::AssertIOAllowed();
776 if (CopyDirectory(from_path
, to_path
, true)) {
777 if (DeleteFile(from_path
, true))
780 // Like Move, this function is not transactional, so we just
781 // leave the copied bits behind if deleting from_path fails.
782 // If to_path exists previously then we have already overwritten
783 // it by now, we don't get better off by deleting the new bits.
788 } // namespace internal