PPB_FLASH_DEVICEID_INTERFACE_1_0 requires PERMISSION_FLASH.
[chromium-blink-merge.git] / base / file_util_win.cc
blob5350b348646e1828c3d7535943136623f8fa3f23
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 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 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
300 // atomically.
301 // TODO(jrg): is there equivalent call to use on Windows instead of
302 // going 2-step?
303 FILE* CreateAndOpenTemporaryFileInDir(const FilePath& dir, FilePath* path) {
304 ThreadRestrictions::AssertIOAllowed();
305 if (!CreateTemporaryFileInDir(dir, path)) {
306 return NULL;
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());
322 return false;
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);
330 return true;
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);
336 return true;
339 bool CreateTemporaryDirInDir(const FilePath& base_dir,
340 const FilePath::StringType& prefix,
341 FilePath* new_dir) {
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;
358 return true;
362 return false;
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))
371 return false;
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.";
387 return true;
389 DLOG(WARNING) << "CreateDirectory(" << full_path_str << "), "
390 << "conflicts with existing file.";
391 if (error) {
392 *error = File::FILE_ERROR_NOT_A_DIRECTORY;
394 return false;
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()) {
404 if (error) {
405 *error = File::FILE_ERROR_NOT_FOUND;
407 return false;
409 if (!CreateDirectoryAndGetError(parent_path, error)) {
410 DLOG(WARNING) << "Failed to create one of the parent directories.";
411 if (error) {
412 DCHECK(*error != File::FILE_OK);
414 return false;
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.
424 return true;
425 } else {
426 if (error)
427 *error = File::OSErrorToFileError(error_code);
428 DLOG(WARNING) << "Failed to create directory " << full_path_str
429 << ", last error is " << error_code << ".";
430 return false;
432 } else {
433 return true;
437 bool NormalizeFilePath(const FilePath& path, FilePath* real_path) {
438 ThreadRestrictions::AssertIOAllowed();
439 FilePath mapped_file;
440 if (!NormalizeToNativeFilePath(path, &mapped_file))
441 return false;
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.";
458 return false;
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)));
479 return true;
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.
490 return false;
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(),
502 GENERIC_READ,
503 kFileShareAll,
504 NULL,
505 OPEN_EXISTING,
506 FILE_ATTRIBUTE_NORMAL,
507 NULL));
508 if (!file_handle)
509 return false;
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(),
516 NULL,
517 PAGE_READONLY,
519 1, // Just one byte. No need to look at the data.
520 NULL));
521 if (!file_map_handle)
522 return false;
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);
527 if (!file_view)
528 return false;
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);
542 success = true;
544 ::UnmapViewOfFile(file_view);
545 return success;
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) {
551 return false;
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)) {
560 return false;
563 ULARGE_INTEGER size;
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);
574 return true;
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(),
586 GENERIC_READ,
587 FILE_SHARE_READ | FILE_SHARE_WRITE,
588 NULL,
589 OPEN_EXISTING,
590 FILE_FLAG_SEQUENTIAL_SCAN,
591 NULL));
592 if (!file)
593 return -1;
595 DWORD read;
596 if (::ReadFile(file, data, size, &read, NULL) &&
597 static_cast<int>(read) == size)
598 return read;
599 return -1;
602 int WriteFile(const FilePath& filename, const char* data, int size) {
603 ThreadRestrictions::AssertIOAllowed();
604 base::win::ScopedHandle file(CreateFile(filename.value().c_str(),
605 GENERIC_WRITE,
607 NULL,
608 CREATE_ALWAYS,
610 NULL));
611 if (!file) {
612 DLOG_GETLASTERROR(WARNING) << "CreateFile failed for path "
613 << UTF16ToUTF8(filename.value());
614 return -1;
617 DWORD written;
618 BOOL result = ::WriteFile(file, data, size, &written, NULL);
619 if (result && static_cast<int>(written) == size)
620 return written;
622 if (!result) {
623 // WriteFile failed.
624 DLOG_GETLASTERROR(WARNING) << "writing file "
625 << UTF16ToUTF8(filename.value()) << " failed";
626 } else {
627 // Didn't write all the bytes.
628 DLOG(WARNING) << "wrote" << written << " bytes to "
629 << UTF16ToUTF8(filename.value()) << " expected " << size;
631 return -1;
634 int AppendToFile(const FilePath& filename, const char* data, int size) {
635 ThreadRestrictions::AssertIOAllowed();
636 base::win::ScopedHandle file(CreateFile(filename.value().c_str(),
637 FILE_APPEND_DATA,
639 NULL,
640 OPEN_EXISTING,
642 NULL));
643 if (!file) {
644 DLOG_GETLASTERROR(WARNING) << "CreateFile failed for path "
645 << UTF16ToUTF8(filename.value());
646 return -1;
649 DWORD written;
650 BOOL result = ::WriteFile(file, data, size, &written, NULL);
651 if (result && static_cast<int>(written) == size)
652 return written;
654 if (!result) {
655 // WriteFile failed.
656 DLOG_GETLASTERROR(WARNING) << "writing file "
657 << UTF16ToUTF8(filename.value())
658 << " failed";
659 } else {
660 // Didn't write all the bytes.
661 DLOG(WARNING) << "wrote" << written << " bytes to "
662 << UTF16ToUTF8(filename.value()) << " expected " << size;
664 return -1;
667 // Gets the current working directory for the process.
668 bool GetCurrentDirectory(FilePath* dir) {
669 ThreadRestrictions::AssertIOAllowed();
671 wchar_t system_buffer[MAX_PATH];
672 system_buffer[0] = 0;
673 DWORD len = ::GetCurrentDirectory(MAX_PATH, system_buffer);
674 if (len == 0 || len > MAX_PATH)
675 return false;
676 // TODO(evanm): the old behavior of this function was to always strip the
677 // trailing slash. We duplicate this here, but it shouldn't be necessary
678 // when everyone is using the appropriate FilePath APIs.
679 std::wstring dir_str(system_buffer);
680 *dir = FilePath(dir_str).StripTrailingSeparators();
681 return true;
684 // Sets the current working directory for the process.
685 bool SetCurrentDirectory(const FilePath& directory) {
686 ThreadRestrictions::AssertIOAllowed();
687 BOOL ret = ::SetCurrentDirectory(directory.value().c_str());
688 return ret != 0;
691 } // namespace base
693 // -----------------------------------------------------------------------------
695 namespace file_util {
697 using base::DirectoryExists;
698 using base::FilePath;
699 using base::kFileShareAll;
701 FILE* OpenFile(const std::string& filename, const char* mode) {
702 base::ThreadRestrictions::AssertIOAllowed();
703 return _fsopen(filename.c_str(), mode, _SH_DENYNO);
706 int GetMaximumPathComponentLength(const FilePath& path) {
707 base::ThreadRestrictions::AssertIOAllowed();
709 wchar_t volume_path[MAX_PATH];
710 if (!GetVolumePathNameW(path.NormalizePathSeparators().value().c_str(),
711 volume_path,
712 arraysize(volume_path))) {
713 return -1;
716 DWORD max_length = 0;
717 if (!GetVolumeInformationW(volume_path, NULL, 0, NULL, &max_length, NULL,
718 NULL, 0)) {
719 return -1;
722 // Length of |path| with path separator appended.
723 size_t prefix = path.StripTrailingSeparators().value().size() + 1;
724 // The whole path string must be shorter than MAX_PATH. That is, it must be
725 // prefix + component_length < MAX_PATH (or equivalently, <= MAX_PATH - 1).
726 int whole_path_limit = std::max(0, MAX_PATH - 1 - static_cast<int>(prefix));
727 return std::min(whole_path_limit, static_cast<int>(max_length));
730 } // namespace file_util
732 namespace base {
733 namespace internal {
735 bool MoveUnsafe(const FilePath& from_path, const FilePath& to_path) {
736 ThreadRestrictions::AssertIOAllowed();
738 // NOTE: I suspect we could support longer paths, but that would involve
739 // analyzing all our usage of files.
740 if (from_path.value().length() >= MAX_PATH ||
741 to_path.value().length() >= MAX_PATH) {
742 return false;
744 if (MoveFileEx(from_path.value().c_str(), to_path.value().c_str(),
745 MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING) != 0)
746 return true;
748 // Keep the last error value from MoveFileEx around in case the below
749 // fails.
750 bool ret = false;
751 DWORD last_error = ::GetLastError();
753 if (DirectoryExists(from_path)) {
754 // MoveFileEx fails if moving directory across volumes. We will simulate
755 // the move by using Copy and Delete. Ideally we could check whether
756 // from_path and to_path are indeed in different volumes.
757 ret = internal::CopyAndDeleteDirectory(from_path, to_path);
760 if (!ret) {
761 // Leave a clue about what went wrong so that it can be (at least) picked
762 // up by a PLOG entry.
763 ::SetLastError(last_error);
766 return ret;
769 bool CopyFileUnsafe(const FilePath& from_path, const FilePath& to_path) {
770 ThreadRestrictions::AssertIOAllowed();
772 // NOTE: I suspect we could support longer paths, but that would involve
773 // analyzing all our usage of files.
774 if (from_path.value().length() >= MAX_PATH ||
775 to_path.value().length() >= MAX_PATH) {
776 return false;
779 // Unlike the posix implementation that copies the file manually and discards
780 // the ACL bits, CopyFile() copies the complete SECURITY_DESCRIPTOR and access
781 // bits, which is usually not what we want. We can't do much about the
782 // SECURITY_DESCRIPTOR but at least remove the read only bit.
783 const wchar_t* dest = to_path.value().c_str();
784 if (!::CopyFile(from_path.value().c_str(), dest, false)) {
785 // Copy failed.
786 return false;
788 DWORD attrs = GetFileAttributes(dest);
789 if (attrs == INVALID_FILE_ATTRIBUTES) {
790 return false;
792 if (attrs & FILE_ATTRIBUTE_READONLY) {
793 SetFileAttributes(dest, attrs & ~FILE_ATTRIBUTE_READONLY);
795 return true;
798 bool CopyAndDeleteDirectory(const FilePath& from_path,
799 const FilePath& to_path) {
800 ThreadRestrictions::AssertIOAllowed();
801 if (CopyDirectory(from_path, to_path, true)) {
802 if (DeleteFile(from_path, true))
803 return true;
805 // Like Move, this function is not transactional, so we just
806 // leave the copied bits behind if deleting from_path fails.
807 // If to_path exists previously then we have already overwritten
808 // it by now, we don't get better off by deleting the new bits.
810 return false;
813 } // namespace internal
814 } // namespace base