Update V8 to version 4.7.58.
[chromium-blink-merge.git] / base / files / file_util_win.cc
blob57dbb809c67fb67175ac00eb636650faccea645a
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/files/file_util.h"
7 #include <windows.h>
8 #include <io.h>
9 #include <psapi.h>
10 #include <shellapi.h>
11 #include <shlobj.h>
12 #include <time.h>
14 #include <algorithm>
15 #include <limits>
16 #include <string>
18 #include "base/files/file_enumerator.h"
19 #include "base/files/file_path.h"
20 #include "base/logging.h"
21 #include "base/metrics/histogram.h"
22 #include "base/process/process_handle.h"
23 #include "base/rand_util.h"
24 #include "base/strings/string_number_conversions.h"
25 #include "base/strings/string_util.h"
26 #include "base/strings/utf_string_conversions.h"
27 #include "base/threading/thread_restrictions.h"
28 #include "base/time/time.h"
29 #include "base/win/scoped_handle.h"
30 #include "base/win/windows_version.h"
32 namespace base {
34 namespace {
36 const DWORD kFileShareAll =
37 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
39 } // namespace
41 FilePath MakeAbsoluteFilePath(const FilePath& input) {
42 ThreadRestrictions::AssertIOAllowed();
43 wchar_t file_path[MAX_PATH];
44 if (!_wfullpath(file_path, input.value().c_str(), MAX_PATH))
45 return FilePath();
46 return FilePath(file_path);
49 bool DeleteFile(const FilePath& path, bool recursive) {
50 ThreadRestrictions::AssertIOAllowed();
52 if (path.value().length() >= MAX_PATH)
53 return false;
55 // On XP SHFileOperation will return ERROR_ACCESS_DENIED instead of
56 // ERROR_FILE_NOT_FOUND, so just shortcut this here.
57 if (path.empty())
58 return true;
60 if (!recursive) {
61 // If not recursing, then first check to see if |path| is a directory.
62 // If it is, then remove it with RemoveDirectory.
63 File::Info file_info;
64 if (GetFileInfo(path, &file_info) && file_info.is_directory)
65 return RemoveDirectory(path.value().c_str()) != 0;
67 // Otherwise, it's a file, wildcard or non-existant. Try DeleteFile first
68 // because it should be faster. If DeleteFile fails, then we fall through
69 // to SHFileOperation, which will do the right thing.
70 if (::DeleteFile(path.value().c_str()) != 0)
71 return true;
74 // SHFILEOPSTRUCT wants the path to be terminated with two NULLs,
75 // so we have to use wcscpy because wcscpy_s writes non-NULLs
76 // into the rest of the buffer.
77 wchar_t double_terminated_path[MAX_PATH + 1] = {0};
78 #pragma warning(suppress:4996) // don't complain about wcscpy deprecation
79 wcscpy(double_terminated_path, path.value().c_str());
81 SHFILEOPSTRUCT file_operation = {0};
82 file_operation.wFunc = FO_DELETE;
83 file_operation.pFrom = double_terminated_path;
84 file_operation.fFlags = FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMATION;
85 if (!recursive)
86 file_operation.fFlags |= FOF_NORECURSION | FOF_FILESONLY;
87 int err = SHFileOperation(&file_operation);
89 // Since we're passing flags to the operation telling it to be silent,
90 // it's possible for the operation to be aborted/cancelled without err
91 // being set (although MSDN doesn't give any scenarios for how this can
92 // happen). See MSDN for SHFileOperation and SHFILEOPTSTRUCT.
93 if (file_operation.fAnyOperationsAborted)
94 return false;
96 // Some versions of Windows return ERROR_FILE_NOT_FOUND (0x2) when deleting
97 // an empty directory and some return 0x402 when they should be returning
98 // ERROR_FILE_NOT_FOUND. MSDN says Vista and up won't return 0x402. Windows 7
99 // can return DE_INVALIDFILES (0x7C) for nonexistent directories.
100 return (err == 0 || err == ERROR_FILE_NOT_FOUND || err == 0x402 ||
101 err == 0x7C);
104 bool DeleteFileAfterReboot(const FilePath& path) {
105 ThreadRestrictions::AssertIOAllowed();
107 if (path.value().length() >= MAX_PATH)
108 return false;
110 return MoveFileEx(path.value().c_str(), NULL,
111 MOVEFILE_DELAY_UNTIL_REBOOT |
112 MOVEFILE_REPLACE_EXISTING) != FALSE;
115 bool ReplaceFile(const FilePath& from_path,
116 const FilePath& to_path,
117 File::Error* error) {
118 ThreadRestrictions::AssertIOAllowed();
119 // Try a simple move first. It will only succeed when |to_path| doesn't
120 // already exist.
121 if (::MoveFile(from_path.value().c_str(), to_path.value().c_str()))
122 return true;
123 // Try the full-blown replace if the move fails, as ReplaceFile will only
124 // succeed when |to_path| does exist. When writing to a network share, we may
125 // not be able to change the ACLs. Ignore ACL errors then
126 // (REPLACEFILE_IGNORE_MERGE_ERRORS).
127 if (::ReplaceFile(to_path.value().c_str(), from_path.value().c_str(), NULL,
128 REPLACEFILE_IGNORE_MERGE_ERRORS, NULL, NULL)) {
129 return true;
131 if (error)
132 *error = File::OSErrorToFileError(GetLastError());
133 return false;
136 bool CopyDirectory(const FilePath& from_path, const FilePath& to_path,
137 bool recursive) {
138 // NOTE(maruel): Previous version of this function used to call
139 // SHFileOperation(). This used to copy the file attributes and extended
140 // attributes, OLE structured storage, NTFS file system alternate data
141 // streams, SECURITY_DESCRIPTOR. In practice, this is not what we want, we
142 // want the containing directory to propagate its SECURITY_DESCRIPTOR.
143 ThreadRestrictions::AssertIOAllowed();
145 // NOTE: I suspect we could support longer paths, but that would involve
146 // analyzing all our usage of files.
147 if (from_path.value().length() >= MAX_PATH ||
148 to_path.value().length() >= MAX_PATH) {
149 return false;
152 // This function does not properly handle destinations within the source.
153 FilePath real_to_path = to_path;
154 if (PathExists(real_to_path)) {
155 real_to_path = MakeAbsoluteFilePath(real_to_path);
156 if (real_to_path.empty())
157 return false;
158 } else {
159 real_to_path = MakeAbsoluteFilePath(real_to_path.DirName());
160 if (real_to_path.empty())
161 return false;
163 FilePath real_from_path = MakeAbsoluteFilePath(from_path);
164 if (real_from_path.empty())
165 return false;
166 if (real_to_path.value().size() >= real_from_path.value().size() &&
167 real_to_path.value().compare(0, real_from_path.value().size(),
168 real_from_path.value()) == 0) {
169 return false;
172 int traverse_type = FileEnumerator::FILES;
173 if (recursive)
174 traverse_type |= FileEnumerator::DIRECTORIES;
175 FileEnumerator traversal(from_path, recursive, traverse_type);
177 if (!PathExists(from_path)) {
178 DLOG(ERROR) << "CopyDirectory() couldn't stat source directory: "
179 << from_path.value().c_str();
180 return false;
182 // TODO(maruel): This is not necessary anymore.
183 DCHECK(recursive || DirectoryExists(from_path));
185 FilePath current = from_path;
186 bool from_is_dir = DirectoryExists(from_path);
187 bool success = true;
188 FilePath from_path_base = from_path;
189 if (recursive && DirectoryExists(to_path)) {
190 // If the destination already exists and is a directory, then the
191 // top level of source needs to be copied.
192 from_path_base = from_path.DirName();
195 while (success && !current.empty()) {
196 // current is the source path, including from_path, so append
197 // the suffix after from_path to to_path to create the target_path.
198 FilePath target_path(to_path);
199 if (from_path_base != current) {
200 if (!from_path_base.AppendRelativePath(current, &target_path)) {
201 success = false;
202 break;
206 if (from_is_dir) {
207 if (!DirectoryExists(target_path) &&
208 !::CreateDirectory(target_path.value().c_str(), NULL)) {
209 DLOG(ERROR) << "CopyDirectory() couldn't create directory: "
210 << target_path.value().c_str();
211 success = false;
213 } else if (!CopyFile(current, target_path)) {
214 DLOG(ERROR) << "CopyDirectory() couldn't create file: "
215 << target_path.value().c_str();
216 success = false;
219 current = traversal.Next();
220 if (!current.empty())
221 from_is_dir = traversal.GetInfo().IsDirectory();
224 return success;
227 bool PathExists(const FilePath& path) {
228 ThreadRestrictions::AssertIOAllowed();
229 return (GetFileAttributes(path.value().c_str()) != INVALID_FILE_ATTRIBUTES);
232 bool PathIsWritable(const FilePath& path) {
233 ThreadRestrictions::AssertIOAllowed();
234 win::ScopedHandle dir(
235 CreateFile(path.value().c_str(), FILE_ADD_FILE, kFileShareAll,
236 NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL));
238 return dir.IsValid();
241 bool DirectoryExists(const FilePath& path) {
242 ThreadRestrictions::AssertIOAllowed();
243 DWORD fileattr = GetFileAttributes(path.value().c_str());
244 if (fileattr != INVALID_FILE_ATTRIBUTES)
245 return (fileattr & FILE_ATTRIBUTE_DIRECTORY) != 0;
246 return false;
249 bool GetTempDir(FilePath* path) {
250 wchar_t temp_path[MAX_PATH + 1];
251 DWORD path_len = ::GetTempPath(MAX_PATH, temp_path);
252 if (path_len >= MAX_PATH || path_len <= 0)
253 return false;
254 // TODO(evanm): the old behavior of this function was to always strip the
255 // trailing slash. We duplicate this here, but it shouldn't be necessary
256 // when everyone is using the appropriate FilePath APIs.
257 *path = FilePath(temp_path).StripTrailingSeparators();
258 return true;
261 FilePath GetHomeDir() {
262 char16 result[MAX_PATH];
263 if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_PROFILE, NULL, SHGFP_TYPE_CURRENT,
264 result)) &&
265 result[0]) {
266 return FilePath(result);
269 // Fall back to the temporary directory on failure.
270 FilePath temp;
271 if (GetTempDir(&temp))
272 return temp;
274 // Last resort.
275 return FilePath(L"C:\\");
278 bool CreateTemporaryFile(FilePath* path) {
279 ThreadRestrictions::AssertIOAllowed();
281 FilePath temp_file;
283 if (!GetTempDir(path))
284 return false;
286 if (CreateTemporaryFileInDir(*path, &temp_file)) {
287 *path = temp_file;
288 return true;
291 return false;
294 // On POSIX we have semantics to create and open a temporary file
295 // atomically.
296 // TODO(jrg): is there equivalent call to use on Windows instead of
297 // going 2-step?
298 FILE* CreateAndOpenTemporaryFileInDir(const FilePath& dir, FilePath* path) {
299 ThreadRestrictions::AssertIOAllowed();
300 if (!CreateTemporaryFileInDir(dir, path)) {
301 return NULL;
303 // Open file in binary mode, to avoid problems with fwrite. On Windows
304 // it replaces \n's with \r\n's, which may surprise you.
305 // Reference: http://msdn.microsoft.com/en-us/library/h9t88zwz(VS.71).aspx
306 return OpenFile(*path, "wb+");
309 bool CreateTemporaryFileInDir(const FilePath& dir, FilePath* temp_file) {
310 ThreadRestrictions::AssertIOAllowed();
312 wchar_t temp_name[MAX_PATH + 1];
314 if (!GetTempFileName(dir.value().c_str(), L"", 0, temp_name)) {
315 DPLOG(WARNING) << "Failed to get temporary file name in "
316 << UTF16ToUTF8(dir.value());
317 return false;
320 wchar_t long_temp_name[MAX_PATH + 1];
321 DWORD long_name_len = GetLongPathName(temp_name, long_temp_name, MAX_PATH);
322 if (long_name_len > MAX_PATH || long_name_len == 0) {
323 // GetLongPathName() failed, but we still have a temporary file.
324 *temp_file = FilePath(temp_name);
325 return true;
328 FilePath::StringType long_temp_name_str;
329 long_temp_name_str.assign(long_temp_name, long_name_len);
330 *temp_file = FilePath(long_temp_name_str);
331 return true;
334 bool CreateTemporaryDirInDir(const FilePath& base_dir,
335 const FilePath::StringType& prefix,
336 FilePath* new_dir) {
337 ThreadRestrictions::AssertIOAllowed();
339 FilePath path_to_create;
341 for (int count = 0; count < 50; ++count) {
342 // Try create a new temporary directory with random generated name. If
343 // the one exists, keep trying another path name until we reach some limit.
344 string16 new_dir_name;
345 new_dir_name.assign(prefix);
346 new_dir_name.append(IntToString16(GetCurrentProcId()));
347 new_dir_name.push_back('_');
348 new_dir_name.append(IntToString16(RandInt(0, kint16max)));
350 path_to_create = base_dir.Append(new_dir_name);
351 if (::CreateDirectory(path_to_create.value().c_str(), NULL)) {
352 *new_dir = path_to_create;
353 return true;
357 return false;
360 bool CreateNewTempDirectory(const FilePath::StringType& prefix,
361 FilePath* new_temp_path) {
362 ThreadRestrictions::AssertIOAllowed();
364 FilePath system_temp_dir;
365 if (!GetTempDir(&system_temp_dir))
366 return false;
368 return CreateTemporaryDirInDir(system_temp_dir, prefix, new_temp_path);
371 bool CreateDirectoryAndGetError(const FilePath& full_path,
372 File::Error* error) {
373 ThreadRestrictions::AssertIOAllowed();
375 // If the path exists, we've succeeded if it's a directory, failed otherwise.
376 const wchar_t* full_path_str = full_path.value().c_str();
377 DWORD fileattr = ::GetFileAttributes(full_path_str);
378 if (fileattr != INVALID_FILE_ATTRIBUTES) {
379 if ((fileattr & FILE_ATTRIBUTE_DIRECTORY) != 0) {
380 DVLOG(1) << "CreateDirectory(" << full_path_str << "), "
381 << "directory already exists.";
382 return true;
384 DLOG(WARNING) << "CreateDirectory(" << full_path_str << "), "
385 << "conflicts with existing file.";
386 if (error) {
387 *error = File::FILE_ERROR_NOT_A_DIRECTORY;
389 return false;
392 // Invariant: Path does not exist as file or directory.
394 // Attempt to create the parent recursively. This will immediately return
395 // true if it already exists, otherwise will create all required parent
396 // directories starting with the highest-level missing parent.
397 FilePath parent_path(full_path.DirName());
398 if (parent_path.value() == full_path.value()) {
399 if (error) {
400 *error = File::FILE_ERROR_NOT_FOUND;
402 return false;
404 if (!CreateDirectoryAndGetError(parent_path, error)) {
405 DLOG(WARNING) << "Failed to create one of the parent directories.";
406 if (error) {
407 DCHECK(*error != File::FILE_OK);
409 return false;
412 if (!::CreateDirectory(full_path_str, NULL)) {
413 DWORD error_code = ::GetLastError();
414 if (error_code == ERROR_ALREADY_EXISTS && DirectoryExists(full_path)) {
415 // This error code ERROR_ALREADY_EXISTS doesn't indicate whether we
416 // were racing with someone creating the same directory, or a file
417 // with the same path. If DirectoryExists() returns true, we lost the
418 // race to create the same directory.
419 return true;
420 } else {
421 if (error)
422 *error = File::OSErrorToFileError(error_code);
423 DLOG(WARNING) << "Failed to create directory " << full_path_str
424 << ", last error is " << error_code << ".";
425 return false;
427 } else {
428 return true;
432 bool NormalizeFilePath(const FilePath& path, FilePath* real_path) {
433 ThreadRestrictions::AssertIOAllowed();
434 FilePath mapped_file;
435 if (!NormalizeToNativeFilePath(path, &mapped_file))
436 return false;
437 // NormalizeToNativeFilePath() will return a path that starts with
438 // "\Device\Harddisk...". Helper DevicePathToDriveLetterPath()
439 // will find a drive letter which maps to the path's device, so
440 // that we return a path starting with a drive letter.
441 return DevicePathToDriveLetterPath(mapped_file, real_path);
444 bool DevicePathToDriveLetterPath(const FilePath& nt_device_path,
445 FilePath* out_drive_letter_path) {
446 ThreadRestrictions::AssertIOAllowed();
448 // Get the mapping of drive letters to device paths.
449 const int kDriveMappingSize = 1024;
450 wchar_t drive_mapping[kDriveMappingSize] = {'\0'};
451 if (!::GetLogicalDriveStrings(kDriveMappingSize - 1, drive_mapping)) {
452 DLOG(ERROR) << "Failed to get drive mapping.";
453 return false;
456 // The drive mapping is a sequence of null terminated strings.
457 // The last string is empty.
458 wchar_t* drive_map_ptr = drive_mapping;
459 wchar_t device_path_as_string[MAX_PATH];
460 wchar_t drive[] = L" :";
462 // For each string in the drive mapping, get the junction that links
463 // to it. If that junction is a prefix of |device_path|, then we
464 // know that |drive| is the real path prefix.
465 while (*drive_map_ptr) {
466 drive[0] = drive_map_ptr[0]; // Copy the drive letter.
468 if (QueryDosDevice(drive, device_path_as_string, MAX_PATH)) {
469 FilePath device_path(device_path_as_string);
470 if (device_path == nt_device_path ||
471 device_path.IsParent(nt_device_path)) {
472 *out_drive_letter_path = FilePath(drive +
473 nt_device_path.value().substr(wcslen(device_path_as_string)));
474 return true;
477 // Move to the next drive letter string, which starts one
478 // increment after the '\0' that terminates the current string.
479 while (*drive_map_ptr++) {}
482 // No drive matched. The path does not start with a device junction
483 // that is mounted as a drive letter. This means there is no drive
484 // letter path to the volume that holds |device_path|, so fail.
485 return false;
488 bool NormalizeToNativeFilePath(const FilePath& path, FilePath* nt_path) {
489 ThreadRestrictions::AssertIOAllowed();
490 // In Vista, GetFinalPathNameByHandle() would give us the real path
491 // from a file handle. If we ever deprecate XP, consider changing the
492 // code below to a call to GetFinalPathNameByHandle(). The method this
493 // function uses is explained in the following msdn article:
494 // http://msdn.microsoft.com/en-us/library/aa366789(VS.85).aspx
495 win::ScopedHandle file_handle(
496 ::CreateFile(path.value().c_str(),
497 GENERIC_READ,
498 kFileShareAll,
499 NULL,
500 OPEN_EXISTING,
501 FILE_ATTRIBUTE_NORMAL,
502 NULL));
503 if (!file_handle.IsValid())
504 return false;
506 // Create a file mapping object. Can't easily use MemoryMappedFile, because
507 // we only map the first byte, and need direct access to the handle. You can
508 // not map an empty file, this call fails in that case.
509 win::ScopedHandle file_map_handle(
510 ::CreateFileMapping(file_handle.Get(),
511 NULL,
512 PAGE_READONLY,
514 1, // Just one byte. No need to look at the data.
515 NULL));
516 if (!file_map_handle.IsValid())
517 return false;
519 // Use a view of the file to get the path to the file.
520 void* file_view = MapViewOfFile(file_map_handle.Get(),
521 FILE_MAP_READ, 0, 0, 1);
522 if (!file_view)
523 return false;
525 // The expansion of |path| into a full path may make it longer.
526 // GetMappedFileName() will fail if the result is longer than MAX_PATH.
527 // Pad a bit to be safe. If kMaxPathLength is ever changed to be less
528 // than MAX_PATH, it would be nessisary to test that GetMappedFileName()
529 // not return kMaxPathLength. This would mean that only part of the
530 // path fit in |mapped_file_path|.
531 const int kMaxPathLength = MAX_PATH + 10;
532 wchar_t mapped_file_path[kMaxPathLength];
533 bool success = false;
534 HANDLE cp = GetCurrentProcess();
535 if (::GetMappedFileNameW(cp, file_view, mapped_file_path, kMaxPathLength)) {
536 *nt_path = FilePath(mapped_file_path);
537 success = true;
539 ::UnmapViewOfFile(file_view);
540 return success;
543 // TODO(rkc): Work out if we want to handle NTFS junctions here or not, handle
544 // them if we do decide to.
545 bool IsLink(const FilePath& file_path) {
546 return false;
549 bool GetFileInfo(const FilePath& file_path, File::Info* results) {
550 ThreadRestrictions::AssertIOAllowed();
552 WIN32_FILE_ATTRIBUTE_DATA attr;
553 if (!GetFileAttributesEx(file_path.value().c_str(),
554 GetFileExInfoStandard, &attr)) {
555 return false;
558 ULARGE_INTEGER size;
559 size.HighPart = attr.nFileSizeHigh;
560 size.LowPart = attr.nFileSizeLow;
561 results->size = size.QuadPart;
563 results->is_directory =
564 (attr.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
565 results->last_modified = Time::FromFileTime(attr.ftLastWriteTime);
566 results->last_accessed = Time::FromFileTime(attr.ftLastAccessTime);
567 results->creation_time = Time::FromFileTime(attr.ftCreationTime);
569 return true;
572 FILE* OpenFile(const FilePath& filename, const char* mode) {
573 ThreadRestrictions::AssertIOAllowed();
574 string16 w_mode = ASCIIToUTF16(mode);
575 return _wfsopen(filename.value().c_str(), w_mode.c_str(), _SH_DENYNO);
578 FILE* FileToFILE(File file, const char* mode) {
579 if (!file.IsValid())
580 return NULL;
581 int fd =
582 _open_osfhandle(reinterpret_cast<intptr_t>(file.GetPlatformFile()), 0);
583 if (fd < 0)
584 return NULL;
585 file.TakePlatformFile();
586 FILE* stream = _fdopen(fd, mode);
587 if (!stream)
588 _close(fd);
589 return stream;
592 int ReadFile(const FilePath& filename, char* data, int max_size) {
593 ThreadRestrictions::AssertIOAllowed();
594 win::ScopedHandle file(CreateFile(filename.value().c_str(),
595 GENERIC_READ,
596 FILE_SHARE_READ | FILE_SHARE_WRITE,
597 NULL,
598 OPEN_EXISTING,
599 FILE_FLAG_SEQUENTIAL_SCAN,
600 NULL));
601 if (!file.IsValid())
602 return -1;
604 DWORD read;
605 if (::ReadFile(file.Get(), data, max_size, &read, NULL))
606 return read;
608 return -1;
611 int WriteFile(const FilePath& filename, const char* data, int size) {
612 ThreadRestrictions::AssertIOAllowed();
613 win::ScopedHandle file(CreateFile(filename.value().c_str(),
614 GENERIC_WRITE,
616 NULL,
617 CREATE_ALWAYS,
619 NULL));
620 if (!file.IsValid()) {
621 DPLOG(WARNING) << "CreateFile failed for path "
622 << UTF16ToUTF8(filename.value());
623 return -1;
626 DWORD written;
627 BOOL result = ::WriteFile(file.Get(), data, size, &written, NULL);
628 if (result && static_cast<int>(written) == size)
629 return written;
631 if (!result) {
632 // WriteFile failed.
633 DPLOG(WARNING) << "writing file " << UTF16ToUTF8(filename.value())
634 << " failed";
635 } else {
636 // Didn't write all the bytes.
637 DLOG(WARNING) << "wrote" << written << " bytes to "
638 << UTF16ToUTF8(filename.value()) << " expected " << size;
640 return -1;
643 bool AppendToFile(const FilePath& filename, const char* data, int size) {
644 ThreadRestrictions::AssertIOAllowed();
645 win::ScopedHandle file(CreateFile(filename.value().c_str(),
646 FILE_APPEND_DATA,
648 NULL,
649 OPEN_EXISTING,
651 NULL));
652 if (!file.IsValid()) {
653 VPLOG(1) << "CreateFile failed for path " << UTF16ToUTF8(filename.value());
654 return false;
657 DWORD written;
658 BOOL result = ::WriteFile(file.Get(), data, size, &written, NULL);
659 if (result && static_cast<int>(written) == size)
660 return true;
662 if (!result) {
663 // WriteFile failed.
664 VPLOG(1) << "Writing file " << UTF16ToUTF8(filename.value()) << " failed";
665 } else {
666 // Didn't write all the bytes.
667 VPLOG(1) << "Only wrote " << written << " out of " << size << " byte(s) to "
668 << UTF16ToUTF8(filename.value());
670 return false;
673 // Gets the current working directory for the process.
674 bool GetCurrentDirectory(FilePath* dir) {
675 ThreadRestrictions::AssertIOAllowed();
677 wchar_t system_buffer[MAX_PATH];
678 system_buffer[0] = 0;
679 DWORD len = ::GetCurrentDirectory(MAX_PATH, system_buffer);
680 if (len == 0 || len > MAX_PATH)
681 return false;
682 // TODO(evanm): the old behavior of this function was to always strip the
683 // trailing slash. We duplicate this here, but it shouldn't be necessary
684 // when everyone is using the appropriate FilePath APIs.
685 std::wstring dir_str(system_buffer);
686 *dir = FilePath(dir_str).StripTrailingSeparators();
687 return true;
690 // Sets the current working directory for the process.
691 bool SetCurrentDirectory(const FilePath& directory) {
692 ThreadRestrictions::AssertIOAllowed();
693 BOOL ret = ::SetCurrentDirectory(directory.value().c_str());
694 return ret != 0;
697 int GetMaximumPathComponentLength(const FilePath& path) {
698 ThreadRestrictions::AssertIOAllowed();
700 wchar_t volume_path[MAX_PATH];
701 if (!GetVolumePathNameW(path.NormalizePathSeparators().value().c_str(),
702 volume_path,
703 arraysize(volume_path))) {
704 return -1;
707 DWORD max_length = 0;
708 if (!GetVolumeInformationW(volume_path, NULL, 0, NULL, &max_length, NULL,
709 NULL, 0)) {
710 return -1;
713 // Length of |path| with path separator appended.
714 size_t prefix = path.StripTrailingSeparators().value().size() + 1;
715 // The whole path string must be shorter than MAX_PATH. That is, it must be
716 // prefix + component_length < MAX_PATH (or equivalently, <= MAX_PATH - 1).
717 int whole_path_limit = std::max(0, MAX_PATH - 1 - static_cast<int>(prefix));
718 return std::min(whole_path_limit, static_cast<int>(max_length));
721 bool CopyFile(const FilePath& from_path, const FilePath& to_path) {
722 ThreadRestrictions::AssertIOAllowed();
723 if (from_path.ReferencesParent() || to_path.ReferencesParent())
724 return false;
726 // NOTE: I suspect we could support longer paths, but that would involve
727 // analyzing all our usage of files.
728 if (from_path.value().length() >= MAX_PATH ||
729 to_path.value().length() >= MAX_PATH) {
730 return false;
733 // Unlike the posix implementation that copies the file manually and discards
734 // the ACL bits, CopyFile() copies the complete SECURITY_DESCRIPTOR and access
735 // bits, which is usually not what we want. We can't do much about the
736 // SECURITY_DESCRIPTOR but at least remove the read only bit.
737 const wchar_t* dest = to_path.value().c_str();
738 if (!::CopyFile(from_path.value().c_str(), dest, false)) {
739 // Copy failed.
740 return false;
742 DWORD attrs = GetFileAttributes(dest);
743 if (attrs == INVALID_FILE_ATTRIBUTES) {
744 return false;
746 if (attrs & FILE_ATTRIBUTE_READONLY) {
747 SetFileAttributes(dest, attrs & ~FILE_ATTRIBUTE_READONLY);
749 return true;
752 // -----------------------------------------------------------------------------
754 namespace internal {
756 bool MoveUnsafe(const FilePath& from_path, const FilePath& to_path) {
757 ThreadRestrictions::AssertIOAllowed();
759 // NOTE: I suspect we could support longer paths, but that would involve
760 // analyzing all our usage of files.
761 if (from_path.value().length() >= MAX_PATH ||
762 to_path.value().length() >= MAX_PATH) {
763 return false;
765 if (MoveFileEx(from_path.value().c_str(), to_path.value().c_str(),
766 MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING) != 0)
767 return true;
769 // Keep the last error value from MoveFileEx around in case the below
770 // fails.
771 bool ret = false;
772 DWORD last_error = ::GetLastError();
774 if (DirectoryExists(from_path)) {
775 // MoveFileEx fails if moving directory across volumes. We will simulate
776 // the move by using Copy and Delete. Ideally we could check whether
777 // from_path and to_path are indeed in different volumes.
778 ret = internal::CopyAndDeleteDirectory(from_path, to_path);
781 if (!ret) {
782 // Leave a clue about what went wrong so that it can be (at least) picked
783 // up by a PLOG entry.
784 ::SetLastError(last_error);
787 return ret;
790 bool CopyAndDeleteDirectory(const FilePath& from_path,
791 const FilePath& to_path) {
792 ThreadRestrictions::AssertIOAllowed();
793 if (CopyDirectory(from_path, to_path, true)) {
794 if (DeleteFile(from_path, true))
795 return true;
797 // Like Move, this function is not transactional, so we just
798 // leave the copied bits behind if deleting from_path fails.
799 // If to_path exists previously then we have already overwritten
800 // it by now, we don't get better off by deleting the new bits.
802 return false;
805 } // namespace internal
806 } // namespace base