Quota: Remove ifdef macros used for callback cleanup
[chromium-blink-merge.git] / base / file_util_win.cc
blobb2f69c85ae1d81db757646b16828984d08d8aaef
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 if (!recursive) {
55 // If not recursing, then first check to see if |path| is a directory.
56 // If it is, then remove it with RemoveDirectory.
57 File::Info file_info;
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)
65 return true;
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;
79 if (!recursive)
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)
88 return false;
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)
100 return false;
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
112 // already exist.
113 if (::MoveFile(from_path.value().c_str(), to_path.value().c_str()))
114 return true;
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)) {
121 return true;
123 if (error)
124 *error = File::OSErrorToFileError(GetLastError());
125 return false;
128 bool CopyDirectory(const FilePath& from_path, const FilePath& to_path,
129 bool recursive) {
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) {
141 return false;
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())
149 return false;
150 } else {
151 real_to_path = MakeAbsoluteFilePath(real_to_path.DirName());
152 if (real_to_path.empty())
153 return false;
155 FilePath real_from_path = MakeAbsoluteFilePath(from_path);
156 if (real_from_path.empty())
157 return false;
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) {
161 return false;
164 int traverse_type = FileEnumerator::FILES;
165 if (recursive)
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();
172 return false;
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);
179 bool success = true;
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)) {
193 success = false;
194 break;
198 if (from_is_dir) {
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();
203 success = false;
205 } else if (!internal::CopyFileUnsafe(current, target_path)) {
206 DLOG(ERROR) << "CopyDirectory() couldn't create file: "
207 << target_path.value().c_str();
208 success = false;
211 current = traversal.Next();
212 if (!current.empty())
213 from_is_dir = traversal.GetInfo().IsDirectory();
216 return success;
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();
226 HANDLE dir =
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)
231 return false;
233 CloseHandle(dir);
234 return true;
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;
242 return false;
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)
249 return false;
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();
254 return true;
257 bool GetShmemTempDir(bool executable, FilePath* path) {
258 return GetTempDir(path);
261 bool CreateTemporaryFile(FilePath* path) {
262 ThreadRestrictions::AssertIOAllowed();
264 FilePath temp_file;
266 if (!GetTempDir(path))
267 return false;
269 if (CreateTemporaryFileInDir(*path, &temp_file)) {
270 *path = temp_file;
271 return true;
274 return false;
277 FILE* CreateAndOpenTemporaryShmemFile(FilePath* path, bool executable) {
278 ThreadRestrictions::AssertIOAllowed();
279 return CreateAndOpenTemporaryFile(path);
282 // On POSIX we have semantics to create and open a temporary file
283 // atomically.
284 // TODO(jrg): is there equivalent call to use on Windows instead of
285 // going 2-step?
286 FILE* CreateAndOpenTemporaryFileInDir(const FilePath& dir, FilePath* path) {
287 ThreadRestrictions::AssertIOAllowed();
288 if (!CreateTemporaryFileInDir(dir, path)) {
289 return NULL;
291 // Open file in binary mode, to avoid problems with fwrite. On Windows
292 // it replaces \n's with \r\n's, which may surprise you.
293 // Reference: http://msdn.microsoft.com/en-us/library/h9t88zwz(VS.71).aspx
294 return OpenFile(*path, "wb+");
297 bool CreateTemporaryFileInDir(const FilePath& dir, FilePath* temp_file) {
298 ThreadRestrictions::AssertIOAllowed();
300 wchar_t temp_name[MAX_PATH + 1];
302 if (!GetTempFileName(dir.value().c_str(), L"", 0, temp_name)) {
303 DPLOG(WARNING) << "Failed to get temporary file name in "
304 << UTF16ToUTF8(dir.value());
305 return false;
308 wchar_t long_temp_name[MAX_PATH + 1];
309 DWORD long_name_len = GetLongPathName(temp_name, long_temp_name, MAX_PATH);
310 if (long_name_len > MAX_PATH || long_name_len == 0) {
311 // GetLongPathName() failed, but we still have a temporary file.
312 *temp_file = FilePath(temp_name);
313 return true;
316 FilePath::StringType long_temp_name_str;
317 long_temp_name_str.assign(long_temp_name, long_name_len);
318 *temp_file = FilePath(long_temp_name_str);
319 return true;
322 bool CreateTemporaryDirInDir(const FilePath& base_dir,
323 const FilePath::StringType& prefix,
324 FilePath* new_dir) {
325 ThreadRestrictions::AssertIOAllowed();
327 FilePath path_to_create;
329 for (int count = 0; count < 50; ++count) {
330 // Try create a new temporary directory with random generated name. If
331 // the one exists, keep trying another path name until we reach some limit.
332 string16 new_dir_name;
333 new_dir_name.assign(prefix);
334 new_dir_name.append(IntToString16(GetCurrentProcId()));
335 new_dir_name.push_back('_');
336 new_dir_name.append(IntToString16(RandInt(0, kint16max)));
338 path_to_create = base_dir.Append(new_dir_name);
339 if (::CreateDirectory(path_to_create.value().c_str(), NULL)) {
340 *new_dir = path_to_create;
341 return true;
345 return false;
348 bool CreateNewTempDirectory(const FilePath::StringType& prefix,
349 FilePath* new_temp_path) {
350 ThreadRestrictions::AssertIOAllowed();
352 FilePath system_temp_dir;
353 if (!GetTempDir(&system_temp_dir))
354 return false;
356 return CreateTemporaryDirInDir(system_temp_dir, prefix, new_temp_path);
359 bool CreateDirectoryAndGetError(const FilePath& full_path,
360 File::Error* error) {
361 ThreadRestrictions::AssertIOAllowed();
363 // If the path exists, we've succeeded if it's a directory, failed otherwise.
364 const wchar_t* full_path_str = full_path.value().c_str();
365 DWORD fileattr = ::GetFileAttributes(full_path_str);
366 if (fileattr != INVALID_FILE_ATTRIBUTES) {
367 if ((fileattr & FILE_ATTRIBUTE_DIRECTORY) != 0) {
368 DVLOG(1) << "CreateDirectory(" << full_path_str << "), "
369 << "directory already exists.";
370 return true;
372 DLOG(WARNING) << "CreateDirectory(" << full_path_str << "), "
373 << "conflicts with existing file.";
374 if (error) {
375 *error = File::FILE_ERROR_NOT_A_DIRECTORY;
377 return false;
380 // Invariant: Path does not exist as file or directory.
382 // Attempt to create the parent recursively. This will immediately return
383 // true if it already exists, otherwise will create all required parent
384 // directories starting with the highest-level missing parent.
385 FilePath parent_path(full_path.DirName());
386 if (parent_path.value() == full_path.value()) {
387 if (error) {
388 *error = File::FILE_ERROR_NOT_FOUND;
390 return false;
392 if (!CreateDirectoryAndGetError(parent_path, error)) {
393 DLOG(WARNING) << "Failed to create one of the parent directories.";
394 if (error) {
395 DCHECK(*error != File::FILE_OK);
397 return false;
400 if (!::CreateDirectory(full_path_str, NULL)) {
401 DWORD error_code = ::GetLastError();
402 if (error_code == ERROR_ALREADY_EXISTS && DirectoryExists(full_path)) {
403 // This error code ERROR_ALREADY_EXISTS doesn't indicate whether we
404 // were racing with someone creating the same directory, or a file
405 // with the same path. If DirectoryExists() returns true, we lost the
406 // race to create the same directory.
407 return true;
408 } else {
409 if (error)
410 *error = File::OSErrorToFileError(error_code);
411 DLOG(WARNING) << "Failed to create directory " << full_path_str
412 << ", last error is " << error_code << ".";
413 return false;
415 } else {
416 return true;
420 bool NormalizeFilePath(const FilePath& path, FilePath* real_path) {
421 ThreadRestrictions::AssertIOAllowed();
422 FilePath mapped_file;
423 if (!NormalizeToNativeFilePath(path, &mapped_file))
424 return false;
425 // NormalizeToNativeFilePath() will return a path that starts with
426 // "\Device\Harddisk...". Helper DevicePathToDriveLetterPath()
427 // will find a drive letter which maps to the path's device, so
428 // that we return a path starting with a drive letter.
429 return DevicePathToDriveLetterPath(mapped_file, real_path);
432 bool DevicePathToDriveLetterPath(const FilePath& nt_device_path,
433 FilePath* out_drive_letter_path) {
434 ThreadRestrictions::AssertIOAllowed();
436 // Get the mapping of drive letters to device paths.
437 const int kDriveMappingSize = 1024;
438 wchar_t drive_mapping[kDriveMappingSize] = {'\0'};
439 if (!::GetLogicalDriveStrings(kDriveMappingSize - 1, drive_mapping)) {
440 DLOG(ERROR) << "Failed to get drive mapping.";
441 return false;
444 // The drive mapping is a sequence of null terminated strings.
445 // The last string is empty.
446 wchar_t* drive_map_ptr = drive_mapping;
447 wchar_t device_path_as_string[MAX_PATH];
448 wchar_t drive[] = L" :";
450 // For each string in the drive mapping, get the junction that links
451 // to it. If that junction is a prefix of |device_path|, then we
452 // know that |drive| is the real path prefix.
453 while (*drive_map_ptr) {
454 drive[0] = drive_map_ptr[0]; // Copy the drive letter.
456 if (QueryDosDevice(drive, device_path_as_string, MAX_PATH)) {
457 FilePath device_path(device_path_as_string);
458 if (device_path == nt_device_path ||
459 device_path.IsParent(nt_device_path)) {
460 *out_drive_letter_path = FilePath(drive +
461 nt_device_path.value().substr(wcslen(device_path_as_string)));
462 return true;
465 // Move to the next drive letter string, which starts one
466 // increment after the '\0' that terminates the current string.
467 while (*drive_map_ptr++);
470 // No drive matched. The path does not start with a device junction
471 // that is mounted as a drive letter. This means there is no drive
472 // letter path to the volume that holds |device_path|, so fail.
473 return false;
476 bool NormalizeToNativeFilePath(const FilePath& path, FilePath* nt_path) {
477 ThreadRestrictions::AssertIOAllowed();
478 // In Vista, GetFinalPathNameByHandle() would give us the real path
479 // from a file handle. If we ever deprecate XP, consider changing the
480 // code below to a call to GetFinalPathNameByHandle(). The method this
481 // function uses is explained in the following msdn article:
482 // http://msdn.microsoft.com/en-us/library/aa366789(VS.85).aspx
483 base::win::ScopedHandle file_handle(
484 ::CreateFile(path.value().c_str(),
485 GENERIC_READ,
486 kFileShareAll,
487 NULL,
488 OPEN_EXISTING,
489 FILE_ATTRIBUTE_NORMAL,
490 NULL));
491 if (!file_handle)
492 return false;
494 // Create a file mapping object. Can't easily use MemoryMappedFile, because
495 // we only map the first byte, and need direct access to the handle. You can
496 // not map an empty file, this call fails in that case.
497 base::win::ScopedHandle file_map_handle(
498 ::CreateFileMapping(file_handle.Get(),
499 NULL,
500 PAGE_READONLY,
502 1, // Just one byte. No need to look at the data.
503 NULL));
504 if (!file_map_handle)
505 return false;
507 // Use a view of the file to get the path to the file.
508 void* file_view = MapViewOfFile(file_map_handle.Get(),
509 FILE_MAP_READ, 0, 0, 1);
510 if (!file_view)
511 return false;
513 // The expansion of |path| into a full path may make it longer.
514 // GetMappedFileName() will fail if the result is longer than MAX_PATH.
515 // Pad a bit to be safe. If kMaxPathLength is ever changed to be less
516 // than MAX_PATH, it would be nessisary to test that GetMappedFileName()
517 // not return kMaxPathLength. This would mean that only part of the
518 // path fit in |mapped_file_path|.
519 const int kMaxPathLength = MAX_PATH + 10;
520 wchar_t mapped_file_path[kMaxPathLength];
521 bool success = false;
522 HANDLE cp = GetCurrentProcess();
523 if (::GetMappedFileNameW(cp, file_view, mapped_file_path, kMaxPathLength)) {
524 *nt_path = FilePath(mapped_file_path);
525 success = true;
527 ::UnmapViewOfFile(file_view);
528 return success;
531 // TODO(rkc): Work out if we want to handle NTFS junctions here or not, handle
532 // them if we do decide to.
533 bool IsLink(const FilePath& file_path) {
534 return false;
537 bool GetFileInfo(const FilePath& file_path, File::Info* results) {
538 ThreadRestrictions::AssertIOAllowed();
540 WIN32_FILE_ATTRIBUTE_DATA attr;
541 if (!GetFileAttributesEx(file_path.value().c_str(),
542 GetFileExInfoStandard, &attr)) {
543 return false;
546 ULARGE_INTEGER size;
547 size.HighPart = attr.nFileSizeHigh;
548 size.LowPart = attr.nFileSizeLow;
549 results->size = size.QuadPart;
551 results->is_directory =
552 (attr.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
553 results->last_modified = Time::FromFileTime(attr.ftLastWriteTime);
554 results->last_accessed = Time::FromFileTime(attr.ftLastAccessTime);
555 results->creation_time = Time::FromFileTime(attr.ftCreationTime);
557 return true;
560 FILE* OpenFile(const FilePath& filename, const char* mode) {
561 ThreadRestrictions::AssertIOAllowed();
562 std::wstring w_mode = ASCIIToWide(std::string(mode));
563 return _wfsopen(filename.value().c_str(), w_mode.c_str(), _SH_DENYNO);
566 int ReadFile(const FilePath& filename, char* data, int size) {
567 ThreadRestrictions::AssertIOAllowed();
568 base::win::ScopedHandle file(CreateFile(filename.value().c_str(),
569 GENERIC_READ,
570 FILE_SHARE_READ | FILE_SHARE_WRITE,
571 NULL,
572 OPEN_EXISTING,
573 FILE_FLAG_SEQUENTIAL_SCAN,
574 NULL));
575 if (!file)
576 return -1;
578 DWORD read;
579 if (::ReadFile(file, data, size, &read, NULL) &&
580 static_cast<int>(read) == size)
581 return read;
582 return -1;
585 } // namespace base
587 // -----------------------------------------------------------------------------
589 namespace file_util {
591 using base::DirectoryExists;
592 using base::FilePath;
593 using base::kFileShareAll;
595 FILE* OpenFile(const std::string& filename, const char* mode) {
596 base::ThreadRestrictions::AssertIOAllowed();
597 return _fsopen(filename.c_str(), mode, _SH_DENYNO);
600 int WriteFile(const FilePath& filename, const char* data, int size) {
601 base::ThreadRestrictions::AssertIOAllowed();
602 base::win::ScopedHandle file(CreateFile(filename.value().c_str(),
603 GENERIC_WRITE,
605 NULL,
606 CREATE_ALWAYS,
608 NULL));
609 if (!file) {
610 DLOG_GETLASTERROR(WARNING) << "CreateFile failed for path "
611 << filename.value();
612 return -1;
615 DWORD written;
616 BOOL result = ::WriteFile(file, data, size, &written, NULL);
617 if (result && static_cast<int>(written) == size)
618 return written;
620 if (!result) {
621 // WriteFile failed.
622 DLOG_GETLASTERROR(WARNING) << "writing file " << filename.value()
623 << " failed";
624 } else {
625 // Didn't write all the bytes.
626 DLOG(WARNING) << "wrote" << written << " bytes to "
627 << filename.value() << " expected " << size;
629 return -1;
632 int AppendToFile(const FilePath& filename, const char* data, int size) {
633 base::ThreadRestrictions::AssertIOAllowed();
634 base::win::ScopedHandle file(CreateFile(filename.value().c_str(),
635 FILE_APPEND_DATA,
637 NULL,
638 OPEN_EXISTING,
640 NULL));
641 if (!file) {
642 DLOG_GETLASTERROR(WARNING) << "CreateFile failed for path "
643 << filename.value();
644 return -1;
647 DWORD written;
648 BOOL result = ::WriteFile(file, data, size, &written, NULL);
649 if (result && static_cast<int>(written) == size)
650 return written;
652 if (!result) {
653 // WriteFile failed.
654 DLOG_GETLASTERROR(WARNING) << "writing file " << filename.value()
655 << " failed";
656 } else {
657 // Didn't write all the bytes.
658 DLOG(WARNING) << "wrote" << written << " bytes to "
659 << filename.value() << " expected " << size;
661 return -1;
664 // Gets the current working directory for the process.
665 bool GetCurrentDirectory(FilePath* dir) {
666 base::ThreadRestrictions::AssertIOAllowed();
668 wchar_t system_buffer[MAX_PATH];
669 system_buffer[0] = 0;
670 DWORD len = ::GetCurrentDirectory(MAX_PATH, system_buffer);
671 if (len == 0 || len > MAX_PATH)
672 return false;
673 // TODO(evanm): the old behavior of this function was to always strip the
674 // trailing slash. We duplicate this here, but it shouldn't be necessary
675 // when everyone is using the appropriate FilePath APIs.
676 std::wstring dir_str(system_buffer);
677 *dir = FilePath(dir_str).StripTrailingSeparators();
678 return true;
681 // Sets the current working directory for the process.
682 bool SetCurrentDirectory(const FilePath& directory) {
683 base::ThreadRestrictions::AssertIOAllowed();
684 BOOL ret = ::SetCurrentDirectory(directory.value().c_str());
685 return ret != 0;
688 int GetMaximumPathComponentLength(const FilePath& path) {
689 base::ThreadRestrictions::AssertIOAllowed();
691 wchar_t volume_path[MAX_PATH];
692 if (!GetVolumePathNameW(path.NormalizePathSeparators().value().c_str(),
693 volume_path,
694 arraysize(volume_path))) {
695 return -1;
698 DWORD max_length = 0;
699 if (!GetVolumeInformationW(volume_path, NULL, 0, NULL, &max_length, NULL,
700 NULL, 0)) {
701 return -1;
704 // Length of |path| with path separator appended.
705 size_t prefix = path.StripTrailingSeparators().value().size() + 1;
706 // The whole path string must be shorter than MAX_PATH. That is, it must be
707 // prefix + component_length < MAX_PATH (or equivalently, <= MAX_PATH - 1).
708 int whole_path_limit = std::max(0, MAX_PATH - 1 - static_cast<int>(prefix));
709 return std::min(whole_path_limit, static_cast<int>(max_length));
712 } // namespace file_util
714 namespace base {
715 namespace internal {
717 bool MoveUnsafe(const FilePath& from_path, const FilePath& to_path) {
718 ThreadRestrictions::AssertIOAllowed();
720 // NOTE: I suspect we could support longer paths, but that would involve
721 // analyzing all our usage of files.
722 if (from_path.value().length() >= MAX_PATH ||
723 to_path.value().length() >= MAX_PATH) {
724 return false;
726 if (MoveFileEx(from_path.value().c_str(), to_path.value().c_str(),
727 MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING) != 0)
728 return true;
730 // Keep the last error value from MoveFileEx around in case the below
731 // fails.
732 bool ret = false;
733 DWORD last_error = ::GetLastError();
735 if (DirectoryExists(from_path)) {
736 // MoveFileEx fails if moving directory across volumes. We will simulate
737 // the move by using Copy and Delete. Ideally we could check whether
738 // from_path and to_path are indeed in different volumes.
739 ret = internal::CopyAndDeleteDirectory(from_path, to_path);
742 if (!ret) {
743 // Leave a clue about what went wrong so that it can be (at least) picked
744 // up by a PLOG entry.
745 ::SetLastError(last_error);
748 return ret;
751 bool CopyFileUnsafe(const FilePath& from_path, const FilePath& to_path) {
752 ThreadRestrictions::AssertIOAllowed();
754 // NOTE: I suspect we could support longer paths, but that would involve
755 // analyzing all our usage of files.
756 if (from_path.value().length() >= MAX_PATH ||
757 to_path.value().length() >= MAX_PATH) {
758 return false;
761 // Unlike the posix implementation that copies the file manually and discards
762 // the ACL bits, CopyFile() copies the complete SECURITY_DESCRIPTOR and access
763 // bits, which is usually not what we want. We can't do much about the
764 // SECURITY_DESCRIPTOR but at least remove the read only bit.
765 const wchar_t* dest = to_path.value().c_str();
766 if (!::CopyFile(from_path.value().c_str(), dest, false)) {
767 // Copy failed.
768 return false;
770 DWORD attrs = GetFileAttributes(dest);
771 if (attrs == INVALID_FILE_ATTRIBUTES) {
772 return false;
774 if (attrs & FILE_ATTRIBUTE_READONLY) {
775 SetFileAttributes(dest, attrs & ~FILE_ATTRIBUTE_READONLY);
777 return true;
780 bool CopyAndDeleteDirectory(const FilePath& from_path,
781 const FilePath& to_path) {
782 ThreadRestrictions::AssertIOAllowed();
783 if (CopyDirectory(from_path, to_path, true)) {
784 if (DeleteFile(from_path, true))
785 return true;
787 // Like Move, this function is not transactional, so we just
788 // leave the copied bits behind if deleting from_path fails.
789 // If to_path exists previously then we have already overwritten
790 // it by now, we don't get better off by deleting the new bits.
792 return false;
795 } // namespace internal
796 } // namespace base