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 bool GetShmemTempDir(bool executable
, FilePath
* path
) {
258 return GetTempDir(path
);
261 FilePath
GetHomeDir() {
262 char16 result
[MAX_PATH
];
263 if (SUCCEEDED(SHGetFolderPath(NULL
, CSIDL_PROFILE
, NULL
, SHGFP_TYPE_CURRENT
,
266 return FilePath(result
);
269 // Fall back to the temporary directory on failure.
271 if (GetTempDir(&temp
))
275 return FilePath(L
"C:\\");
278 bool CreateTemporaryFile(FilePath
* path
) {
279 ThreadRestrictions::AssertIOAllowed();
283 if (!GetTempDir(path
))
286 if (CreateTemporaryFileInDir(*path
, &temp_file
)) {
294 FILE* CreateAndOpenTemporaryShmemFile(FilePath
* path
, bool executable
) {
295 ThreadRestrictions::AssertIOAllowed();
296 return CreateAndOpenTemporaryFile(path
);
299 // On POSIX we have semantics to create and open a temporary file
301 // TODO(jrg): is there equivalent call to use on Windows instead of
303 FILE* CreateAndOpenTemporaryFileInDir(const FilePath
& dir
, FilePath
* path
) {
304 ThreadRestrictions::AssertIOAllowed();
305 if (!CreateTemporaryFileInDir(dir
, path
)) {
308 // Open file in binary mode, to avoid problems with fwrite. On Windows
309 // it replaces \n's with \r\n's, which may surprise you.
310 // Reference: http://msdn.microsoft.com/en-us/library/h9t88zwz(VS.71).aspx
311 return OpenFile(*path
, "wb+");
314 bool CreateTemporaryFileInDir(const FilePath
& dir
, FilePath
* temp_file
) {
315 ThreadRestrictions::AssertIOAllowed();
317 wchar_t temp_name
[MAX_PATH
+ 1];
319 if (!GetTempFileName(dir
.value().c_str(), L
"", 0, temp_name
)) {
320 DPLOG(WARNING
) << "Failed to get temporary file name in "
321 << UTF16ToUTF8(dir
.value());
325 wchar_t long_temp_name
[MAX_PATH
+ 1];
326 DWORD long_name_len
= GetLongPathName(temp_name
, long_temp_name
, MAX_PATH
);
327 if (long_name_len
> MAX_PATH
|| long_name_len
== 0) {
328 // GetLongPathName() failed, but we still have a temporary file.
329 *temp_file
= FilePath(temp_name
);
333 FilePath::StringType long_temp_name_str
;
334 long_temp_name_str
.assign(long_temp_name
, long_name_len
);
335 *temp_file
= FilePath(long_temp_name_str
);
339 bool CreateTemporaryDirInDir(const FilePath
& base_dir
,
340 const FilePath::StringType
& prefix
,
342 ThreadRestrictions::AssertIOAllowed();
344 FilePath path_to_create
;
346 for (int count
= 0; count
< 50; ++count
) {
347 // Try create a new temporary directory with random generated name. If
348 // the one exists, keep trying another path name until we reach some limit.
349 string16 new_dir_name
;
350 new_dir_name
.assign(prefix
);
351 new_dir_name
.append(IntToString16(GetCurrentProcId()));
352 new_dir_name
.push_back('_');
353 new_dir_name
.append(IntToString16(RandInt(0, kint16max
)));
355 path_to_create
= base_dir
.Append(new_dir_name
);
356 if (::CreateDirectory(path_to_create
.value().c_str(), NULL
)) {
357 *new_dir
= path_to_create
;
365 bool CreateNewTempDirectory(const FilePath::StringType
& prefix
,
366 FilePath
* new_temp_path
) {
367 ThreadRestrictions::AssertIOAllowed();
369 FilePath system_temp_dir
;
370 if (!GetTempDir(&system_temp_dir
))
373 return CreateTemporaryDirInDir(system_temp_dir
, prefix
, new_temp_path
);
376 bool CreateDirectoryAndGetError(const FilePath
& full_path
,
377 File::Error
* error
) {
378 ThreadRestrictions::AssertIOAllowed();
380 // If the path exists, we've succeeded if it's a directory, failed otherwise.
381 const wchar_t* full_path_str
= full_path
.value().c_str();
382 DWORD fileattr
= ::GetFileAttributes(full_path_str
);
383 if (fileattr
!= INVALID_FILE_ATTRIBUTES
) {
384 if ((fileattr
& FILE_ATTRIBUTE_DIRECTORY
) != 0) {
385 DVLOG(1) << "CreateDirectory(" << full_path_str
<< "), "
386 << "directory already exists.";
389 DLOG(WARNING
) << "CreateDirectory(" << full_path_str
<< "), "
390 << "conflicts with existing file.";
392 *error
= File::FILE_ERROR_NOT_A_DIRECTORY
;
397 // Invariant: Path does not exist as file or directory.
399 // Attempt to create the parent recursively. This will immediately return
400 // true if it already exists, otherwise will create all required parent
401 // directories starting with the highest-level missing parent.
402 FilePath
parent_path(full_path
.DirName());
403 if (parent_path
.value() == full_path
.value()) {
405 *error
= File::FILE_ERROR_NOT_FOUND
;
409 if (!CreateDirectoryAndGetError(parent_path
, error
)) {
410 DLOG(WARNING
) << "Failed to create one of the parent directories.";
412 DCHECK(*error
!= File::FILE_OK
);
417 if (!::CreateDirectory(full_path_str
, NULL
)) {
418 DWORD error_code
= ::GetLastError();
419 if (error_code
== ERROR_ALREADY_EXISTS
&& DirectoryExists(full_path
)) {
420 // This error code ERROR_ALREADY_EXISTS doesn't indicate whether we
421 // were racing with someone creating the same directory, or a file
422 // with the same path. If DirectoryExists() returns true, we lost the
423 // race to create the same directory.
427 *error
= File::OSErrorToFileError(error_code
);
428 DLOG(WARNING
) << "Failed to create directory " << full_path_str
429 << ", last error is " << error_code
<< ".";
437 bool NormalizeFilePath(const FilePath
& path
, FilePath
* real_path
) {
438 ThreadRestrictions::AssertIOAllowed();
439 FilePath mapped_file
;
440 if (!NormalizeToNativeFilePath(path
, &mapped_file
))
442 // NormalizeToNativeFilePath() will return a path that starts with
443 // "\Device\Harddisk...". Helper DevicePathToDriveLetterPath()
444 // will find a drive letter which maps to the path's device, so
445 // that we return a path starting with a drive letter.
446 return DevicePathToDriveLetterPath(mapped_file
, real_path
);
449 bool DevicePathToDriveLetterPath(const FilePath
& nt_device_path
,
450 FilePath
* out_drive_letter_path
) {
451 ThreadRestrictions::AssertIOAllowed();
453 // Get the mapping of drive letters to device paths.
454 const int kDriveMappingSize
= 1024;
455 wchar_t drive_mapping
[kDriveMappingSize
] = {'\0'};
456 if (!::GetLogicalDriveStrings(kDriveMappingSize
- 1, drive_mapping
)) {
457 DLOG(ERROR
) << "Failed to get drive mapping.";
461 // The drive mapping is a sequence of null terminated strings.
462 // The last string is empty.
463 wchar_t* drive_map_ptr
= drive_mapping
;
464 wchar_t device_path_as_string
[MAX_PATH
];
465 wchar_t drive
[] = L
" :";
467 // For each string in the drive mapping, get the junction that links
468 // to it. If that junction is a prefix of |device_path|, then we
469 // know that |drive| is the real path prefix.
470 while (*drive_map_ptr
) {
471 drive
[0] = drive_map_ptr
[0]; // Copy the drive letter.
473 if (QueryDosDevice(drive
, device_path_as_string
, MAX_PATH
)) {
474 FilePath
device_path(device_path_as_string
);
475 if (device_path
== nt_device_path
||
476 device_path
.IsParent(nt_device_path
)) {
477 *out_drive_letter_path
= FilePath(drive
+
478 nt_device_path
.value().substr(wcslen(device_path_as_string
)));
482 // Move to the next drive letter string, which starts one
483 // increment after the '\0' that terminates the current string.
484 while (*drive_map_ptr
++);
487 // No drive matched. The path does not start with a device junction
488 // that is mounted as a drive letter. This means there is no drive
489 // letter path to the volume that holds |device_path|, so fail.
493 bool NormalizeToNativeFilePath(const FilePath
& path
, FilePath
* nt_path
) {
494 ThreadRestrictions::AssertIOAllowed();
495 // In Vista, GetFinalPathNameByHandle() would give us the real path
496 // from a file handle. If we ever deprecate XP, consider changing the
497 // code below to a call to GetFinalPathNameByHandle(). The method this
498 // function uses is explained in the following msdn article:
499 // http://msdn.microsoft.com/en-us/library/aa366789(VS.85).aspx
500 base::win::ScopedHandle
file_handle(
501 ::CreateFile(path
.value().c_str(),
506 FILE_ATTRIBUTE_NORMAL
,
511 // Create a file mapping object. Can't easily use MemoryMappedFile, because
512 // we only map the first byte, and need direct access to the handle. You can
513 // not map an empty file, this call fails in that case.
514 base::win::ScopedHandle
file_map_handle(
515 ::CreateFileMapping(file_handle
.Get(),
519 1, // Just one byte. No need to look at the data.
521 if (!file_map_handle
)
524 // Use a view of the file to get the path to the file.
525 void* file_view
= MapViewOfFile(file_map_handle
.Get(),
526 FILE_MAP_READ
, 0, 0, 1);
530 // The expansion of |path| into a full path may make it longer.
531 // GetMappedFileName() will fail if the result is longer than MAX_PATH.
532 // Pad a bit to be safe. If kMaxPathLength is ever changed to be less
533 // than MAX_PATH, it would be nessisary to test that GetMappedFileName()
534 // not return kMaxPathLength. This would mean that only part of the
535 // path fit in |mapped_file_path|.
536 const int kMaxPathLength
= MAX_PATH
+ 10;
537 wchar_t mapped_file_path
[kMaxPathLength
];
538 bool success
= false;
539 HANDLE cp
= GetCurrentProcess();
540 if (::GetMappedFileNameW(cp
, file_view
, mapped_file_path
, kMaxPathLength
)) {
541 *nt_path
= FilePath(mapped_file_path
);
544 ::UnmapViewOfFile(file_view
);
548 // TODO(rkc): Work out if we want to handle NTFS junctions here or not, handle
549 // them if we do decide to.
550 bool IsLink(const FilePath
& file_path
) {
554 bool GetFileInfo(const FilePath
& file_path
, File::Info
* results
) {
555 ThreadRestrictions::AssertIOAllowed();
557 WIN32_FILE_ATTRIBUTE_DATA attr
;
558 if (!GetFileAttributesEx(file_path
.value().c_str(),
559 GetFileExInfoStandard
, &attr
)) {
564 size
.HighPart
= attr
.nFileSizeHigh
;
565 size
.LowPart
= attr
.nFileSizeLow
;
566 results
->size
= size
.QuadPart
;
568 results
->is_directory
=
569 (attr
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
) != 0;
570 results
->last_modified
= Time::FromFileTime(attr
.ftLastWriteTime
);
571 results
->last_accessed
= Time::FromFileTime(attr
.ftLastAccessTime
);
572 results
->creation_time
= Time::FromFileTime(attr
.ftCreationTime
);
577 FILE* OpenFile(const FilePath
& filename
, const char* mode
) {
578 ThreadRestrictions::AssertIOAllowed();
579 std::wstring w_mode
= ASCIIToWide(std::string(mode
));
580 return _wfsopen(filename
.value().c_str(), w_mode
.c_str(), _SH_DENYNO
);
583 int ReadFile(const FilePath
& filename
, char* data
, int size
) {
584 ThreadRestrictions::AssertIOAllowed();
585 base::win::ScopedHandle
file(CreateFile(filename
.value().c_str(),
587 FILE_SHARE_READ
| FILE_SHARE_WRITE
,
590 FILE_FLAG_SEQUENTIAL_SCAN
,
596 if (::ReadFile(file
, data
, size
, &read
, NULL
) &&
597 static_cast<int>(read
) == size
)
604 // -----------------------------------------------------------------------------
606 namespace file_util
{
608 using base::DirectoryExists
;
609 using base::FilePath
;
610 using base::kFileShareAll
;
612 FILE* OpenFile(const std::string
& filename
, const char* mode
) {
613 base::ThreadRestrictions::AssertIOAllowed();
614 return _fsopen(filename
.c_str(), mode
, _SH_DENYNO
);
617 int WriteFile(const FilePath
& filename
, const char* data
, int size
) {
618 base::ThreadRestrictions::AssertIOAllowed();
619 base::win::ScopedHandle
file(CreateFile(filename
.value().c_str(),
627 DLOG_GETLASTERROR(WARNING
) << "CreateFile failed for path "
633 BOOL result
= ::WriteFile(file
, data
, size
, &written
, NULL
);
634 if (result
&& static_cast<int>(written
) == size
)
639 DLOG_GETLASTERROR(WARNING
) << "writing file " << filename
.value()
642 // Didn't write all the bytes.
643 DLOG(WARNING
) << "wrote" << written
<< " bytes to "
644 << filename
.value() << " expected " << size
;
649 int AppendToFile(const FilePath
& filename
, const char* data
, int size
) {
650 base::ThreadRestrictions::AssertIOAllowed();
651 base::win::ScopedHandle
file(CreateFile(filename
.value().c_str(),
659 DLOG_GETLASTERROR(WARNING
) << "CreateFile failed for path "
665 BOOL result
= ::WriteFile(file
, data
, size
, &written
, NULL
);
666 if (result
&& static_cast<int>(written
) == size
)
671 DLOG_GETLASTERROR(WARNING
) << "writing file " << filename
.value()
674 // Didn't write all the bytes.
675 DLOG(WARNING
) << "wrote" << written
<< " bytes to "
676 << filename
.value() << " expected " << size
;
681 // Gets the current working directory for the process.
682 bool GetCurrentDirectory(FilePath
* dir
) {
683 base::ThreadRestrictions::AssertIOAllowed();
685 wchar_t system_buffer
[MAX_PATH
];
686 system_buffer
[0] = 0;
687 DWORD len
= ::GetCurrentDirectory(MAX_PATH
, system_buffer
);
688 if (len
== 0 || len
> MAX_PATH
)
690 // TODO(evanm): the old behavior of this function was to always strip the
691 // trailing slash. We duplicate this here, but it shouldn't be necessary
692 // when everyone is using the appropriate FilePath APIs.
693 std::wstring
dir_str(system_buffer
);
694 *dir
= FilePath(dir_str
).StripTrailingSeparators();
698 // Sets the current working directory for the process.
699 bool SetCurrentDirectory(const FilePath
& directory
) {
700 base::ThreadRestrictions::AssertIOAllowed();
701 BOOL ret
= ::SetCurrentDirectory(directory
.value().c_str());
705 int GetMaximumPathComponentLength(const FilePath
& path
) {
706 base::ThreadRestrictions::AssertIOAllowed();
708 wchar_t volume_path
[MAX_PATH
];
709 if (!GetVolumePathNameW(path
.NormalizePathSeparators().value().c_str(),
711 arraysize(volume_path
))) {
715 DWORD max_length
= 0;
716 if (!GetVolumeInformationW(volume_path
, NULL
, 0, NULL
, &max_length
, NULL
,
721 // Length of |path| with path separator appended.
722 size_t prefix
= path
.StripTrailingSeparators().value().size() + 1;
723 // The whole path string must be shorter than MAX_PATH. That is, it must be
724 // prefix + component_length < MAX_PATH (or equivalently, <= MAX_PATH - 1).
725 int whole_path_limit
= std::max(0, MAX_PATH
- 1 - static_cast<int>(prefix
));
726 return std::min(whole_path_limit
, static_cast<int>(max_length
));
729 } // namespace file_util
734 bool MoveUnsafe(const FilePath
& from_path
, const FilePath
& to_path
) {
735 ThreadRestrictions::AssertIOAllowed();
737 // NOTE: I suspect we could support longer paths, but that would involve
738 // analyzing all our usage of files.
739 if (from_path
.value().length() >= MAX_PATH
||
740 to_path
.value().length() >= MAX_PATH
) {
743 if (MoveFileEx(from_path
.value().c_str(), to_path
.value().c_str(),
744 MOVEFILE_COPY_ALLOWED
| MOVEFILE_REPLACE_EXISTING
) != 0)
747 // Keep the last error value from MoveFileEx around in case the below
750 DWORD last_error
= ::GetLastError();
752 if (DirectoryExists(from_path
)) {
753 // MoveFileEx fails if moving directory across volumes. We will simulate
754 // the move by using Copy and Delete. Ideally we could check whether
755 // from_path and to_path are indeed in different volumes.
756 ret
= internal::CopyAndDeleteDirectory(from_path
, to_path
);
760 // Leave a clue about what went wrong so that it can be (at least) picked
761 // up by a PLOG entry.
762 ::SetLastError(last_error
);
768 bool CopyFileUnsafe(const FilePath
& from_path
, const FilePath
& to_path
) {
769 ThreadRestrictions::AssertIOAllowed();
771 // NOTE: I suspect we could support longer paths, but that would involve
772 // analyzing all our usage of files.
773 if (from_path
.value().length() >= MAX_PATH
||
774 to_path
.value().length() >= MAX_PATH
) {
778 // Unlike the posix implementation that copies the file manually and discards
779 // the ACL bits, CopyFile() copies the complete SECURITY_DESCRIPTOR and access
780 // bits, which is usually not what we want. We can't do much about the
781 // SECURITY_DESCRIPTOR but at least remove the read only bit.
782 const wchar_t* dest
= to_path
.value().c_str();
783 if (!::CopyFile(from_path
.value().c_str(), dest
, false)) {
787 DWORD attrs
= GetFileAttributes(dest
);
788 if (attrs
== INVALID_FILE_ATTRIBUTES
) {
791 if (attrs
& FILE_ATTRIBUTE_READONLY
) {
792 SetFileAttributes(dest
, attrs
& ~FILE_ATTRIBUTE_READONLY
);
797 bool CopyAndDeleteDirectory(const FilePath
& from_path
,
798 const FilePath
& to_path
) {
799 ThreadRestrictions::AssertIOAllowed();
800 if (CopyDirectory(from_path
, to_path
, true)) {
801 if (DeleteFile(from_path
, true))
804 // Like Move, this function is not transactional, so we just
805 // leave the copied bits behind if deleting from_path fails.
806 // If to_path exists previously then we have already overwritten
807 // it by now, we don't get better off by deleting the new bits.
812 } // namespace internal