Revert 270383 "Reland https://codereview.chromium.org/276493002:..."
[chromium-blink-merge.git] / base / file_util_win.cc
blobadf6608f4e3f16e32238fb46c6b2ae2cbaa5fc04
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"
7 #include <windows.h>
8 #include <psapi.h>
9 #include <shellapi.h>
10 #include <shlobj.h>
11 #include <time.h>
13 #include <algorithm>
14 #include <limits>
15 #include <string>
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"
31 namespace base {
33 namespace {
35 const DWORD kFileShareAll =
36 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
38 } // namespace
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))
44 return FilePath();
45 return FilePath(file_path);
48 bool DeleteFile(const FilePath& path, bool recursive) {
49 ThreadRestrictions::AssertIOAllowed();
51 if (path.value().length() >= MAX_PATH)
52 return false;
54 // On XP SHFileOperation will return ERROR_ACCESS_DENIED instead of
55 // ERROR_FILE_NOT_FOUND, so just shortcut this here.
56 if (path.empty())
57 return true;
59 if (!recursive) {
60 // If not recursing, then first check to see if |path| is a directory.
61 // If it is, then remove it with RemoveDirectory.
62 File::Info file_info;
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)
70 return true;
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;
84 if (!recursive)
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)
93 return false;
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)
105 return false;
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
117 // already exist.
118 if (::MoveFile(from_path.value().c_str(), to_path.value().c_str()))
119 return true;
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)) {
126 return true;
128 if (error)
129 *error = File::OSErrorToFileError(GetLastError());
130 return false;
133 bool CopyDirectory(const FilePath& from_path, const FilePath& to_path,
134 bool recursive) {
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) {
146 return false;
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())
154 return false;
155 } else {
156 real_to_path = MakeAbsoluteFilePath(real_to_path.DirName());
157 if (real_to_path.empty())
158 return false;
160 FilePath real_from_path = MakeAbsoluteFilePath(from_path);
161 if (real_from_path.empty())
162 return false;
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) {
166 return false;
169 int traverse_type = FileEnumerator::FILES;
170 if (recursive)
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();
177 return false;
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);
184 bool success = true;
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)) {
198 success = false;
199 break;
203 if (from_is_dir) {
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();
208 success = false;
210 } else if (!internal::CopyFileUnsafe(current, target_path)) {
211 DLOG(ERROR) << "CopyDirectory() couldn't create file: "
212 << target_path.value().c_str();
213 success = false;
216 current = traversal.Next();
217 if (!current.empty())
218 from_is_dir = traversal.GetInfo().IsDirectory();
221 return success;
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();
231 HANDLE dir =
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)
236 return false;
238 CloseHandle(dir);
239 return true;
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;
247 return false;
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)
254 return false;
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();
259 return true;
262 FilePath GetHomeDir() {
263 char16 result[MAX_PATH];
264 if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_PROFILE, NULL, SHGFP_TYPE_CURRENT,
265 result)) &&
266 result[0]) {
267 return FilePath(result);
270 // Fall back to the temporary directory on failure.
271 FilePath temp;
272 if (GetTempDir(&temp))
273 return temp;
275 // Last resort.
276 return FilePath(L"C:\\");
279 bool CreateTemporaryFile(FilePath* path) {
280 ThreadRestrictions::AssertIOAllowed();
282 FilePath temp_file;
284 if (!GetTempDir(path))
285 return false;
287 if (CreateTemporaryFileInDir(*path, &temp_file)) {
288 *path = temp_file;
289 return true;
292 return false;
295 // On POSIX we have semantics to create and open a temporary file
296 // atomically.
297 // TODO(jrg): is there equivalent call to use on Windows instead of
298 // going 2-step?
299 FILE* CreateAndOpenTemporaryFileInDir(const FilePath& dir, FilePath* path) {
300 ThreadRestrictions::AssertIOAllowed();
301 if (!CreateTemporaryFileInDir(dir, path)) {
302 return NULL;
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());
318 return false;
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);
326 return true;
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);
332 return true;
335 bool CreateTemporaryDirInDir(const FilePath& base_dir,
336 const FilePath::StringType& prefix,
337 FilePath* new_dir) {
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;
354 return true;
358 return false;
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))
367 return false;
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.";
383 return true;
385 DLOG(WARNING) << "CreateDirectory(" << full_path_str << "), "
386 << "conflicts with existing file.";
387 if (error) {
388 *error = File::FILE_ERROR_NOT_A_DIRECTORY;
390 return false;
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()) {
400 if (error) {
401 *error = File::FILE_ERROR_NOT_FOUND;
403 return false;
405 if (!CreateDirectoryAndGetError(parent_path, error)) {
406 DLOG(WARNING) << "Failed to create one of the parent directories.";
407 if (error) {
408 DCHECK(*error != File::FILE_OK);
410 return false;
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.
420 return true;
421 } else {
422 if (error)
423 *error = File::OSErrorToFileError(error_code);
424 DLOG(WARNING) << "Failed to create directory " << full_path_str
425 << ", last error is " << error_code << ".";
426 return false;
428 } else {
429 return true;
433 bool NormalizeFilePath(const FilePath& path, FilePath* real_path) {
434 ThreadRestrictions::AssertIOAllowed();
435 FilePath mapped_file;
436 if (!NormalizeToNativeFilePath(path, &mapped_file))
437 return false;
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.";
454 return false;
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)));
475 return true;
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.
486 return false;
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(),
498 GENERIC_READ,
499 kFileShareAll,
500 NULL,
501 OPEN_EXISTING,
502 FILE_ATTRIBUTE_NORMAL,
503 NULL));
504 if (!file_handle)
505 return false;
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(),
512 NULL,
513 PAGE_READONLY,
515 1, // Just one byte. No need to look at the data.
516 NULL));
517 if (!file_map_handle)
518 return false;
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);
523 if (!file_view)
524 return false;
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);
538 success = true;
540 ::UnmapViewOfFile(file_view);
541 return success;
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) {
547 return false;
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)) {
556 return false;
559 ULARGE_INTEGER size;
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);
570 return true;
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(),
582 GENERIC_READ,
583 FILE_SHARE_READ | FILE_SHARE_WRITE,
584 NULL,
585 OPEN_EXISTING,
586 FILE_FLAG_SEQUENTIAL_SCAN,
587 NULL));
588 if (!file)
589 return -1;
591 DWORD read;
592 if (::ReadFile(file, data, max_size, &read, NULL))
593 return read;
595 return -1;
598 int WriteFile(const FilePath& filename, const char* data, int size) {
599 ThreadRestrictions::AssertIOAllowed();
600 base::win::ScopedHandle file(CreateFile(filename.value().c_str(),
601 GENERIC_WRITE,
603 NULL,
604 CREATE_ALWAYS,
606 NULL));
607 if (!file) {
608 DLOG_GETLASTERROR(WARNING) << "CreateFile failed for path "
609 << UTF16ToUTF8(filename.value());
610 return -1;
613 DWORD written;
614 BOOL result = ::WriteFile(file, data, size, &written, NULL);
615 if (result && static_cast<int>(written) == size)
616 return written;
618 if (!result) {
619 // WriteFile failed.
620 DLOG_GETLASTERROR(WARNING) << "writing file "
621 << UTF16ToUTF8(filename.value()) << " failed";
622 } else {
623 // Didn't write all the bytes.
624 DLOG(WARNING) << "wrote" << written << " bytes to "
625 << UTF16ToUTF8(filename.value()) << " expected " << size;
627 return -1;
630 int AppendToFile(const FilePath& filename, const char* data, int size) {
631 ThreadRestrictions::AssertIOAllowed();
632 base::win::ScopedHandle file(CreateFile(filename.value().c_str(),
633 FILE_APPEND_DATA,
635 NULL,
636 OPEN_EXISTING,
638 NULL));
639 if (!file) {
640 DLOG_GETLASTERROR(WARNING) << "CreateFile failed for path "
641 << UTF16ToUTF8(filename.value());
642 return -1;
645 DWORD written;
646 BOOL result = ::WriteFile(file, data, size, &written, NULL);
647 if (result && static_cast<int>(written) == size)
648 return written;
650 if (!result) {
651 // WriteFile failed.
652 DLOG_GETLASTERROR(WARNING) << "writing file "
653 << UTF16ToUTF8(filename.value())
654 << " failed";
655 } else {
656 // Didn't write all the bytes.
657 DLOG(WARNING) << "wrote" << written << " bytes to "
658 << UTF16ToUTF8(filename.value()) << " expected " << size;
660 return -1;
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)
671 return false;
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();
677 return true;
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());
684 return ret != 0;
687 int GetMaximumPathComponentLength(const FilePath& path) {
688 ThreadRestrictions::AssertIOAllowed();
690 wchar_t volume_path[MAX_PATH];
691 if (!GetVolumePathNameW(path.NormalizePathSeparators().value().c_str(),
692 volume_path,
693 arraysize(volume_path))) {
694 return -1;
697 DWORD max_length = 0;
698 if (!GetVolumeInformationW(volume_path, NULL, 0, NULL, &max_length, NULL,
699 NULL, 0)) {
700 return -1;
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 // -----------------------------------------------------------------------------
713 namespace internal {
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) {
722 return false;
724 if (MoveFileEx(from_path.value().c_str(), to_path.value().c_str(),
725 MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING) != 0)
726 return true;
728 // Keep the last error value from MoveFileEx around in case the below
729 // fails.
730 bool ret = false;
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);
740 if (!ret) {
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);
746 return ret;
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) {
756 return false;
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)) {
765 // Copy failed.
766 return false;
768 DWORD attrs = GetFileAttributes(dest);
769 if (attrs == INVALID_FILE_ATTRIBUTES) {
770 return false;
772 if (attrs & FILE_ATTRIBUTE_READONLY) {
773 SetFileAttributes(dest, attrs & ~FILE_ATTRIBUTE_READONLY);
775 return true;
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))
783 return 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.
790 return false;
793 } // namespace internal
794 } // namespace base