summaryrefslogtreecommitdiffstats
path: root/base/files
diff options
context:
space:
mode:
Diffstat (limited to 'base/files')
-rw-r--r--base/files/file_enumerator.cc2
-rw-r--r--base/files/file_path_watcher_browsertest.cc2
-rw-r--r--base/files/file_path_watcher_fsevents.cc2
-rw-r--r--base/files/file_path_watcher_kqueue.cc2
-rw-r--r--base/files/file_path_watcher_linux.cc2
-rw-r--r--base/files/file_path_watcher_win.cc2
-rw-r--r--base/files/file_proxy.cc2
-rw-r--r--base/files/file_proxy_unittest.cc2
-rw-r--r--base/files/file_unittest.cc2
-rw-r--r--base/files/file_util.cc260
-rw-r--r--base/files/file_util.h439
-rw-r--r--base/files/file_util_android.cc16
-rw-r--r--base/files/file_util_linux.cc78
-rw-r--r--base/files/file_util_mac.mm52
-rw-r--r--base/files/file_util_posix.cc912
-rw-r--r--base/files/file_util_proxy.cc2
-rw-r--r--base/files/file_util_proxy_unittest.cc2
-rw-r--r--base/files/file_util_unittest.cc2596
-rw-r--r--base/files/file_util_win.cc810
-rw-r--r--base/files/important_file_writer.cc2
-rw-r--r--base/files/important_file_writer_unittest.cc2
-rw-r--r--base/files/memory_mapped_file_unittest.cc2
-rw-r--r--base/files/scoped_temp_dir.cc2
-rw-r--r--base/files/scoped_temp_dir_unittest.cc2
24 files changed, 5179 insertions, 16 deletions
diff --git a/base/files/file_enumerator.cc b/base/files/file_enumerator.cc
index e49f465..9749980 100644
--- a/base/files/file_enumerator.cc
+++ b/base/files/file_enumerator.cc
@@ -4,7 +4,7 @@
#include "base/files/file_enumerator.h"
-#include "base/file_util.h"
+#include "base/files/file_util.h"
namespace base {
diff --git a/base/files/file_path_watcher_browsertest.cc b/base/files/file_path_watcher_browsertest.cc
index ff6d9d5..5cf75fc 100644
--- a/base/files/file_path_watcher_browsertest.cc
+++ b/base/files/file_path_watcher_browsertest.cc
@@ -17,8 +17,8 @@
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/compiler_specific.h"
-#include "base/file_util.h"
#include "base/files/file_path.h"
+#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/message_loop/message_loop.h"
#include "base/message_loop/message_loop_proxy.h"
diff --git a/base/files/file_path_watcher_fsevents.cc b/base/files/file_path_watcher_fsevents.cc
index edf4d23..f658efe 100644
--- a/base/files/file_path_watcher_fsevents.cc
+++ b/base/files/file_path_watcher_fsevents.cc
@@ -7,7 +7,7 @@
#include <list>
#include "base/bind.h"
-#include "base/file_util.h"
+#include "base/files/file_util.h"
#include "base/lazy_instance.h"
#include "base/logging.h"
#include "base/mac/libdispatch_task_runner.h"
diff --git a/base/files/file_path_watcher_kqueue.cc b/base/files/file_path_watcher_kqueue.cc
index c38e344..8941d2e 100644
--- a/base/files/file_path_watcher_kqueue.cc
+++ b/base/files/file_path_watcher_kqueue.cc
@@ -8,7 +8,7 @@
#include <sys/param.h>
#include "base/bind.h"
-#include "base/file_util.h"
+#include "base/files/file_util.h"
#include "base/logging.h"
#include "base/strings/stringprintf.h"
diff --git a/base/files/file_path_watcher_linux.cc b/base/files/file_path_watcher_linux.cc
index 915ad50..26eafb3 100644
--- a/base/files/file_path_watcher_linux.cc
+++ b/base/files/file_path_watcher_linux.cc
@@ -20,9 +20,9 @@
#include "base/bind.h"
#include "base/containers/hash_tables.h"
#include "base/debug/trace_event.h"
-#include "base/file_util.h"
#include "base/files/file_enumerator.h"
#include "base/files/file_path.h"
+#include "base/files/file_util.h"
#include "base/lazy_instance.h"
#include "base/location.h"
#include "base/logging.h"
diff --git a/base/files/file_path_watcher_win.cc b/base/files/file_path_watcher_win.cc
index ec2fe6d..a3021404 100644
--- a/base/files/file_path_watcher_win.cc
+++ b/base/files/file_path_watcher_win.cc
@@ -5,9 +5,9 @@
#include "base/files/file_path_watcher.h"
#include "base/bind.h"
-#include "base/file_util.h"
#include "base/files/file.h"
#include "base/files/file_path.h"
+#include "base/files/file_util.h"
#include "base/logging.h"
#include "base/memory/ref_counted.h"
#include "base/message_loop/message_loop_proxy.h"
diff --git a/base/files/file_proxy.cc b/base/files/file_proxy.cc
index 291b98d..53b14fe 100644
--- a/base/files/file_proxy.cc
+++ b/base/files/file_proxy.cc
@@ -6,8 +6,8 @@
#include "base/bind.h"
#include "base/bind_helpers.h"
-#include "base/file_util.h"
#include "base/files/file.h"
+#include "base/files/file_util.h"
#include "base/location.h"
#include "base/message_loop/message_loop_proxy.h"
#include "base/task_runner.h"
diff --git a/base/files/file_proxy_unittest.cc b/base/files/file_proxy_unittest.cc
index 9be8abf..2c62fa9 100644
--- a/base/files/file_proxy_unittest.cc
+++ b/base/files/file_proxy_unittest.cc
@@ -5,8 +5,8 @@
#include "base/files/file_proxy.h"
#include "base/bind.h"
-#include "base/file_util.h"
#include "base/files/file.h"
+#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/memory/weak_ptr.h"
#include "base/message_loop/message_loop.h"
diff --git a/base/files/file_unittest.cc b/base/files/file_unittest.cc
index de88145..6616f6a 100644
--- a/base/files/file_unittest.cc
+++ b/base/files/file_unittest.cc
@@ -2,8 +2,8 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#include "base/file_util.h"
#include "base/files/file.h"
+#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/time/time.h"
#include "testing/gtest/include/gtest/gtest.h"
diff --git a/base/files/file_util.cc b/base/files/file_util.cc
new file mode 100644
index 0000000..96a7164
--- /dev/null
+++ b/base/files/file_util.cc
@@ -0,0 +1,260 @@
+// Copyright (c) 2012 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "base/files/file_util.h"
+
+#if defined(OS_WIN)
+#include <io.h>
+#endif
+#include <stdio.h>
+
+#include <fstream>
+#include <limits>
+
+#include "base/files/file_enumerator.h"
+#include "base/files/file_path.h"
+#include "base/logging.h"
+#include "base/strings/string_piece.h"
+#include "base/strings/string_util.h"
+#include "base/strings/stringprintf.h"
+#include "base/strings/utf_string_conversions.h"
+
+namespace base {
+
+namespace {
+
+// The maximum number of 'uniquified' files we will try to create.
+// This is used when the filename we're trying to download is already in use,
+// so we create a new unique filename by appending " (nnn)" before the
+// extension, where 1 <= nnn <= kMaxUniqueFiles.
+// Also used by code that cleans up said files.
+static const int kMaxUniqueFiles = 100;
+
+} // namespace
+
+int64 ComputeDirectorySize(const FilePath& root_path) {
+ int64 running_size = 0;
+ FileEnumerator file_iter(root_path, true, FileEnumerator::FILES);
+ while (!file_iter.Next().empty())
+ running_size += file_iter.GetInfo().GetSize();
+ return running_size;
+}
+
+bool Move(const FilePath& from_path, const FilePath& to_path) {
+ if (from_path.ReferencesParent() || to_path.ReferencesParent())
+ return false;
+ return internal::MoveUnsafe(from_path, to_path);
+}
+
+bool CopyFile(const FilePath& from_path, const FilePath& to_path) {
+ if (from_path.ReferencesParent() || to_path.ReferencesParent())
+ return false;
+ return internal::CopyFileUnsafe(from_path, to_path);
+}
+
+bool ContentsEqual(const FilePath& filename1, const FilePath& filename2) {
+ // We open the file in binary format even if they are text files because
+ // we are just comparing that bytes are exactly same in both files and not
+ // doing anything smart with text formatting.
+ std::ifstream file1(filename1.value().c_str(),
+ std::ios::in | std::ios::binary);
+ std::ifstream file2(filename2.value().c_str(),
+ std::ios::in | std::ios::binary);
+
+ // Even if both files aren't openable (and thus, in some sense, "equal"),
+ // any unusable file yields a result of "false".
+ if (!file1.is_open() || !file2.is_open())
+ return false;
+
+ const int BUFFER_SIZE = 2056;
+ char buffer1[BUFFER_SIZE], buffer2[BUFFER_SIZE];
+ do {
+ file1.read(buffer1, BUFFER_SIZE);
+ file2.read(buffer2, BUFFER_SIZE);
+
+ if ((file1.eof() != file2.eof()) ||
+ (file1.gcount() != file2.gcount()) ||
+ (memcmp(buffer1, buffer2, file1.gcount()))) {
+ file1.close();
+ file2.close();
+ return false;
+ }
+ } while (!file1.eof() || !file2.eof());
+
+ file1.close();
+ file2.close();
+ return true;
+}
+
+bool TextContentsEqual(const FilePath& filename1, const FilePath& filename2) {
+ std::ifstream file1(filename1.value().c_str(), std::ios::in);
+ std::ifstream file2(filename2.value().c_str(), std::ios::in);
+
+ // Even if both files aren't openable (and thus, in some sense, "equal"),
+ // any unusable file yields a result of "false".
+ if (!file1.is_open() || !file2.is_open())
+ return false;
+
+ do {
+ std::string line1, line2;
+ getline(file1, line1);
+ getline(file2, line2);
+
+ // Check for mismatched EOF states, or any error state.
+ if ((file1.eof() != file2.eof()) ||
+ file1.bad() || file2.bad()) {
+ return false;
+ }
+
+ // Trim all '\r' and '\n' characters from the end of the line.
+ std::string::size_type end1 = line1.find_last_not_of("\r\n");
+ if (end1 == std::string::npos)
+ line1.clear();
+ else if (end1 + 1 < line1.length())
+ line1.erase(end1 + 1);
+
+ std::string::size_type end2 = line2.find_last_not_of("\r\n");
+ if (end2 == std::string::npos)
+ line2.clear();
+ else if (end2 + 1 < line2.length())
+ line2.erase(end2 + 1);
+
+ if (line1 != line2)
+ return false;
+ } while (!file1.eof() || !file2.eof());
+
+ return true;
+}
+
+bool ReadFileToString(const FilePath& path,
+ std::string* contents,
+ size_t max_size) {
+ if (contents)
+ contents->clear();
+ if (path.ReferencesParent())
+ return false;
+ FILE* file = OpenFile(path, "rb");
+ if (!file) {
+ return false;
+ }
+
+ char buf[1 << 16];
+ size_t len;
+ size_t size = 0;
+ bool read_status = true;
+
+ // Many files supplied in |path| have incorrect size (proc files etc).
+ // Hence, the file is read sequentially as opposed to a one-shot read.
+ while ((len = fread(buf, 1, sizeof(buf), file)) > 0) {
+ if (contents)
+ contents->append(buf, std::min(len, max_size - size));
+
+ if ((max_size - size) < len) {
+ read_status = false;
+ break;
+ }
+
+ size += len;
+ }
+ read_status = read_status && !ferror(file);
+ CloseFile(file);
+
+ return read_status;
+}
+
+bool ReadFileToString(const FilePath& path, std::string* contents) {
+ return ReadFileToString(path, contents, std::numeric_limits<size_t>::max());
+}
+
+bool IsDirectoryEmpty(const FilePath& dir_path) {
+ FileEnumerator files(dir_path, false,
+ FileEnumerator::FILES | FileEnumerator::DIRECTORIES);
+ if (files.Next().empty())
+ return true;
+ return false;
+}
+
+FILE* CreateAndOpenTemporaryFile(FilePath* path) {
+ FilePath directory;
+ if (!GetTempDir(&directory))
+ return NULL;
+
+ return CreateAndOpenTemporaryFileInDir(directory, path);
+}
+
+bool CreateDirectory(const FilePath& full_path) {
+ return CreateDirectoryAndGetError(full_path, NULL);
+}
+
+bool GetFileSize(const FilePath& file_path, int64* file_size) {
+ File::Info info;
+ if (!GetFileInfo(file_path, &info))
+ return false;
+ *file_size = info.size;
+ return true;
+}
+
+bool TouchFile(const FilePath& path,
+ const Time& last_accessed,
+ const Time& last_modified) {
+ int flags = File::FLAG_OPEN | File::FLAG_WRITE_ATTRIBUTES;
+
+#if defined(OS_WIN)
+ // On Windows, FILE_FLAG_BACKUP_SEMANTICS is needed to open a directory.
+ if (DirectoryExists(path))
+ flags |= File::FLAG_BACKUP_SEMANTICS;
+#endif // OS_WIN
+
+ File file(path, flags);
+ if (!file.IsValid())
+ return false;
+
+ return file.SetTimes(last_accessed, last_modified);
+}
+
+bool CloseFile(FILE* file) {
+ if (file == NULL)
+ return true;
+ return fclose(file) == 0;
+}
+
+bool TruncateFile(FILE* file) {
+ if (file == NULL)
+ return false;
+ long current_offset = ftell(file);
+ if (current_offset == -1)
+ return false;
+#if defined(OS_WIN)
+ int fd = _fileno(file);
+ if (_chsize(fd, current_offset) != 0)
+ return false;
+#else
+ int fd = fileno(file);
+ if (ftruncate(fd, current_offset) != 0)
+ return false;
+#endif
+ return true;
+}
+
+int GetUniquePathNumber(const FilePath& path,
+ const FilePath::StringType& suffix) {
+ bool have_suffix = !suffix.empty();
+ if (!PathExists(path) &&
+ (!have_suffix || !PathExists(FilePath(path.value() + suffix)))) {
+ return 0;
+ }
+
+ FilePath new_path;
+ for (int count = 1; count <= kMaxUniqueFiles; ++count) {
+ new_path = path.InsertBeforeExtensionASCII(StringPrintf(" (%d)", count));
+ if (!PathExists(new_path) &&
+ (!have_suffix || !PathExists(FilePath(new_path.value() + suffix)))) {
+ return count;
+ }
+ }
+
+ return -1;
+}
+
+} // namespace base
diff --git a/base/files/file_util.h b/base/files/file_util.h
new file mode 100644
index 0000000..feebeed
--- /dev/null
+++ b/base/files/file_util.h
@@ -0,0 +1,439 @@
+// Copyright (c) 2012 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// This file contains utility functions for dealing with the local
+// filesystem.
+
+#ifndef BASE_FILES_FILE_UTIL_H_
+#define BASE_FILES_FILE_UTIL_H_
+
+#include "build/build_config.h"
+
+#if defined(OS_WIN)
+#include <windows.h>
+#elif defined(OS_POSIX)
+#include <sys/stat.h>
+#include <unistd.h>
+#endif
+
+#include <stdio.h>
+
+#include <set>
+#include <string>
+#include <vector>
+
+#include "base/base_export.h"
+#include "base/basictypes.h"
+#include "base/files/file.h"
+#include "base/files/file_path.h"
+#include "base/memory/scoped_ptr.h"
+#include "base/strings/string16.h"
+
+#if defined(OS_POSIX)
+#include "base/file_descriptor_posix.h"
+#include "base/logging.h"
+#include "base/posix/eintr_wrapper.h"
+#endif
+
+namespace base {
+
+class Time;
+
+//-----------------------------------------------------------------------------
+// Functions that involve filesystem access or modification:
+
+// Returns an absolute version of a relative path. Returns an empty path on
+// error. On POSIX, this function fails if the path does not exist. This
+// function can result in I/O so it can be slow.
+BASE_EXPORT FilePath MakeAbsoluteFilePath(const FilePath& input);
+
+// Returns the total number of bytes used by all the files under |root_path|.
+// If the path does not exist the function returns 0.
+//
+// This function is implemented using the FileEnumerator class so it is not
+// particularly speedy in any platform.
+BASE_EXPORT int64 ComputeDirectorySize(const FilePath& root_path);
+
+// Deletes the given path, whether it's a file or a directory.
+// If it's a directory, it's perfectly happy to delete all of the
+// directory's contents. Passing true to recursive deletes
+// subdirectories and their contents as well.
+// Returns true if successful, false otherwise. It is considered successful
+// to attempt to delete a file that does not exist.
+//
+// In posix environment and if |path| is a symbolic link, this deletes only
+// the symlink. (even if the symlink points to a non-existent file)
+//
+// WARNING: USING THIS WITH recursive==true IS EQUIVALENT
+// TO "rm -rf", SO USE WITH CAUTION.
+BASE_EXPORT bool DeleteFile(const FilePath& path, bool recursive);
+
+#if defined(OS_WIN)
+// Schedules to delete the given path, whether it's a file or a directory, until
+// the operating system is restarted.
+// Note:
+// 1) The file/directory to be deleted should exist in a temp folder.
+// 2) The directory to be deleted must be empty.
+BASE_EXPORT bool DeleteFileAfterReboot(const FilePath& path);
+#endif
+
+// Moves the given path, whether it's a file or a directory.
+// If a simple rename is not possible, such as in the case where the paths are
+// on different volumes, this will attempt to copy and delete. Returns
+// true for success.
+// This function fails if either path contains traversal components ('..').
+BASE_EXPORT bool Move(const FilePath& from_path, const FilePath& to_path);
+
+// Renames file |from_path| to |to_path|. Both paths must be on the same
+// volume, or the function will fail. Destination file will be created
+// if it doesn't exist. Prefer this function over Move when dealing with
+// temporary files. On Windows it preserves attributes of the target file.
+// Returns true on success, leaving *error unchanged.
+// Returns false on failure and sets *error appropriately, if it is non-NULL.
+BASE_EXPORT bool ReplaceFile(const FilePath& from_path,
+ const FilePath& to_path,
+ File::Error* error);
+
+// Copies a single file. Use CopyDirectory to copy directories.
+// This function fails if either path contains traversal components ('..').
+//
+// This function keeps the metadata on Windows. The read only bit on Windows is
+// not kept.
+BASE_EXPORT bool CopyFile(const FilePath& from_path, const FilePath& to_path);
+
+// Copies the given path, and optionally all subdirectories and their contents
+// as well.
+//
+// If there are files existing under to_path, always overwrite. Returns true
+// if successful, false otherwise. Wildcards on the names are not supported.
+//
+// This function calls into CopyFile() so the same behavior w.r.t. metadata
+// applies.
+//
+// If you only need to copy a file use CopyFile, it's faster.
+BASE_EXPORT bool CopyDirectory(const FilePath& from_path,
+ const FilePath& to_path,
+ bool recursive);
+
+// Returns true if the given path exists on the local filesystem,
+// false otherwise.
+BASE_EXPORT bool PathExists(const FilePath& path);
+
+// Returns true if the given path is writable by the user, false otherwise.
+BASE_EXPORT bool PathIsWritable(const FilePath& path);
+
+// Returns true if the given path exists and is a directory, false otherwise.
+BASE_EXPORT bool DirectoryExists(const FilePath& path);
+
+// Returns true if the contents of the two files given are equal, false
+// otherwise. If either file can't be read, returns false.
+BASE_EXPORT bool ContentsEqual(const FilePath& filename1,
+ const FilePath& filename2);
+
+// Returns true if the contents of the two text files given are equal, false
+// otherwise. This routine treats "\r\n" and "\n" as equivalent.
+BASE_EXPORT bool TextContentsEqual(const FilePath& filename1,
+ const FilePath& filename2);
+
+// Reads the file at |path| into |contents| and returns true on success and
+// false on error. For security reasons, a |path| containing path traversal
+// components ('..') is treated as a read error and |contents| is set to empty.
+// In case of I/O error, |contents| holds the data that could be read from the
+// file before the error occurred.
+// |contents| may be NULL, in which case this function is useful for its side
+// effect of priming the disk cache (could be used for unit tests).
+BASE_EXPORT bool ReadFileToString(const FilePath& path, std::string* contents);
+
+// Reads the file at |path| into |contents| and returns true on success and
+// false on error. For security reasons, a |path| containing path traversal
+// components ('..') is treated as a read error and |contents| is set to empty.
+// In case of I/O error, |contents| holds the data that could be read from the
+// file before the error occurred. When the file size exceeds |max_size|, the
+// function returns false with |contents| holding the file truncated to
+// |max_size|.
+// |contents| may be NULL, in which case this function is useful for its side
+// effect of priming the disk cache (could be used for unit tests).
+BASE_EXPORT bool ReadFileToString(const FilePath& path,
+ std::string* contents,
+ size_t max_size);
+
+#if defined(OS_POSIX)
+
+// Read exactly |bytes| bytes from file descriptor |fd|, storing the result
+// in |buffer|. This function is protected against EINTR and partial reads.
+// Returns true iff |bytes| bytes have been successfully read from |fd|.
+BASE_EXPORT bool ReadFromFD(int fd, char* buffer, size_t bytes);
+
+// Creates a symbolic link at |symlink| pointing to |target|. Returns
+// false on failure.
+BASE_EXPORT bool CreateSymbolicLink(const FilePath& target,
+ const FilePath& symlink);
+
+// Reads the given |symlink| and returns where it points to in |target|.
+// Returns false upon failure.
+BASE_EXPORT bool ReadSymbolicLink(const FilePath& symlink, FilePath* target);
+
+// Bits and masks of the file permission.
+enum FilePermissionBits {
+ FILE_PERMISSION_MASK = S_IRWXU | S_IRWXG | S_IRWXO,
+ FILE_PERMISSION_USER_MASK = S_IRWXU,
+ FILE_PERMISSION_GROUP_MASK = S_IRWXG,
+ FILE_PERMISSION_OTHERS_MASK = S_IRWXO,
+
+ FILE_PERMISSION_READ_BY_USER = S_IRUSR,
+ FILE_PERMISSION_WRITE_BY_USER = S_IWUSR,
+ FILE_PERMISSION_EXECUTE_BY_USER = S_IXUSR,
+ FILE_PERMISSION_READ_BY_GROUP = S_IRGRP,
+ FILE_PERMISSION_WRITE_BY_GROUP = S_IWGRP,
+ FILE_PERMISSION_EXECUTE_BY_GROUP = S_IXGRP,
+ FILE_PERMISSION_READ_BY_OTHERS = S_IROTH,
+ FILE_PERMISSION_WRITE_BY_OTHERS = S_IWOTH,
+ FILE_PERMISSION_EXECUTE_BY_OTHERS = S_IXOTH,
+};
+
+// Reads the permission of the given |path|, storing the file permission
+// bits in |mode|. If |path| is symbolic link, |mode| is the permission of
+// a file which the symlink points to.
+BASE_EXPORT bool GetPosixFilePermissions(const FilePath& path, int* mode);
+// Sets the permission of the given |path|. If |path| is symbolic link, sets
+// the permission of a file which the symlink points to.
+BASE_EXPORT bool SetPosixFilePermissions(const FilePath& path, int mode);
+
+#endif // OS_POSIX
+
+// Returns true if the given directory is empty
+BASE_EXPORT bool IsDirectoryEmpty(const FilePath& dir_path);
+
+// Get the temporary directory provided by the system.
+//
+// WARNING: In general, you should use CreateTemporaryFile variants below
+// instead of this function. Those variants will ensure that the proper
+// permissions are set so that other users on the system can't edit them while
+// they're open (which can lead to security issues).
+BASE_EXPORT bool GetTempDir(FilePath* path);
+
+// Get the home directory. This is more complicated than just getenv("HOME")
+// as it knows to fall back on getpwent() etc.
+//
+// You should not generally call this directly. Instead use DIR_HOME with the
+// path service which will use this function but cache the value.
+// Path service may also override DIR_HOME.
+BASE_EXPORT FilePath GetHomeDir();
+
+// Creates a temporary file. The full path is placed in |path|, and the
+// function returns true if was successful in creating the file. The file will
+// be empty and all handles closed after this function returns.
+BASE_EXPORT bool CreateTemporaryFile(FilePath* path);
+
+// Same as CreateTemporaryFile but the file is created in |dir|.
+BASE_EXPORT bool CreateTemporaryFileInDir(const FilePath& dir,
+ FilePath* temp_file);
+
+// Create and open a temporary file. File is opened for read/write.
+// The full path is placed in |path|.
+// Returns a handle to the opened file or NULL if an error occurred.
+BASE_EXPORT FILE* CreateAndOpenTemporaryFile(FilePath* path);
+
+// Similar to CreateAndOpenTemporaryFile, but the file is created in |dir|.
+BASE_EXPORT FILE* CreateAndOpenTemporaryFileInDir(const FilePath& dir,
+ FilePath* path);
+
+// Create a new directory. If prefix is provided, the new directory name is in
+// the format of prefixyyyy.
+// NOTE: prefix is ignored in the POSIX implementation.
+// If success, return true and output the full path of the directory created.
+BASE_EXPORT bool CreateNewTempDirectory(const FilePath::StringType& prefix,
+ FilePath* new_temp_path);
+
+// Create a directory within another directory.
+// Extra characters will be appended to |prefix| to ensure that the
+// new directory does not have the same name as an existing directory.
+BASE_EXPORT bool CreateTemporaryDirInDir(const FilePath& base_dir,
+ const FilePath::StringType& prefix,
+ FilePath* new_dir);
+
+// Creates a directory, as well as creating any parent directories, if they
+// don't exist. Returns 'true' on successful creation, or if the directory
+// already exists. The directory is only readable by the current user.
+// Returns true on success, leaving *error unchanged.
+// Returns false on failure and sets *error appropriately, if it is non-NULL.
+BASE_EXPORT bool CreateDirectoryAndGetError(const FilePath& full_path,
+ File::Error* error);
+
+// Backward-compatible convenience method for the above.
+BASE_EXPORT bool CreateDirectory(const FilePath& full_path);
+
+// Returns the file size. Returns true on success.
+BASE_EXPORT bool GetFileSize(const FilePath& file_path, int64* file_size);
+
+// Sets |real_path| to |path| with symbolic links and junctions expanded.
+// On windows, make sure the path starts with a lettered drive.
+// |path| must reference a file. Function will fail if |path| points to
+// a directory or to a nonexistent path. On windows, this function will
+// fail if |path| is a junction or symlink that points to an empty file,
+// or if |real_path| would be longer than MAX_PATH characters.
+BASE_EXPORT bool NormalizeFilePath(const FilePath& path, FilePath* real_path);
+
+#if defined(OS_WIN)
+
+// Given a path in NT native form ("\Device\HarddiskVolumeXX\..."),
+// return in |drive_letter_path| the equivalent path that starts with
+// a drive letter ("C:\..."). Return false if no such path exists.
+BASE_EXPORT bool DevicePathToDriveLetterPath(const FilePath& device_path,
+ FilePath* drive_letter_path);
+
+// Given an existing file in |path|, set |real_path| to the path
+// in native NT format, of the form "\Device\HarddiskVolumeXX\..".
+// Returns false if the path can not be found. Empty files cannot
+// be resolved with this function.
+BASE_EXPORT bool NormalizeToNativeFilePath(const FilePath& path,
+ FilePath* nt_path);
+#endif
+
+// This function will return if the given file is a symlink or not.
+BASE_EXPORT bool IsLink(const FilePath& file_path);
+
+// Returns information about the given file path.
+BASE_EXPORT bool GetFileInfo(const FilePath& file_path, File::Info* info);
+
+// Sets the time of the last access and the time of the last modification.
+BASE_EXPORT bool TouchFile(const FilePath& path,
+ const Time& last_accessed,
+ const Time& last_modified);
+
+// Wrapper for fopen-like calls. Returns non-NULL FILE* on success.
+BASE_EXPORT FILE* OpenFile(const FilePath& filename, const char* mode);
+
+// Closes file opened by OpenFile. Returns true on success.
+BASE_EXPORT bool CloseFile(FILE* file);
+
+// Associates a standard FILE stream with an existing File. Note that this
+// functions take ownership of the existing File.
+BASE_EXPORT FILE* FileToFILE(File file, const char* mode);
+
+// Truncates an open file to end at the location of the current file pointer.
+// This is a cross-platform analog to Windows' SetEndOfFile() function.
+BASE_EXPORT bool TruncateFile(FILE* file);
+
+// Reads at most the given number of bytes from the file into the buffer.
+// Returns the number of read bytes, or -1 on error.
+BASE_EXPORT int ReadFile(const FilePath& filename, char* data, int max_size);
+
+// Writes the given buffer into the file, overwriting any data that was
+// previously there. Returns the number of bytes written, or -1 on error.
+BASE_EXPORT int WriteFile(const FilePath& filename, const char* data,
+ int size);
+
+#if defined(OS_POSIX)
+// Append the data to |fd|. Does not close |fd| when done.
+BASE_EXPORT int WriteFileDescriptor(const int fd, const char* data, int size);
+#endif
+
+// Append the given buffer into the file. Returns the number of bytes written,
+// or -1 on error.
+BASE_EXPORT int AppendToFile(const FilePath& filename,
+ const char* data, int size);
+
+// Gets the current working directory for the process.
+BASE_EXPORT bool GetCurrentDirectory(FilePath* path);
+
+// Sets the current working directory for the process.
+BASE_EXPORT bool SetCurrentDirectory(const FilePath& path);
+
+// Attempts to find a number that can be appended to the |path| to make it
+// unique. If |path| does not exist, 0 is returned. If it fails to find such
+// a number, -1 is returned. If |suffix| is not empty, also checks the
+// existence of it with the given suffix.
+BASE_EXPORT int GetUniquePathNumber(const FilePath& path,
+ const FilePath::StringType& suffix);
+
+#if defined(OS_POSIX)
+// Test that |path| can only be changed by a given user and members of
+// a given set of groups.
+// Specifically, test that all parts of |path| under (and including) |base|:
+// * Exist.
+// * Are owned by a specific user.
+// * Are not writable by all users.
+// * Are owned by a member of a given set of groups, or are not writable by
+// their group.
+// * Are not symbolic links.
+// This is useful for checking that a config file is administrator-controlled.
+// |base| must contain |path|.
+BASE_EXPORT bool VerifyPathControlledByUser(const base::FilePath& base,
+ const base::FilePath& path,
+ uid_t owner_uid,
+ const std::set<gid_t>& group_gids);
+#endif // defined(OS_POSIX)
+
+#if defined(OS_MACOSX) && !defined(OS_IOS)
+// Is |path| writable only by a user with administrator privileges?
+// This function uses Mac OS conventions. The super user is assumed to have
+// uid 0, and the administrator group is assumed to be named "admin".
+// Testing that |path|, and every parent directory including the root of
+// the filesystem, are owned by the superuser, controlled by the group
+// "admin", are not writable by all users, and contain no symbolic links.
+// Will return false if |path| does not exist.
+BASE_EXPORT bool VerifyPathControlledByAdmin(const base::FilePath& path);
+#endif // defined(OS_MACOSX) && !defined(OS_IOS)
+
+// Returns the maximum length of path component on the volume containing
+// the directory |path|, in the number of FilePath::CharType, or -1 on failure.
+BASE_EXPORT int GetMaximumPathComponentLength(const base::FilePath& path);
+
+#if defined(OS_LINUX)
+// Broad categories of file systems as returned by statfs() on Linux.
+enum FileSystemType {
+ FILE_SYSTEM_UNKNOWN, // statfs failed.
+ FILE_SYSTEM_0, // statfs.f_type == 0 means unknown, may indicate AFS.
+ FILE_SYSTEM_ORDINARY, // on-disk filesystem like ext2
+ FILE_SYSTEM_NFS,
+ FILE_SYSTEM_SMB,
+ FILE_SYSTEM_CODA,
+ FILE_SYSTEM_MEMORY, // in-memory file system
+ FILE_SYSTEM_CGROUP, // cgroup control.
+ FILE_SYSTEM_OTHER, // any other value.
+ FILE_SYSTEM_TYPE_COUNT
+};
+
+// Attempts determine the FileSystemType for |path|.
+// Returns false if |path| doesn't exist.
+BASE_EXPORT bool GetFileSystemType(const FilePath& path, FileSystemType* type);
+#endif
+
+#if defined(OS_POSIX)
+// Get a temporary directory for shared memory files. The directory may depend
+// on whether the destination is intended for executable files, which in turn
+// depends on how /dev/shmem was mounted. As a result, you must supply whether
+// you intend to create executable shmem segments so this function can find
+// an appropriate location.
+BASE_EXPORT bool GetShmemTempDir(bool executable, FilePath* path);
+#endif
+
+// Internal --------------------------------------------------------------------
+
+namespace internal {
+
+// Same as Move but allows paths with traversal components.
+// Use only with extreme care.
+BASE_EXPORT bool MoveUnsafe(const FilePath& from_path,
+ const FilePath& to_path);
+
+// Same as CopyFile but allows paths with traversal components.
+// Use only with extreme care.
+BASE_EXPORT bool CopyFileUnsafe(const FilePath& from_path,
+ const FilePath& to_path);
+
+#if defined(OS_WIN)
+// Copy from_path to to_path recursively and then delete from_path recursively.
+// Returns true if all operations succeed.
+// This function simulates Move(), but unlike Move() it works across volumes.
+// This function is not transactional.
+BASE_EXPORT bool CopyAndDeleteDirectory(const FilePath& from_path,
+ const FilePath& to_path);
+#endif // defined(OS_WIN)
+
+} // namespace internal
+} // namespace base
+
+#endif // BASE_FILES_FILE_UTIL_H_
diff --git a/base/files/file_util_android.cc b/base/files/file_util_android.cc
new file mode 100644
index 0000000..b8b3b37
--- /dev/null
+++ b/base/files/file_util_android.cc
@@ -0,0 +1,16 @@
+// Copyright (c) 2012 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "base/files/file_util.h"
+
+#include "base/files/file_path.h"
+#include "base/path_service.h"
+
+namespace base {
+
+bool GetShmemTempDir(bool executable, base::FilePath* path) {
+ return PathService::Get(base::DIR_CACHE, path);
+}
+
+} // namespace base
diff --git a/base/files/file_util_linux.cc b/base/files/file_util_linux.cc
new file mode 100644
index 0000000..532962f
--- /dev/null
+++ b/base/files/file_util_linux.cc
@@ -0,0 +1,78 @@
+// Copyright (c) 2011 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "base/files/file_util.h"
+
+#include <errno.h>
+#include <linux/magic.h>
+#include <sys/vfs.h>
+
+#include "base/files/file_path.h"
+
+// Make sure some of the newer macros from magic.h are defined.
+// TODO(mostynb@opera.com): remove this after 2014.
+#ifndef BTRFS_SUPER_MAGIC
+#define BTRFS_SUPER_MAGIC 0x9123683E
+#endif
+#ifndef HUGETLBFS_MAGIC
+#define HUGETLBFS_MAGIC 0x958458f6
+#endif
+#ifndef RAMFS_MAGIC
+#define RAMFS_MAGIC 0x858458f6
+#endif
+#ifndef TMPFS_MAGIC
+#define TMPFS_MAGIC 0x01021994
+#endif
+
+namespace base {
+
+bool GetFileSystemType(const FilePath& path, FileSystemType* type) {
+ struct statfs statfs_buf;
+ if (statfs(path.value().c_str(), &statfs_buf) < 0) {
+ if (errno == ENOENT)
+ return false;
+ *type = FILE_SYSTEM_UNKNOWN;
+ return true;
+ }
+
+ // Not all possible |statfs_buf.f_type| values are in linux/magic.h.
+ // Missing values are copied from the statfs man page.
+ switch (statfs_buf.f_type) {
+ case 0:
+ *type = FILE_SYSTEM_0;
+ break;
+ case EXT2_SUPER_MAGIC: // Also ext3 and ext4
+ case MSDOS_SUPER_MAGIC:
+ case REISERFS_SUPER_MAGIC:
+ case BTRFS_SUPER_MAGIC:
+ case 0x5346544E: // NTFS
+ case 0x58465342: // XFS
+ case 0x3153464A: // JFS
+ *type = FILE_SYSTEM_ORDINARY;
+ break;
+ case NFS_SUPER_MAGIC:
+ *type = FILE_SYSTEM_NFS;
+ break;
+ case SMB_SUPER_MAGIC:
+ case 0xFF534D42: // CIFS
+ *type = FILE_SYSTEM_SMB;
+ break;
+ case CODA_SUPER_MAGIC:
+ *type = FILE_SYSTEM_CODA;
+ break;
+ case HUGETLBFS_MAGIC:
+ case RAMFS_MAGIC:
+ case TMPFS_MAGIC:
+ *type = FILE_SYSTEM_MEMORY;
+ break;
+ case CGROUP_SUPER_MAGIC:
+ *type = FILE_SYSTEM_CGROUP;
+ break;
+ default:
+ *type = FILE_SYSTEM_OTHER;
+ }
+ return true;
+}
+
+} // namespace base
diff --git a/base/files/file_util_mac.mm b/base/files/file_util_mac.mm
new file mode 100644
index 0000000..695935a
--- /dev/null
+++ b/base/files/file_util_mac.mm
@@ -0,0 +1,52 @@
+// Copyright (c) 2012 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "base/files/file_util.h"
+
+#import <Foundation/Foundation.h>
+#include <copyfile.h>
+
+#include "base/basictypes.h"
+#include "base/files/file_path.h"
+#include "base/mac/foundation_util.h"
+#include "base/strings/string_util.h"
+#include "base/threading/thread_restrictions.h"
+
+namespace base {
+namespace internal {
+
+bool CopyFileUnsafe(const FilePath& from_path, const FilePath& to_path) {
+ ThreadRestrictions::AssertIOAllowed();
+ return (copyfile(from_path.value().c_str(),
+ to_path.value().c_str(), NULL, COPYFILE_DATA) == 0);
+}
+
+} // namespace internal
+
+bool GetTempDir(base::FilePath* path) {
+ NSString* tmp = NSTemporaryDirectory();
+ if (tmp == nil)
+ return false;
+ *path = base::mac::NSStringToFilePath(tmp);
+ return true;
+}
+
+FilePath GetHomeDir() {
+ NSString* tmp = NSHomeDirectory();
+ if (tmp != nil) {
+ FilePath mac_home_dir = base::mac::NSStringToFilePath(tmp);
+ if (!mac_home_dir.empty())
+ return mac_home_dir;
+ }
+
+ // Fall back on temp dir if no home directory is defined.
+ FilePath rv;
+ if (GetTempDir(&rv))
+ return rv;
+
+ // Last resort.
+ return FilePath("/tmp");
+}
+
+} // namespace base
diff --git a/base/files/file_util_posix.cc b/base/files/file_util_posix.cc
new file mode 100644
index 0000000..07c21d1
--- /dev/null
+++ b/base/files/file_util_posix.cc
@@ -0,0 +1,912 @@
+// Copyright (c) 2012 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "base/files/file_util.h"
+
+#include <dirent.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <libgen.h>
+#include <limits.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/errno.h>
+#include <sys/mman.h>
+#include <sys/param.h>
+#include <sys/stat.h>
+#include <sys/time.h>
+#include <sys/types.h>
+#include <time.h>
+#include <unistd.h>
+
+#if defined(OS_MACOSX)
+#include <AvailabilityMacros.h>
+#include "base/mac/foundation_util.h"
+#elif !defined(OS_CHROMEOS) && defined(USE_GLIB)
+#include <glib.h> // for g_get_home_dir()
+#endif
+
+#include <fstream>
+
+#include "base/basictypes.h"
+#include "base/files/file_enumerator.h"
+#include "base/files/file_path.h"
+#include "base/files/scoped_file.h"
+#include "base/logging.h"
+#include "base/memory/scoped_ptr.h"
+#include "base/memory/singleton.h"
+#include "base/path_service.h"
+#include "base/posix/eintr_wrapper.h"
+#include "base/stl_util.h"
+#include "base/strings/string_util.h"
+#include "base/strings/stringprintf.h"
+#include "base/strings/sys_string_conversions.h"
+#include "base/strings/utf_string_conversions.h"
+#include "base/sys_info.h"
+#include "base/threading/thread_restrictions.h"
+#include "base/time/time.h"
+
+#if defined(OS_ANDROID)
+#include "base/android/content_uri_utils.h"
+#include "base/os_compat_android.h"
+#endif
+
+#if !defined(OS_IOS)
+#include <grp.h>
+#endif
+
+namespace base {
+
+namespace {
+
+#if defined(OS_BSD) || defined(OS_MACOSX) || defined(OS_NACL)
+static int CallStat(const char *path, stat_wrapper_t *sb) {
+ ThreadRestrictions::AssertIOAllowed();
+ return stat(path, sb);
+}
+static int CallLstat(const char *path, stat_wrapper_t *sb) {
+ ThreadRestrictions::AssertIOAllowed();
+ return lstat(path, sb);
+}
+#else // defined(OS_BSD) || defined(OS_MACOSX) || defined(OS_NACL)
+static int CallStat(const char *path, stat_wrapper_t *sb) {
+ ThreadRestrictions::AssertIOAllowed();
+ return stat64(path, sb);
+}
+static int CallLstat(const char *path, stat_wrapper_t *sb) {
+ ThreadRestrictions::AssertIOAllowed();
+ return lstat64(path, sb);
+}
+#endif // !(defined(OS_BSD) || defined(OS_MACOSX) || defined(OS_NACL))
+
+// Helper for NormalizeFilePath(), defined below.
+bool RealPath(const FilePath& path, FilePath* real_path) {
+ ThreadRestrictions::AssertIOAllowed(); // For realpath().
+ FilePath::CharType buf[PATH_MAX];
+ if (!realpath(path.value().c_str(), buf))
+ return false;
+
+ *real_path = FilePath(buf);
+ return true;
+}
+
+// Helper for VerifyPathControlledByUser.
+bool VerifySpecificPathControlledByUser(const FilePath& path,
+ uid_t owner_uid,
+ const std::set<gid_t>& group_gids) {
+ stat_wrapper_t stat_info;
+ if (CallLstat(path.value().c_str(), &stat_info) != 0) {
+ DPLOG(ERROR) << "Failed to get information on path "
+ << path.value();
+ return false;
+ }
+
+ if (S_ISLNK(stat_info.st_mode)) {
+ DLOG(ERROR) << "Path " << path.value()
+ << " is a symbolic link.";
+ return false;
+ }
+
+ if (stat_info.st_uid != owner_uid) {
+ DLOG(ERROR) << "Path " << path.value()
+ << " is owned by the wrong user.";
+ return false;
+ }
+
+ if ((stat_info.st_mode & S_IWGRP) &&
+ !ContainsKey(group_gids, stat_info.st_gid)) {
+ DLOG(ERROR) << "Path " << path.value()
+ << " is writable by an unprivileged group.";
+ return false;
+ }
+
+ if (stat_info.st_mode & S_IWOTH) {
+ DLOG(ERROR) << "Path " << path.value()
+ << " is writable by any user.";
+ return false;
+ }
+
+ return true;
+}
+
+std::string TempFileName() {
+#if defined(OS_MACOSX)
+ return StringPrintf(".%s.XXXXXX", base::mac::BaseBundleID());
+#endif
+
+#if defined(GOOGLE_CHROME_BUILD)
+ return std::string(".com.google.Chrome.XXXXXX");
+#else
+ return std::string(".org.chromium.Chromium.XXXXXX");
+#endif
+}
+
+// Creates and opens a temporary file in |directory|, returning the
+// file descriptor. |path| is set to the temporary file path.
+// This function does NOT unlink() the file.
+int CreateAndOpenFdForTemporaryFile(FilePath directory, FilePath* path) {
+ ThreadRestrictions::AssertIOAllowed(); // For call to mkstemp().
+ *path = directory.Append(base::TempFileName());
+ const std::string& tmpdir_string = path->value();
+ // this should be OK since mkstemp just replaces characters in place
+ char* buffer = const_cast<char*>(tmpdir_string.c_str());
+
+ return HANDLE_EINTR(mkstemp(buffer));
+}
+
+#if defined(OS_LINUX)
+// Determine if /dev/shm files can be mapped and then mprotect'd PROT_EXEC.
+// This depends on the mount options used for /dev/shm, which vary among
+// different Linux distributions and possibly local configuration. It also
+// depends on details of kernel--ChromeOS uses the noexec option for /dev/shm
+// but its kernel allows mprotect with PROT_EXEC anyway.
+bool DetermineDevShmExecutable() {
+ bool result = false;
+ FilePath path;
+
+ ScopedFD fd(CreateAndOpenFdForTemporaryFile(FilePath("/dev/shm"), &path));
+ if (fd.is_valid()) {
+ DeleteFile(path, false);
+ long sysconf_result = sysconf(_SC_PAGESIZE);
+ CHECK_GE(sysconf_result, 0);
+ size_t pagesize = static_cast<size_t>(sysconf_result);
+ CHECK_GE(sizeof(pagesize), sizeof(sysconf_result));
+ void* mapping = mmap(NULL, pagesize, PROT_READ, MAP_SHARED, fd.get(), 0);
+ if (mapping != MAP_FAILED) {
+ if (mprotect(mapping, pagesize, PROT_READ | PROT_EXEC) == 0)
+ result = true;
+ munmap(mapping, pagesize);
+ }
+ }
+ return result;
+}
+#endif // defined(OS_LINUX)
+
+} // namespace
+
+FilePath MakeAbsoluteFilePath(const FilePath& input) {
+ ThreadRestrictions::AssertIOAllowed();
+ char full_path[PATH_MAX];
+ if (realpath(input.value().c_str(), full_path) == NULL)
+ return FilePath();
+ return FilePath(full_path);
+}
+
+// TODO(erikkay): The Windows version of this accepts paths like "foo/bar/*"
+// which works both with and without the recursive flag. I'm not sure we need
+// that functionality. If not, remove from file_util_win.cc, otherwise add it
+// here.
+bool DeleteFile(const FilePath& path, bool recursive) {
+ ThreadRestrictions::AssertIOAllowed();
+ const char* path_str = path.value().c_str();
+ stat_wrapper_t file_info;
+ int test = CallLstat(path_str, &file_info);
+ if (test != 0) {
+ // The Windows version defines this condition as success.
+ bool ret = (errno == ENOENT || errno == ENOTDIR);
+ return ret;
+ }
+ if (!S_ISDIR(file_info.st_mode))
+ return (unlink(path_str) == 0);
+ if (!recursive)
+ return (rmdir(path_str) == 0);
+
+ bool success = true;
+ std::stack<std::string> directories;
+ directories.push(path.value());
+ FileEnumerator traversal(path, true,
+ FileEnumerator::FILES | FileEnumerator::DIRECTORIES |
+ FileEnumerator::SHOW_SYM_LINKS);
+ for (FilePath current = traversal.Next(); success && !current.empty();
+ current = traversal.Next()) {
+ if (traversal.GetInfo().IsDirectory())
+ directories.push(current.value());
+ else
+ success = (unlink(current.value().c_str()) == 0);
+ }
+
+ while (success && !directories.empty()) {
+ FilePath dir = FilePath(directories.top());
+ directories.pop();
+ success = (rmdir(dir.value().c_str()) == 0);
+ }
+ return success;
+}
+
+bool ReplaceFile(const FilePath& from_path,
+ const FilePath& to_path,
+ File::Error* error) {
+ ThreadRestrictions::AssertIOAllowed();
+ if (rename(from_path.value().c_str(), to_path.value().c_str()) == 0)
+ return true;
+ if (error)
+ *error = File::OSErrorToFileError(errno);
+ return false;
+}
+
+bool CopyDirectory(const FilePath& from_path,
+ const FilePath& to_path,
+ bool recursive) {
+ ThreadRestrictions::AssertIOAllowed();
+ // Some old callers of CopyDirectory want it to support wildcards.
+ // After some discussion, we decided to fix those callers.
+ // Break loudly here if anyone tries to do this.
+ DCHECK(to_path.value().find('*') == std::string::npos);
+ DCHECK(from_path.value().find('*') == std::string::npos);
+
+ if (from_path.value().size() >= PATH_MAX) {
+ return false;
+ }
+
+ // This function does not properly handle destinations within the source
+ FilePath real_to_path = to_path;
+ if (PathExists(real_to_path)) {
+ real_to_path = MakeAbsoluteFilePath(real_to_path);
+ if (real_to_path.empty())
+ return false;
+ } else {
+ real_to_path = MakeAbsoluteFilePath(real_to_path.DirName());
+ if (real_to_path.empty())
+ return false;
+ }
+ FilePath real_from_path = MakeAbsoluteFilePath(from_path);
+ if (real_from_path.empty())
+ return false;
+ if (real_to_path.value().size() >= real_from_path.value().size() &&
+ real_to_path.value().compare(0, real_from_path.value().size(),
+ real_from_path.value()) == 0) {
+ return false;
+ }
+
+ int traverse_type = FileEnumerator::FILES | FileEnumerator::SHOW_SYM_LINKS;
+ if (recursive)
+ traverse_type |= FileEnumerator::DIRECTORIES;
+ FileEnumerator traversal(from_path, recursive, traverse_type);
+
+ // We have to mimic windows behavior here. |to_path| may not exist yet,
+ // start the loop with |to_path|.
+ struct stat from_stat;
+ FilePath current = from_path;
+ if (stat(from_path.value().c_str(), &from_stat) < 0) {
+ DLOG(ERROR) << "CopyDirectory() couldn't stat source directory: "
+ << from_path.value() << " errno = " << errno;
+ return false;
+ }
+ struct stat to_path_stat;
+ FilePath from_path_base = from_path;
+ if (recursive && stat(to_path.value().c_str(), &to_path_stat) == 0 &&
+ S_ISDIR(to_path_stat.st_mode)) {
+ // If the destination already exists and is a directory, then the
+ // top level of source needs to be copied.
+ from_path_base = from_path.DirName();
+ }
+
+ // The Windows version of this function assumes that non-recursive calls
+ // will always have a directory for from_path.
+ // TODO(maruel): This is not necessary anymore.
+ DCHECK(recursive || S_ISDIR(from_stat.st_mode));
+
+ bool success = true;
+ while (success && !current.empty()) {
+ // current is the source path, including from_path, so append
+ // the suffix after from_path to to_path to create the target_path.
+ FilePath target_path(to_path);
+ if (from_path_base != current) {
+ if (!from_path_base.AppendRelativePath(current, &target_path)) {
+ success = false;
+ break;
+ }
+ }
+
+ if (S_ISDIR(from_stat.st_mode)) {
+ if (mkdir(target_path.value().c_str(), from_stat.st_mode & 01777) != 0 &&
+ errno != EEXIST) {
+ DLOG(ERROR) << "CopyDirectory() couldn't create directory: "
+ << target_path.value() << " errno = " << errno;
+ success = false;
+ }
+ } else if (S_ISREG(from_stat.st_mode)) {
+ if (!CopyFile(current, target_path)) {
+ DLOG(ERROR) << "CopyDirectory() couldn't create file: "
+ << target_path.value();
+ success = false;
+ }
+ } else {
+ DLOG(WARNING) << "CopyDirectory() skipping non-regular file: "
+ << current.value();
+ }
+
+ current = traversal.Next();
+ if (!current.empty())
+ from_stat = traversal.GetInfo().stat();
+ }
+
+ return success;
+}
+
+bool PathExists(const FilePath& path) {
+ ThreadRestrictions::AssertIOAllowed();
+#if defined(OS_ANDROID)
+ if (path.IsContentUri()) {
+ return ContentUriExists(path);
+ }
+#endif
+ return access(path.value().c_str(), F_OK) == 0;
+}
+
+bool PathIsWritable(const FilePath& path) {
+ ThreadRestrictions::AssertIOAllowed();
+ return access(path.value().c_str(), W_OK) == 0;
+}
+
+bool DirectoryExists(const FilePath& path) {
+ ThreadRestrictions::AssertIOAllowed();
+ stat_wrapper_t file_info;
+ if (CallStat(path.value().c_str(), &file_info) == 0)
+ return S_ISDIR(file_info.st_mode);
+ return false;
+}
+
+bool ReadFromFD(int fd, char* buffer, size_t bytes) {
+ size_t total_read = 0;
+ while (total_read < bytes) {
+ ssize_t bytes_read =
+ HANDLE_EINTR(read(fd, buffer + total_read, bytes - total_read));
+ if (bytes_read <= 0)
+ break;
+ total_read += bytes_read;
+ }
+ return total_read == bytes;
+}
+
+bool CreateSymbolicLink(const FilePath& target_path,
+ const FilePath& symlink_path) {
+ DCHECK(!symlink_path.empty());
+ DCHECK(!target_path.empty());
+ return ::symlink(target_path.value().c_str(),
+ symlink_path.value().c_str()) != -1;
+}
+
+bool ReadSymbolicLink(const FilePath& symlink_path, FilePath* target_path) {
+ DCHECK(!symlink_path.empty());
+ DCHECK(target_path);
+ char buf[PATH_MAX];
+ ssize_t count = ::readlink(symlink_path.value().c_str(), buf, arraysize(buf));
+
+ if (count <= 0) {
+ target_path->clear();
+ return false;
+ }
+
+ *target_path = FilePath(FilePath::StringType(buf, count));
+ return true;
+}
+
+bool GetPosixFilePermissions(const FilePath& path, int* mode) {
+ ThreadRestrictions::AssertIOAllowed();
+ DCHECK(mode);
+
+ stat_wrapper_t file_info;
+ // Uses stat(), because on symbolic link, lstat() does not return valid
+ // permission bits in st_mode
+ if (CallStat(path.value().c_str(), &file_info) != 0)
+ return false;
+
+ *mode = file_info.st_mode & FILE_PERMISSION_MASK;
+ return true;
+}
+
+bool SetPosixFilePermissions(const FilePath& path,
+ int mode) {
+ ThreadRestrictions::AssertIOAllowed();
+ DCHECK((mode & ~FILE_PERMISSION_MASK) == 0);
+
+ // Calls stat() so that we can preserve the higher bits like S_ISGID.
+ stat_wrapper_t stat_buf;
+ if (CallStat(path.value().c_str(), &stat_buf) != 0)
+ return false;
+
+ // Clears the existing permission bits, and adds the new ones.
+ mode_t updated_mode_bits = stat_buf.st_mode & ~FILE_PERMISSION_MASK;
+ updated_mode_bits |= mode & FILE_PERMISSION_MASK;
+
+ if (HANDLE_EINTR(chmod(path.value().c_str(), updated_mode_bits)) != 0)
+ return false;
+
+ return true;
+}
+
+#if !defined(OS_MACOSX)
+// This is implemented in file_util_mac.mm for Mac.
+bool GetTempDir(FilePath* path) {
+ const char* tmp = getenv("TMPDIR");
+ if (tmp) {
+ *path = FilePath(tmp);
+ } else {
+#if defined(OS_ANDROID)
+ return PathService::Get(base::DIR_CACHE, path);
+#else
+ *path = FilePath("/tmp");
+#endif
+ }
+ return true;
+}
+#endif // !defined(OS_MACOSX)
+
+#if !defined(OS_MACOSX) // Mac implementation is in file_util_mac.mm.
+FilePath GetHomeDir() {
+#if defined(OS_CHROMEOS)
+ if (SysInfo::IsRunningOnChromeOS()) {
+ // On Chrome OS chrome::DIR_USER_DATA is overridden with a primary user
+ // homedir once it becomes available. Return / as the safe option.
+ return FilePath("/");
+ }
+#endif
+
+ const char* home_dir = getenv("HOME");
+ if (home_dir && home_dir[0])
+ return FilePath(home_dir);
+
+#if defined(OS_ANDROID)
+ DLOG(WARNING) << "OS_ANDROID: Home directory lookup not yet implemented.";
+#elif defined(USE_GLIB) && !defined(OS_CHROMEOS)
+ // g_get_home_dir calls getpwent, which can fall through to LDAP calls so
+ // this may do I/O. However, it should be rare that $HOME is not defined and
+ // this is typically called from the path service which has no threading
+ // restrictions. The path service will cache the result which limits the
+ // badness of blocking on I/O. As a result, we don't have a thread
+ // restriction here.
+ home_dir = g_get_home_dir();
+ if (home_dir && home_dir[0])
+ return FilePath(home_dir);
+#endif
+
+ FilePath rv;
+ if (GetTempDir(&rv))
+ return rv;
+
+ // Last resort.
+ return FilePath("/tmp");
+}
+#endif // !defined(OS_MACOSX)
+
+bool CreateTemporaryFile(FilePath* path) {
+ ThreadRestrictions::AssertIOAllowed(); // For call to close().
+ FilePath directory;
+ if (!GetTempDir(&directory))
+ return false;
+ int fd = CreateAndOpenFdForTemporaryFile(directory, path);
+ if (fd < 0)
+ return false;
+ close(fd);
+ return true;
+}
+
+FILE* CreateAndOpenTemporaryFileInDir(const FilePath& dir, FilePath* path) {
+ int fd = CreateAndOpenFdForTemporaryFile(dir, path);
+ if (fd < 0)
+ return NULL;
+
+ FILE* file = fdopen(fd, "a+");
+ if (!file)
+ close(fd);
+ return file;
+}
+
+bool CreateTemporaryFileInDir(const FilePath& dir, FilePath* temp_file) {
+ ThreadRestrictions::AssertIOAllowed(); // For call to close().
+ int fd = CreateAndOpenFdForTemporaryFile(dir, temp_file);
+ return ((fd >= 0) && !IGNORE_EINTR(close(fd)));
+}
+
+static bool CreateTemporaryDirInDirImpl(const FilePath& base_dir,
+ const FilePath::StringType& name_tmpl,
+ FilePath* new_dir) {
+ ThreadRestrictions::AssertIOAllowed(); // For call to mkdtemp().
+ DCHECK(name_tmpl.find("XXXXXX") != FilePath::StringType::npos)
+ << "Directory name template must contain \"XXXXXX\".";
+
+ FilePath sub_dir = base_dir.Append(name_tmpl);
+ std::string sub_dir_string = sub_dir.value();
+
+ // this should be OK since mkdtemp just replaces characters in place
+ char* buffer = const_cast<char*>(sub_dir_string.c_str());
+ char* dtemp = mkdtemp(buffer);
+ if (!dtemp) {
+ DPLOG(ERROR) << "mkdtemp";
+ return false;
+ }
+ *new_dir = FilePath(dtemp);
+ return true;
+}
+
+bool CreateTemporaryDirInDir(const FilePath& base_dir,
+ const FilePath::StringType& prefix,
+ FilePath* new_dir) {
+ FilePath::StringType mkdtemp_template = prefix;
+ mkdtemp_template.append(FILE_PATH_LITERAL("XXXXXX"));
+ return CreateTemporaryDirInDirImpl(base_dir, mkdtemp_template, new_dir);
+}
+
+bool CreateNewTempDirectory(const FilePath::StringType& prefix,
+ FilePath* new_temp_path) {
+ FilePath tmpdir;
+ if (!GetTempDir(&tmpdir))
+ return false;
+
+ return CreateTemporaryDirInDirImpl(tmpdir, TempFileName(), new_temp_path);
+}
+
+bool CreateDirectoryAndGetError(const FilePath& full_path,
+ File::Error* error) {
+ ThreadRestrictions::AssertIOAllowed(); // For call to mkdir().
+ std::vector<FilePath> subpaths;
+
+ // Collect a list of all parent directories.
+ FilePath last_path = full_path;
+ subpaths.push_back(full_path);
+ for (FilePath path = full_path.DirName();
+ path.value() != last_path.value(); path = path.DirName()) {
+ subpaths.push_back(path);
+ last_path = path;
+ }
+
+ // Iterate through the parents and create the missing ones.
+ for (std::vector<FilePath>::reverse_iterator i = subpaths.rbegin();
+ i != subpaths.rend(); ++i) {
+ if (DirectoryExists(*i))
+ continue;
+ if (mkdir(i->value().c_str(), 0700) == 0)
+ continue;
+ // Mkdir failed, but it might have failed with EEXIST, or some other error
+ // due to the the directory appearing out of thin air. This can occur if
+ // two processes are trying to create the same file system tree at the same
+ // time. Check to see if it exists and make sure it is a directory.
+ int saved_errno = errno;
+ if (!DirectoryExists(*i)) {
+ if (error)
+ *error = File::OSErrorToFileError(saved_errno);
+ return false;
+ }
+ }
+ return true;
+}
+
+bool NormalizeFilePath(const FilePath& path, FilePath* normalized_path) {
+ FilePath real_path_result;
+ if (!RealPath(path, &real_path_result))
+ return false;
+
+ // To be consistant with windows, fail if |real_path_result| is a
+ // directory.
+ stat_wrapper_t file_info;
+ if (CallStat(real_path_result.value().c_str(), &file_info) != 0 ||
+ S_ISDIR(file_info.st_mode))
+ return false;
+
+ *normalized_path = real_path_result;
+ return true;
+}
+
+// TODO(rkc): Refactor GetFileInfo and FileEnumerator to handle symlinks
+// correctly. http://code.google.com/p/chromium-os/issues/detail?id=15948
+bool IsLink(const FilePath& file_path) {
+ stat_wrapper_t st;
+ // If we can't lstat the file, it's safe to assume that the file won't at
+ // least be a 'followable' link.
+ if (CallLstat(file_path.value().c_str(), &st) != 0)
+ return false;
+
+ if (S_ISLNK(st.st_mode))
+ return true;
+ else
+ return false;
+}
+
+bool GetFileInfo(const FilePath& file_path, File::Info* results) {
+ stat_wrapper_t file_info;
+#if defined(OS_ANDROID)
+ if (file_path.IsContentUri()) {
+ File file = OpenContentUriForRead(file_path);
+ if (!file.IsValid())
+ return false;
+ return file.GetInfo(results);
+ } else {
+#endif // defined(OS_ANDROID)
+ if (CallStat(file_path.value().c_str(), &file_info) != 0)
+ return false;
+#if defined(OS_ANDROID)
+ }
+#endif // defined(OS_ANDROID)
+
+ results->FromStat(file_info);
+ return true;
+}
+
+FILE* OpenFile(const FilePath& filename, const char* mode) {
+ ThreadRestrictions::AssertIOAllowed();
+ FILE* result = NULL;
+ do {
+ result = fopen(filename.value().c_str(), mode);
+ } while (!result && errno == EINTR);
+ return result;
+}
+
+// NaCl doesn't implement system calls to open files directly.
+#if !defined(OS_NACL)
+FILE* FileToFILE(File file, const char* mode) {
+ FILE* stream = fdopen(file.GetPlatformFile(), mode);
+ if (stream)
+ file.TakePlatformFile();
+ return stream;
+}
+#endif // !defined(OS_NACL)
+
+int ReadFile(const FilePath& filename, char* data, int max_size) {
+ ThreadRestrictions::AssertIOAllowed();
+ int fd = HANDLE_EINTR(open(filename.value().c_str(), O_RDONLY));
+ if (fd < 0)
+ return -1;
+
+ ssize_t bytes_read = HANDLE_EINTR(read(fd, data, max_size));
+ if (IGNORE_EINTR(close(fd)) < 0)
+ return -1;
+ return bytes_read;
+}
+
+int WriteFile(const FilePath& filename, const char* data, int size) {
+ ThreadRestrictions::AssertIOAllowed();
+ int fd = HANDLE_EINTR(creat(filename.value().c_str(), 0640));
+ if (fd < 0)
+ return -1;
+
+ int bytes_written = WriteFileDescriptor(fd, data, size);
+ if (IGNORE_EINTR(close(fd)) < 0)
+ return -1;
+ return bytes_written;
+}
+
+int WriteFileDescriptor(const int fd, const char* data, int size) {
+ // Allow for partial writes.
+ ssize_t bytes_written_total = 0;
+ for (ssize_t bytes_written_partial = 0; bytes_written_total < size;
+ bytes_written_total += bytes_written_partial) {
+ bytes_written_partial =
+ HANDLE_EINTR(write(fd, data + bytes_written_total,
+ size - bytes_written_total));
+ if (bytes_written_partial < 0)
+ return -1;
+ }
+
+ return bytes_written_total;
+}
+
+int AppendToFile(const FilePath& filename, const char* data, int size) {
+ ThreadRestrictions::AssertIOAllowed();
+ int fd = HANDLE_EINTR(open(filename.value().c_str(), O_WRONLY | O_APPEND));
+ if (fd < 0)
+ return -1;
+
+ int bytes_written = WriteFileDescriptor(fd, data, size);
+ if (IGNORE_EINTR(close(fd)) < 0)
+ return -1;
+ return bytes_written;
+}
+
+// Gets the current working directory for the process.
+bool GetCurrentDirectory(FilePath* dir) {
+ // getcwd can return ENOENT, which implies it checks against the disk.
+ ThreadRestrictions::AssertIOAllowed();
+
+ char system_buffer[PATH_MAX] = "";
+ if (!getcwd(system_buffer, sizeof(system_buffer))) {
+ NOTREACHED();
+ return false;
+ }
+ *dir = FilePath(system_buffer);
+ return true;
+}
+
+// Sets the current working directory for the process.
+bool SetCurrentDirectory(const FilePath& path) {
+ ThreadRestrictions::AssertIOAllowed();
+ int ret = chdir(path.value().c_str());
+ return !ret;
+}
+
+bool VerifyPathControlledByUser(const FilePath& base,
+ const FilePath& path,
+ uid_t owner_uid,
+ const std::set<gid_t>& group_gids) {
+ if (base != path && !base.IsParent(path)) {
+ DLOG(ERROR) << "|base| must be a subdirectory of |path|. base = \""
+ << base.value() << "\", path = \"" << path.value() << "\"";
+ return false;
+ }
+
+ std::vector<FilePath::StringType> base_components;
+ std::vector<FilePath::StringType> path_components;
+
+ base.GetComponents(&base_components);
+ path.GetComponents(&path_components);
+
+ std::vector<FilePath::StringType>::const_iterator ib, ip;
+ for (ib = base_components.begin(), ip = path_components.begin();
+ ib != base_components.end(); ++ib, ++ip) {
+ // |base| must be a subpath of |path|, so all components should match.
+ // If these CHECKs fail, look at the test that base is a parent of
+ // path at the top of this function.
+ DCHECK(ip != path_components.end());
+ DCHECK(*ip == *ib);
+ }
+
+ FilePath current_path = base;
+ if (!VerifySpecificPathControlledByUser(current_path, owner_uid, group_gids))
+ return false;
+
+ for (; ip != path_components.end(); ++ip) {
+ current_path = current_path.Append(*ip);
+ if (!VerifySpecificPathControlledByUser(
+ current_path, owner_uid, group_gids))
+ return false;
+ }
+ return true;
+}
+
+#if defined(OS_MACOSX) && !defined(OS_IOS)
+bool VerifyPathControlledByAdmin(const FilePath& path) {
+ const unsigned kRootUid = 0;
+ const FilePath kFileSystemRoot("/");
+
+ // The name of the administrator group on mac os.
+ const char* const kAdminGroupNames[] = {
+ "admin",
+ "wheel"
+ };
+
+ // Reading the groups database may touch the file system.
+ ThreadRestrictions::AssertIOAllowed();
+
+ std::set<gid_t> allowed_group_ids;
+ for (int i = 0, ie = arraysize(kAdminGroupNames); i < ie; ++i) {
+ struct group *group_record = getgrnam(kAdminGroupNames[i]);
+ if (!group_record) {
+ DPLOG(ERROR) << "Could not get the group ID of group \""
+ << kAdminGroupNames[i] << "\".";
+ continue;
+ }
+
+ allowed_group_ids.insert(group_record->gr_gid);
+ }
+
+ return VerifyPathControlledByUser(
+ kFileSystemRoot, path, kRootUid, allowed_group_ids);
+}
+#endif // defined(OS_MACOSX) && !defined(OS_IOS)
+
+int GetMaximumPathComponentLength(const FilePath& path) {
+ ThreadRestrictions::AssertIOAllowed();
+ return pathconf(path.value().c_str(), _PC_NAME_MAX);
+}
+
+#if !defined(OS_ANDROID)
+// This is implemented in file_util_android.cc for that platform.
+bool GetShmemTempDir(bool executable, FilePath* path) {
+#if defined(OS_LINUX)
+ bool use_dev_shm = true;
+ if (executable) {
+ static const bool s_dev_shm_executable = DetermineDevShmExecutable();
+ use_dev_shm = s_dev_shm_executable;
+ }
+ if (use_dev_shm) {
+ *path = FilePath("/dev/shm");
+ return true;
+ }
+#endif
+ return GetTempDir(path);
+}
+#endif // !defined(OS_ANDROID)
+
+// -----------------------------------------------------------------------------
+
+namespace internal {
+
+bool MoveUnsafe(const FilePath& from_path, const FilePath& to_path) {
+ ThreadRestrictions::AssertIOAllowed();
+ // Windows compatibility: if to_path exists, from_path and to_path
+ // must be the same type, either both files, or both directories.
+ stat_wrapper_t to_file_info;
+ if (CallStat(to_path.value().c_str(), &to_file_info) == 0) {
+ stat_wrapper_t from_file_info;
+ if (CallStat(from_path.value().c_str(), &from_file_info) == 0) {
+ if (S_ISDIR(to_file_info.st_mode) != S_ISDIR(from_file_info.st_mode))
+ return false;
+ } else {
+ return false;
+ }
+ }
+
+ if (rename(from_path.value().c_str(), to_path.value().c_str()) == 0)
+ return true;
+
+ if (!CopyDirectory(from_path, to_path, true))
+ return false;
+
+ DeleteFile(from_path, true);
+ return true;
+}
+
+#if !defined(OS_MACOSX)
+// Mac has its own implementation, this is for all other Posix systems.
+bool CopyFileUnsafe(const FilePath& from_path, const FilePath& to_path) {
+ ThreadRestrictions::AssertIOAllowed();
+ int infile = HANDLE_EINTR(open(from_path.value().c_str(), O_RDONLY));
+ if (infile < 0)
+ return false;
+
+ int outfile = HANDLE_EINTR(creat(to_path.value().c_str(), 0666));
+ if (outfile < 0) {
+ close(infile);
+ return false;
+ }
+
+ const size_t kBufferSize = 32768;
+ std::vector<char> buffer(kBufferSize);
+ bool result = true;
+
+ while (result) {
+ ssize_t bytes_read = HANDLE_EINTR(read(infile, &buffer[0], buffer.size()));
+ if (bytes_read < 0) {
+ result = false;
+ break;
+ }
+ if (bytes_read == 0)
+ break;
+ // Allow for partial writes
+ ssize_t bytes_written_per_read = 0;
+ do {
+ ssize_t bytes_written_partial = HANDLE_EINTR(write(
+ outfile,
+ &buffer[bytes_written_per_read],
+ bytes_read - bytes_written_per_read));
+ if (bytes_written_partial < 0) {
+ result = false;
+ break;
+ }
+ bytes_written_per_read += bytes_written_partial;
+ } while (bytes_written_per_read < bytes_read);
+ }
+
+ if (IGNORE_EINTR(close(infile)) < 0)
+ result = false;
+ if (IGNORE_EINTR(close(outfile)) < 0)
+ result = false;
+
+ return result;
+}
+#endif // !defined(OS_MACOSX)
+
+} // namespace internal
+} // namespace base
diff --git a/base/files/file_util_proxy.cc b/base/files/file_util_proxy.cc
index 72d9436..0942e7a 100644
--- a/base/files/file_util_proxy.cc
+++ b/base/files/file_util_proxy.cc
@@ -6,7 +6,7 @@
#include "base/bind.h"
#include "base/bind_helpers.h"
-#include "base/file_util.h"
+#include "base/files/file_util.h"
#include "base/location.h"
#include "base/task_runner.h"
#include "base/task_runner_util.h"
diff --git a/base/files/file_util_proxy_unittest.cc b/base/files/file_util_proxy_unittest.cc
index 52073ae..a18cd43 100644
--- a/base/files/file_util_proxy_unittest.cc
+++ b/base/files/file_util_proxy_unittest.cc
@@ -5,7 +5,7 @@
#include "base/files/file_util_proxy.h"
#include "base/bind.h"
-#include "base/file_util.h"
+#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/memory/weak_ptr.h"
#include "base/message_loop/message_loop.h"
diff --git a/base/files/file_util_unittest.cc b/base/files/file_util_unittest.cc
new file mode 100644
index 0000000..e085aef
--- /dev/null
+++ b/base/files/file_util_unittest.cc
@@ -0,0 +1,2596 @@
+// Copyright (c) 2012 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "build/build_config.h"
+
+#if defined(OS_WIN)
+#include <windows.h>
+#include <shellapi.h>
+#include <shlobj.h>
+#include <tchar.h>
+#include <winioctl.h>
+#endif
+
+#if defined(OS_POSIX)
+#include <errno.h>
+#include <fcntl.h>
+#include <unistd.h>
+#endif
+
+#include <algorithm>
+#include <fstream>
+#include <set>
+#include <vector>
+
+#include "base/base_paths.h"
+#include "base/files/file_enumerator.h"
+#include "base/files/file_path.h"
+#include "base/files/file_util.h"
+#include "base/files/scoped_file.h"
+#include "base/files/scoped_temp_dir.h"
+#include "base/path_service.h"
+#include "base/strings/utf_string_conversions.h"
+#include "base/test/test_file_util.h"
+#include "base/threading/platform_thread.h"
+#include "testing/gtest/include/gtest/gtest.h"
+#include "testing/platform_test.h"
+
+#if defined(OS_WIN)
+#include "base/win/scoped_handle.h"
+#include "base/win/windows_version.h"
+#endif
+
+#if defined(OS_ANDROID)
+#include "base/android/content_uri_utils.h"
+#endif
+
+// This macro helps avoid wrapped lines in the test structs.
+#define FPL(x) FILE_PATH_LITERAL(x)
+
+namespace base {
+
+namespace {
+
+// To test that NormalizeFilePath() deals with NTFS reparse points correctly,
+// we need functions to create and delete reparse points.
+#if defined(OS_WIN)
+typedef struct _REPARSE_DATA_BUFFER {
+ ULONG ReparseTag;
+ USHORT ReparseDataLength;
+ USHORT Reserved;
+ union {
+ struct {
+ USHORT SubstituteNameOffset;
+ USHORT SubstituteNameLength;
+ USHORT PrintNameOffset;
+ USHORT PrintNameLength;
+ ULONG Flags;
+ WCHAR PathBuffer[1];
+ } SymbolicLinkReparseBuffer;
+ struct {
+ USHORT SubstituteNameOffset;
+ USHORT SubstituteNameLength;
+ USHORT PrintNameOffset;
+ USHORT PrintNameLength;
+ WCHAR PathBuffer[1];
+ } MountPointReparseBuffer;
+ struct {
+ UCHAR DataBuffer[1];
+ } GenericReparseBuffer;
+ };
+} REPARSE_DATA_BUFFER, *PREPARSE_DATA_BUFFER;
+
+// Sets a reparse point. |source| will now point to |target|. Returns true if
+// the call succeeds, false otherwise.
+bool SetReparsePoint(HANDLE source, const FilePath& target_path) {
+ std::wstring kPathPrefix = L"\\??\\";
+ std::wstring target_str;
+ // The juction will not work if the target path does not start with \??\ .
+ if (kPathPrefix != target_path.value().substr(0, kPathPrefix.size()))
+ target_str += kPathPrefix;
+ target_str += target_path.value();
+ const wchar_t* target = target_str.c_str();
+ USHORT size_target = static_cast<USHORT>(wcslen(target)) * sizeof(target[0]);
+ char buffer[2000] = {0};
+ DWORD returned;
+
+ REPARSE_DATA_BUFFER* data = reinterpret_cast<REPARSE_DATA_BUFFER*>(buffer);
+
+ data->ReparseTag = 0xa0000003;
+ memcpy(data->MountPointReparseBuffer.PathBuffer, target, size_target + 2);
+
+ data->MountPointReparseBuffer.SubstituteNameLength = size_target;
+ data->MountPointReparseBuffer.PrintNameOffset = size_target + 2;
+ data->ReparseDataLength = size_target + 4 + 8;
+
+ int data_size = data->ReparseDataLength + 8;
+
+ if (!DeviceIoControl(source, FSCTL_SET_REPARSE_POINT, &buffer, data_size,
+ NULL, 0, &returned, NULL)) {
+ return false;
+ }
+ return true;
+}
+
+// Delete the reparse point referenced by |source|. Returns true if the call
+// succeeds, false otherwise.
+bool DeleteReparsePoint(HANDLE source) {
+ DWORD returned;
+ REPARSE_DATA_BUFFER data = {0};
+ data.ReparseTag = 0xa0000003;
+ if (!DeviceIoControl(source, FSCTL_DELETE_REPARSE_POINT, &data, 8, NULL, 0,
+ &returned, NULL)) {
+ return false;
+ }
+ return true;
+}
+
+// Manages a reparse point for a test.
+class ReparsePoint {
+ public:
+ // Creates a reparse point from |source| (an empty directory) to |target|.
+ ReparsePoint(const FilePath& source, const FilePath& target) {
+ dir_.Set(
+ ::CreateFile(source.value().c_str(),
+ FILE_ALL_ACCESS,
+ FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
+ NULL,
+ OPEN_EXISTING,
+ FILE_FLAG_BACKUP_SEMANTICS, // Needed to open a directory.
+ NULL));
+ created_ = dir_.IsValid() && SetReparsePoint(dir_, target);
+ }
+
+ ~ReparsePoint() {
+ if (created_)
+ DeleteReparsePoint(dir_);
+ }
+
+ bool IsValid() { return created_; }
+
+ private:
+ win::ScopedHandle dir_;
+ bool created_;
+ DISALLOW_COPY_AND_ASSIGN(ReparsePoint);
+};
+
+#endif
+
+#if defined(OS_POSIX)
+// Provide a simple way to change the permissions bits on |path| in tests.
+// ASSERT failures will return, but not stop the test. Caller should wrap
+// calls to this function in ASSERT_NO_FATAL_FAILURE().
+void ChangePosixFilePermissions(const FilePath& path,
+ int mode_bits_to_set,
+ int mode_bits_to_clear) {
+ ASSERT_FALSE(mode_bits_to_set & mode_bits_to_clear)
+ << "Can't set and clear the same bits.";
+
+ int mode = 0;
+ ASSERT_TRUE(GetPosixFilePermissions(path, &mode));
+ mode |= mode_bits_to_set;
+ mode &= ~mode_bits_to_clear;
+ ASSERT_TRUE(SetPosixFilePermissions(path, mode));
+}
+#endif // defined(OS_POSIX)
+
+const wchar_t bogus_content[] = L"I'm cannon fodder.";
+
+const int FILES_AND_DIRECTORIES =
+ FileEnumerator::FILES | FileEnumerator::DIRECTORIES;
+
+// file_util winds up using autoreleased objects on the Mac, so this needs
+// to be a PlatformTest
+class FileUtilTest : public PlatformTest {
+ protected:
+ virtual void SetUp() OVERRIDE {
+ PlatformTest::SetUp();
+ ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
+ }
+
+ ScopedTempDir temp_dir_;
+};
+
+// Collects all the results from the given file enumerator, and provides an
+// interface to query whether a given file is present.
+class FindResultCollector {
+ public:
+ explicit FindResultCollector(FileEnumerator& enumerator) {
+ FilePath cur_file;
+ while (!(cur_file = enumerator.Next()).value().empty()) {
+ FilePath::StringType path = cur_file.value();
+ // The file should not be returned twice.
+ EXPECT_TRUE(files_.end() == files_.find(path))
+ << "Same file returned twice";
+
+ // Save for later.
+ files_.insert(path);
+ }
+ }
+
+ // Returns true if the enumerator found the file.
+ bool HasFile(const FilePath& file) const {
+ return files_.find(file.value()) != files_.end();
+ }
+
+ int size() {
+ return static_cast<int>(files_.size());
+ }
+
+ private:
+ std::set<FilePath::StringType> files_;
+};
+
+// Simple function to dump some text into a new file.
+void CreateTextFile(const FilePath& filename,
+ const std::wstring& contents) {
+ std::wofstream file;
+ file.open(filename.value().c_str());
+ ASSERT_TRUE(file.is_open());
+ file << contents;
+ file.close();
+}
+
+// Simple function to take out some text from a file.
+std::wstring ReadTextFile(const FilePath& filename) {
+ wchar_t contents[64];
+ std::wifstream file;
+ file.open(filename.value().c_str());
+ EXPECT_TRUE(file.is_open());
+ file.getline(contents, arraysize(contents));
+ file.close();
+ return std::wstring(contents);
+}
+
+#if defined(OS_WIN)
+uint64 FileTimeAsUint64(const FILETIME& ft) {
+ ULARGE_INTEGER u;
+ u.LowPart = ft.dwLowDateTime;
+ u.HighPart = ft.dwHighDateTime;
+ return u.QuadPart;
+}
+#endif
+
+TEST_F(FileUtilTest, FileAndDirectorySize) {
+ // Create three files of 20, 30 and 3 chars (utf8). ComputeDirectorySize
+ // should return 53 bytes.
+ FilePath file_01 = temp_dir_.path().Append(FPL("The file 01.txt"));
+ CreateTextFile(file_01, L"12345678901234567890");
+ int64 size_f1 = 0;
+ ASSERT_TRUE(GetFileSize(file_01, &size_f1));
+ EXPECT_EQ(20ll, size_f1);
+
+ FilePath subdir_path = temp_dir_.path().Append(FPL("Level2"));
+ CreateDirectory(subdir_path);
+
+ FilePath file_02 = subdir_path.Append(FPL("The file 02.txt"));
+ CreateTextFile(file_02, L"123456789012345678901234567890");
+ int64 size_f2 = 0;
+ ASSERT_TRUE(GetFileSize(file_02, &size_f2));
+ EXPECT_EQ(30ll, size_f2);
+
+ FilePath subsubdir_path = subdir_path.Append(FPL("Level3"));
+ CreateDirectory(subsubdir_path);
+
+ FilePath file_03 = subsubdir_path.Append(FPL("The file 03.txt"));
+ CreateTextFile(file_03, L"123");
+
+ int64 computed_size = ComputeDirectorySize(temp_dir_.path());
+ EXPECT_EQ(size_f1 + size_f2 + 3, computed_size);
+}
+
+TEST_F(FileUtilTest, NormalizeFilePathBasic) {
+ // Create a directory under the test dir. Because we create it,
+ // we know it is not a link.
+ FilePath file_a_path = temp_dir_.path().Append(FPL("file_a"));
+ FilePath dir_path = temp_dir_.path().Append(FPL("dir"));
+ FilePath file_b_path = dir_path.Append(FPL("file_b"));
+ CreateDirectory(dir_path);
+
+ FilePath normalized_file_a_path, normalized_file_b_path;
+ ASSERT_FALSE(PathExists(file_a_path));
+ ASSERT_FALSE(NormalizeFilePath(file_a_path, &normalized_file_a_path))
+ << "NormalizeFilePath() should fail on nonexistent paths.";
+
+ CreateTextFile(file_a_path, bogus_content);
+ ASSERT_TRUE(PathExists(file_a_path));
+ ASSERT_TRUE(NormalizeFilePath(file_a_path, &normalized_file_a_path));
+
+ CreateTextFile(file_b_path, bogus_content);
+ ASSERT_TRUE(PathExists(file_b_path));
+ ASSERT_TRUE(NormalizeFilePath(file_b_path, &normalized_file_b_path));
+
+ // Beacuse this test created |dir_path|, we know it is not a link
+ // or junction. So, the real path of the directory holding file a
+ // must be the parent of the path holding file b.
+ ASSERT_TRUE(normalized_file_a_path.DirName()
+ .IsParent(normalized_file_b_path.DirName()));
+}
+
+#if defined(OS_WIN)
+
+TEST_F(FileUtilTest, NormalizeFilePathReparsePoints) {
+ // Build the following directory structure:
+ //
+ // temp_dir
+ // |-> base_a
+ // | |-> sub_a
+ // | |-> file.txt
+ // | |-> long_name___... (Very long name.)
+ // | |-> sub_long
+ // | |-> deep.txt
+ // |-> base_b
+ // |-> to_sub_a (reparse point to temp_dir\base_a\sub_a)
+ // |-> to_base_b (reparse point to temp_dir\base_b)
+ // |-> to_sub_long (reparse point to temp_dir\sub_a\long_name_\sub_long)
+
+ FilePath base_a = temp_dir_.path().Append(FPL("base_a"));
+ ASSERT_TRUE(CreateDirectory(base_a));
+
+ FilePath sub_a = base_a.Append(FPL("sub_a"));
+ ASSERT_TRUE(CreateDirectory(sub_a));
+
+ FilePath file_txt = sub_a.Append(FPL("file.txt"));
+ CreateTextFile(file_txt, bogus_content);
+
+ // Want a directory whose name is long enough to make the path to the file
+ // inside just under MAX_PATH chars. This will be used to test that when
+ // a junction expands to a path over MAX_PATH chars in length,
+ // NormalizeFilePath() fails without crashing.
+ FilePath sub_long_rel(FPL("sub_long"));
+ FilePath deep_txt(FPL("deep.txt"));
+
+ int target_length = MAX_PATH;
+ target_length -= (sub_a.value().length() + 1); // +1 for the sepperator '\'.
+ target_length -= (sub_long_rel.Append(deep_txt).value().length() + 1);
+ // Without making the path a bit shorter, CreateDirectory() fails.
+ // the resulting path is still long enough to hit the failing case in
+ // NormalizePath().
+ const int kCreateDirLimit = 4;
+ target_length -= kCreateDirLimit;
+ FilePath::StringType long_name_str = FPL("long_name_");
+ long_name_str.resize(target_length, '_');
+
+ FilePath long_name = sub_a.Append(FilePath(long_name_str));
+ FilePath deep_file = long_name.Append(sub_long_rel).Append(deep_txt);
+ ASSERT_EQ(MAX_PATH - kCreateDirLimit, deep_file.value().length());
+
+ FilePath sub_long = deep_file.DirName();
+ ASSERT_TRUE(CreateDirectory(sub_long));
+ CreateTextFile(deep_file, bogus_content);
+
+ FilePath base_b = temp_dir_.path().Append(FPL("base_b"));
+ ASSERT_TRUE(CreateDirectory(base_b));
+
+ FilePath to_sub_a = base_b.Append(FPL("to_sub_a"));
+ ASSERT_TRUE(CreateDirectory(to_sub_a));
+ FilePath normalized_path;
+ {
+ ReparsePoint reparse_to_sub_a(to_sub_a, sub_a);
+ ASSERT_TRUE(reparse_to_sub_a.IsValid());
+
+ FilePath to_base_b = base_b.Append(FPL("to_base_b"));
+ ASSERT_TRUE(CreateDirectory(to_base_b));
+ ReparsePoint reparse_to_base_b(to_base_b, base_b);
+ ASSERT_TRUE(reparse_to_base_b.IsValid());
+
+ FilePath to_sub_long = base_b.Append(FPL("to_sub_long"));
+ ASSERT_TRUE(CreateDirectory(to_sub_long));
+ ReparsePoint reparse_to_sub_long(to_sub_long, sub_long);
+ ASSERT_TRUE(reparse_to_sub_long.IsValid());
+
+ // Normalize a junction free path: base_a\sub_a\file.txt .
+ ASSERT_TRUE(NormalizeFilePath(file_txt, &normalized_path));
+ ASSERT_STREQ(file_txt.value().c_str(), normalized_path.value().c_str());
+
+ // Check that the path base_b\to_sub_a\file.txt can be normalized to exclude
+ // the junction to_sub_a.
+ ASSERT_TRUE(NormalizeFilePath(to_sub_a.Append(FPL("file.txt")),
+ &normalized_path));
+ ASSERT_STREQ(file_txt.value().c_str(), normalized_path.value().c_str());
+
+ // Check that the path base_b\to_base_b\to_base_b\to_sub_a\file.txt can be
+ // normalized to exclude junctions to_base_b and to_sub_a .
+ ASSERT_TRUE(NormalizeFilePath(base_b.Append(FPL("to_base_b"))
+ .Append(FPL("to_base_b"))
+ .Append(FPL("to_sub_a"))
+ .Append(FPL("file.txt")),
+ &normalized_path));
+ ASSERT_STREQ(file_txt.value().c_str(), normalized_path.value().c_str());
+
+ // A long enough path will cause NormalizeFilePath() to fail. Make a long
+ // path using to_base_b many times, and check that paths long enough to fail
+ // do not cause a crash.
+ FilePath long_path = base_b;
+ const int kLengthLimit = MAX_PATH + 200;
+ while (long_path.value().length() <= kLengthLimit) {
+ long_path = long_path.Append(FPL("to_base_b"));
+ }
+ long_path = long_path.Append(FPL("to_sub_a"))
+ .Append(FPL("file.txt"));
+
+ ASSERT_FALSE(NormalizeFilePath(long_path, &normalized_path));
+
+ // Normalizing the junction to deep.txt should fail, because the expanded
+ // path to deep.txt is longer than MAX_PATH.
+ ASSERT_FALSE(NormalizeFilePath(to_sub_long.Append(deep_txt),
+ &normalized_path));
+
+ // Delete the reparse points, and see that NormalizeFilePath() fails
+ // to traverse them.
+ }
+
+ ASSERT_FALSE(NormalizeFilePath(to_sub_a.Append(FPL("file.txt")),
+ &normalized_path));
+}
+
+TEST_F(FileUtilTest, DevicePathToDriveLetter) {
+ // Get a drive letter.
+ std::wstring real_drive_letter = temp_dir_.path().value().substr(0, 2);
+ if (!isalpha(real_drive_letter[0]) || ':' != real_drive_letter[1]) {
+ LOG(ERROR) << "Can't get a drive letter to test with.";
+ return;
+ }
+
+ // Get the NT style path to that drive.
+ wchar_t device_path[MAX_PATH] = {'\0'};
+ ASSERT_TRUE(
+ ::QueryDosDevice(real_drive_letter.c_str(), device_path, MAX_PATH));
+ FilePath actual_device_path(device_path);
+ FilePath win32_path;
+
+ // Run DevicePathToDriveLetterPath() on the NT style path we got from
+ // QueryDosDevice(). Expect the drive letter we started with.
+ ASSERT_TRUE(DevicePathToDriveLetterPath(actual_device_path, &win32_path));
+ ASSERT_EQ(real_drive_letter, win32_path.value());
+
+ // Add some directories to the path. Expect those extra path componenets
+ // to be preserved.
+ FilePath kRelativePath(FPL("dir1\\dir2\\file.txt"));
+ ASSERT_TRUE(DevicePathToDriveLetterPath(
+ actual_device_path.Append(kRelativePath),
+ &win32_path));
+ EXPECT_EQ(FilePath(real_drive_letter + L"\\").Append(kRelativePath).value(),
+ win32_path.value());
+
+ // Deform the real path so that it is invalid by removing the last four
+ // characters. The way windows names devices that are hard disks
+ // (\Device\HardDiskVolume${NUMBER}) guarantees that the string is longer
+ // than three characters. The only way the truncated string could be a
+ // real drive is if more than 10^3 disks are mounted:
+ // \Device\HardDiskVolume10000 would be truncated to \Device\HardDiskVolume1
+ // Check that DevicePathToDriveLetterPath fails.
+ int path_length = actual_device_path.value().length();
+ int new_length = path_length - 4;
+ ASSERT_LT(0, new_length);
+ FilePath prefix_of_real_device_path(
+ actual_device_path.value().substr(0, new_length));
+ ASSERT_FALSE(DevicePathToDriveLetterPath(prefix_of_real_device_path,
+ &win32_path));
+
+ ASSERT_FALSE(DevicePathToDriveLetterPath(
+ prefix_of_real_device_path.Append(kRelativePath),
+ &win32_path));
+
+ // Deform the real path so that it is invalid by adding some characters. For
+ // example, if C: maps to \Device\HardDiskVolume8, then we simulate a
+ // request for the drive letter whose native path is
+ // \Device\HardDiskVolume812345 . We assume such a device does not exist,
+ // because drives are numbered in order and mounting 112345 hard disks will
+ // never happen.
+ const FilePath::StringType kExtraChars = FPL("12345");
+
+ FilePath real_device_path_plus_numbers(
+ actual_device_path.value() + kExtraChars);
+
+ ASSERT_FALSE(DevicePathToDriveLetterPath(
+ real_device_path_plus_numbers,
+ &win32_path));
+
+ ASSERT_FALSE(DevicePathToDriveLetterPath(
+ real_device_path_plus_numbers.Append(kRelativePath),
+ &win32_path));
+}
+
+TEST_F(FileUtilTest, CreateTemporaryFileInDirLongPathTest) {
+ // Test that CreateTemporaryFileInDir() creates a path and returns a long path
+ // if it is available. This test requires that:
+ // - the filesystem at |temp_dir_| supports long filenames.
+ // - the account has FILE_LIST_DIRECTORY permission for all ancestor
+ // directories of |temp_dir_|.
+ const FilePath::CharType kLongDirName[] = FPL("A long path");
+ const FilePath::CharType kTestSubDirName[] = FPL("test");
+ FilePath long_test_dir = temp_dir_.path().Append(kLongDirName);
+ ASSERT_TRUE(CreateDirectory(long_test_dir));
+
+ // kLongDirName is not a 8.3 component. So GetShortName() should give us a
+ // different short name.
+ WCHAR path_buffer[MAX_PATH];
+ DWORD path_buffer_length = GetShortPathName(long_test_dir.value().c_str(),
+ path_buffer, MAX_PATH);
+ ASSERT_LT(path_buffer_length, DWORD(MAX_PATH));
+ ASSERT_NE(DWORD(0), path_buffer_length);
+ FilePath short_test_dir(path_buffer);
+ ASSERT_STRNE(kLongDirName, short_test_dir.BaseName().value().c_str());
+
+ FilePath temp_file;
+ ASSERT_TRUE(CreateTemporaryFileInDir(short_test_dir, &temp_file));
+ EXPECT_STREQ(kLongDirName, temp_file.DirName().BaseName().value().c_str());
+ EXPECT_TRUE(PathExists(temp_file));
+
+ // Create a subdirectory of |long_test_dir| and make |long_test_dir|
+ // unreadable. We should still be able to create a temp file in the
+ // subdirectory, but we won't be able to determine the long path for it. This
+ // mimics the environment that some users run where their user profiles reside
+ // in a location where the don't have full access to the higher level
+ // directories. (Note that this assumption is true for NTFS, but not for some
+ // network file systems. E.g. AFS).
+ FilePath access_test_dir = long_test_dir.Append(kTestSubDirName);
+ ASSERT_TRUE(CreateDirectory(access_test_dir));
+ base::FilePermissionRestorer long_test_dir_restorer(long_test_dir);
+ ASSERT_TRUE(base::MakeFileUnreadable(long_test_dir));
+
+ // Use the short form of the directory to create a temporary filename.
+ ASSERT_TRUE(CreateTemporaryFileInDir(
+ short_test_dir.Append(kTestSubDirName), &temp_file));
+ EXPECT_TRUE(PathExists(temp_file));
+ EXPECT_TRUE(short_test_dir.IsParent(temp_file.DirName()));
+
+ // Check that the long path can't be determined for |temp_file|.
+ path_buffer_length = GetLongPathName(temp_file.value().c_str(),
+ path_buffer, MAX_PATH);
+ EXPECT_EQ(DWORD(0), path_buffer_length);
+}
+
+#endif // defined(OS_WIN)
+
+#if defined(OS_POSIX)
+
+TEST_F(FileUtilTest, CreateAndReadSymlinks) {
+ FilePath link_from = temp_dir_.path().Append(FPL("from_file"));
+ FilePath link_to = temp_dir_.path().Append(FPL("to_file"));
+ CreateTextFile(link_to, bogus_content);
+
+ ASSERT_TRUE(CreateSymbolicLink(link_to, link_from))
+ << "Failed to create file symlink.";
+
+ // If we created the link properly, we should be able to read the contents
+ // through it.
+ std::wstring contents = ReadTextFile(link_from);
+ EXPECT_EQ(bogus_content, contents);
+
+ FilePath result;
+ ASSERT_TRUE(ReadSymbolicLink(link_from, &result));
+ EXPECT_EQ(link_to.value(), result.value());
+
+ // Link to a directory.
+ link_from = temp_dir_.path().Append(FPL("from_dir"));
+ link_to = temp_dir_.path().Append(FPL("to_dir"));
+ ASSERT_TRUE(CreateDirectory(link_to));
+ ASSERT_TRUE(CreateSymbolicLink(link_to, link_from))
+ << "Failed to create directory symlink.";
+
+ // Test failures.
+ EXPECT_FALSE(CreateSymbolicLink(link_to, link_to));
+ EXPECT_FALSE(ReadSymbolicLink(link_to, &result));
+ FilePath missing = temp_dir_.path().Append(FPL("missing"));
+ EXPECT_FALSE(ReadSymbolicLink(missing, &result));
+}
+
+// The following test of NormalizeFilePath() require that we create a symlink.
+// This can not be done on Windows before Vista. On Vista, creating a symlink
+// requires privilege "SeCreateSymbolicLinkPrivilege".
+// TODO(skerner): Investigate the possibility of giving base_unittests the
+// privileges required to create a symlink.
+TEST_F(FileUtilTest, NormalizeFilePathSymlinks) {
+ // Link one file to another.
+ FilePath link_from = temp_dir_.path().Append(FPL("from_file"));
+ FilePath link_to = temp_dir_.path().Append(FPL("to_file"));
+ CreateTextFile(link_to, bogus_content);
+
+ ASSERT_TRUE(CreateSymbolicLink(link_to, link_from))
+ << "Failed to create file symlink.";
+
+ // Check that NormalizeFilePath sees the link.
+ FilePath normalized_path;
+ ASSERT_TRUE(NormalizeFilePath(link_from, &normalized_path));
+ EXPECT_NE(link_from, link_to);
+ EXPECT_EQ(link_to.BaseName().value(), normalized_path.BaseName().value());
+ EXPECT_EQ(link_to.BaseName().value(), normalized_path.BaseName().value());
+
+ // Link to a directory.
+ link_from = temp_dir_.path().Append(FPL("from_dir"));
+ link_to = temp_dir_.path().Append(FPL("to_dir"));
+ ASSERT_TRUE(CreateDirectory(link_to));
+ ASSERT_TRUE(CreateSymbolicLink(link_to, link_from))
+ << "Failed to create directory symlink.";
+
+ EXPECT_FALSE(NormalizeFilePath(link_from, &normalized_path))
+ << "Links to directories should return false.";
+
+ // Test that a loop in the links causes NormalizeFilePath() to return false.
+ link_from = temp_dir_.path().Append(FPL("link_a"));
+ link_to = temp_dir_.path().Append(FPL("link_b"));
+ ASSERT_TRUE(CreateSymbolicLink(link_to, link_from))
+ << "Failed to create loop symlink a.";
+ ASSERT_TRUE(CreateSymbolicLink(link_from, link_to))
+ << "Failed to create loop symlink b.";
+
+ // Infinite loop!
+ EXPECT_FALSE(NormalizeFilePath(link_from, &normalized_path));
+}
+#endif // defined(OS_POSIX)
+
+TEST_F(FileUtilTest, DeleteNonExistent) {
+ FilePath non_existent = temp_dir_.path().AppendASCII("bogus_file_dne.foobar");
+ ASSERT_FALSE(PathExists(non_existent));
+
+ EXPECT_TRUE(DeleteFile(non_existent, false));
+ ASSERT_FALSE(PathExists(non_existent));
+ EXPECT_TRUE(DeleteFile(non_existent, true));
+ ASSERT_FALSE(PathExists(non_existent));
+}
+
+TEST_F(FileUtilTest, DeleteNonExistentWithNonExistentParent) {
+ FilePath non_existent = temp_dir_.path().AppendASCII("bogus_topdir");
+ non_existent = non_existent.AppendASCII("bogus_subdir");
+ ASSERT_FALSE(PathExists(non_existent));
+
+ EXPECT_TRUE(DeleteFile(non_existent, false));
+ ASSERT_FALSE(PathExists(non_existent));
+ EXPECT_TRUE(DeleteFile(non_existent, true));
+ ASSERT_FALSE(PathExists(non_existent));
+}
+
+TEST_F(FileUtilTest, DeleteFile) {
+ // Create a file
+ FilePath file_name = temp_dir_.path().Append(FPL("Test DeleteFile 1.txt"));
+ CreateTextFile(file_name, bogus_content);
+ ASSERT_TRUE(PathExists(file_name));
+
+ // Make sure it's deleted
+ EXPECT_TRUE(DeleteFile(file_name, false));
+ EXPECT_FALSE(PathExists(file_name));
+
+ // Test recursive case, create a new file
+ file_name = temp_dir_.path().Append(FPL("Test DeleteFile 2.txt"));
+ CreateTextFile(file_name, bogus_content);
+ ASSERT_TRUE(PathExists(file_name));
+
+ // Make sure it's deleted
+ EXPECT_TRUE(DeleteFile(file_name, true));
+ EXPECT_FALSE(PathExists(file_name));
+}
+
+#if defined(OS_POSIX)
+TEST_F(FileUtilTest, DeleteSymlinkToExistentFile) {
+ // Create a file.
+ FilePath file_name = temp_dir_.path().Append(FPL("Test DeleteFile 2.txt"));
+ CreateTextFile(file_name, bogus_content);
+ ASSERT_TRUE(PathExists(file_name));
+
+ // Create a symlink to the file.
+ FilePath file_link = temp_dir_.path().Append("file_link_2");
+ ASSERT_TRUE(CreateSymbolicLink(file_name, file_link))
+ << "Failed to create symlink.";
+
+ // Delete the symbolic link.
+ EXPECT_TRUE(DeleteFile(file_link, false));
+
+ // Make sure original file is not deleted.
+ EXPECT_FALSE(PathExists(file_link));
+ EXPECT_TRUE(PathExists(file_name));
+}
+
+TEST_F(FileUtilTest, DeleteSymlinkToNonExistentFile) {
+ // Create a non-existent file path.
+ FilePath non_existent = temp_dir_.path().Append(FPL("Test DeleteFile 3.txt"));
+ EXPECT_FALSE(PathExists(non_existent));
+
+ // Create a symlink to the non-existent file.
+ FilePath file_link = temp_dir_.path().Append("file_link_3");
+ ASSERT_TRUE(CreateSymbolicLink(non_existent, file_link))
+ << "Failed to create symlink.";
+
+ // Make sure the symbolic link is exist.
+ EXPECT_TRUE(IsLink(file_link));
+ EXPECT_FALSE(PathExists(file_link));
+
+ // Delete the symbolic link.
+ EXPECT_TRUE(DeleteFile(file_link, false));
+
+ // Make sure the symbolic link is deleted.
+ EXPECT_FALSE(IsLink(file_link));
+}
+
+TEST_F(FileUtilTest, ChangeFilePermissionsAndRead) {
+ // Create a file path.
+ FilePath file_name = temp_dir_.path().Append(FPL("Test Readable File.txt"));
+ EXPECT_FALSE(PathExists(file_name));
+
+ const std::string kData("hello");
+
+ int buffer_size = kData.length();
+ char* buffer = new char[buffer_size];
+
+ // Write file.
+ EXPECT_EQ(static_cast<int>(kData.length()),
+ WriteFile(file_name, kData.data(), kData.length()));
+ EXPECT_TRUE(PathExists(file_name));
+
+ // Make sure the file is readable.
+ int32 mode = 0;
+ EXPECT_TRUE(GetPosixFilePermissions(file_name, &mode));
+ EXPECT_TRUE(mode & FILE_PERMISSION_READ_BY_USER);
+
+ // Get rid of the read permission.
+ EXPECT_TRUE(SetPosixFilePermissions(file_name, 0u));
+ EXPECT_TRUE(GetPosixFilePermissions(file_name, &mode));
+ EXPECT_FALSE(mode & FILE_PERMISSION_READ_BY_USER);
+ // Make sure the file can't be read.
+ EXPECT_EQ(-1, ReadFile(file_name, buffer, buffer_size));
+
+ // Give the read permission.
+ EXPECT_TRUE(SetPosixFilePermissions(file_name, FILE_PERMISSION_READ_BY_USER));
+ EXPECT_TRUE(GetPosixFilePermissions(file_name, &mode));
+ EXPECT_TRUE(mode & FILE_PERMISSION_READ_BY_USER);
+ // Make sure the file can be read.
+ EXPECT_EQ(static_cast<int>(kData.length()),
+ ReadFile(file_name, buffer, buffer_size));
+
+ // Delete the file.
+ EXPECT_TRUE(DeleteFile(file_name, false));
+ EXPECT_FALSE(PathExists(file_name));
+
+ delete[] buffer;
+}
+
+TEST_F(FileUtilTest, ChangeFilePermissionsAndWrite) {
+ // Create a file path.
+ FilePath file_name = temp_dir_.path().Append(FPL("Test Readable File.txt"));
+ EXPECT_FALSE(PathExists(file_name));
+
+ const std::string kData("hello");
+
+ // Write file.
+ EXPECT_EQ(static_cast<int>(kData.length()),
+ WriteFile(file_name, kData.data(), kData.length()));
+ EXPECT_TRUE(PathExists(file_name));
+
+ // Make sure the file is writable.
+ int mode = 0;
+ EXPECT_TRUE(GetPosixFilePermissions(file_name, &mode));
+ EXPECT_TRUE(mode & FILE_PERMISSION_WRITE_BY_USER);
+ EXPECT_TRUE(PathIsWritable(file_name));
+
+ // Get rid of the write permission.
+ EXPECT_TRUE(SetPosixFilePermissions(file_name, 0u));
+ EXPECT_TRUE(GetPosixFilePermissions(file_name, &mode));
+ EXPECT_FALSE(mode & FILE_PERMISSION_WRITE_BY_USER);
+ // Make sure the file can't be write.
+ EXPECT_EQ(-1, WriteFile(file_name, kData.data(), kData.length()));
+ EXPECT_FALSE(PathIsWritable(file_name));
+
+ // Give read permission.
+ EXPECT_TRUE(SetPosixFilePermissions(file_name,
+ FILE_PERMISSION_WRITE_BY_USER));
+ EXPECT_TRUE(GetPosixFilePermissions(file_name, &mode));
+ EXPECT_TRUE(mode & FILE_PERMISSION_WRITE_BY_USER);
+ // Make sure the file can be write.
+ EXPECT_EQ(static_cast<int>(kData.length()),
+ WriteFile(file_name, kData.data(), kData.length()));
+ EXPECT_TRUE(PathIsWritable(file_name));
+
+ // Delete the file.
+ EXPECT_TRUE(DeleteFile(file_name, false));
+ EXPECT_FALSE(PathExists(file_name));
+}
+
+TEST_F(FileUtilTest, ChangeDirectoryPermissionsAndEnumerate) {
+ // Create a directory path.
+ FilePath subdir_path =
+ temp_dir_.path().Append(FPL("PermissionTest1"));
+ CreateDirectory(subdir_path);
+ ASSERT_TRUE(PathExists(subdir_path));
+
+ // Create a dummy file to enumerate.
+ FilePath file_name = subdir_path.Append(FPL("Test Readable File.txt"));
+ EXPECT_FALSE(PathExists(file_name));
+ const std::string kData("hello");
+ EXPECT_EQ(static_cast<int>(kData.length()),
+ WriteFile(file_name, kData.data(), kData.length()));
+ EXPECT_TRUE(PathExists(file_name));
+
+ // Make sure the directory has the all permissions.
+ int mode = 0;
+ EXPECT_TRUE(GetPosixFilePermissions(subdir_path, &mode));
+ EXPECT_EQ(FILE_PERMISSION_USER_MASK, mode & FILE_PERMISSION_USER_MASK);
+
+ // Get rid of the permissions from the directory.
+ EXPECT_TRUE(SetPosixFilePermissions(subdir_path, 0u));
+ EXPECT_TRUE(GetPosixFilePermissions(subdir_path, &mode));
+ EXPECT_FALSE(mode & FILE_PERMISSION_USER_MASK);
+
+ // Make sure the file in the directory can't be enumerated.
+ FileEnumerator f1(subdir_path, true, FileEnumerator::FILES);
+ EXPECT_TRUE(PathExists(subdir_path));
+ FindResultCollector c1(f1);
+ EXPECT_EQ(0, c1.size());
+ EXPECT_FALSE(GetPosixFilePermissions(file_name, &mode));
+
+ // Give the permissions to the directory.
+ EXPECT_TRUE(SetPosixFilePermissions(subdir_path, FILE_PERMISSION_USER_MASK));
+ EXPECT_TRUE(GetPosixFilePermissions(subdir_path, &mode));
+ EXPECT_EQ(FILE_PERMISSION_USER_MASK, mode & FILE_PERMISSION_USER_MASK);
+
+ // Make sure the file in the directory can be enumerated.
+ FileEnumerator f2(subdir_path, true, FileEnumerator::FILES);
+ FindResultCollector c2(f2);
+ EXPECT_TRUE(c2.HasFile(file_name));
+ EXPECT_EQ(1, c2.size());
+
+ // Delete the file.
+ EXPECT_TRUE(DeleteFile(subdir_path, true));
+ EXPECT_FALSE(PathExists(subdir_path));
+}
+
+#endif // defined(OS_POSIX)
+
+#if defined(OS_WIN)
+// Tests that the Delete function works for wild cards, especially
+// with the recursion flag. Also coincidentally tests PathExists.
+// TODO(erikkay): see if anyone's actually using this feature of the API
+TEST_F(FileUtilTest, DeleteWildCard) {
+ // Create a file and a directory
+ FilePath file_name = temp_dir_.path().Append(FPL("Test DeleteWildCard.txt"));
+ CreateTextFile(file_name, bogus_content);
+ ASSERT_TRUE(PathExists(file_name));
+
+ FilePath subdir_path = temp_dir_.path().Append(FPL("DeleteWildCardDir"));
+ CreateDirectory(subdir_path);
+ ASSERT_TRUE(PathExists(subdir_path));
+
+ // Create the wildcard path
+ FilePath directory_contents = temp_dir_.path();
+ directory_contents = directory_contents.Append(FPL("*"));
+
+ // Delete non-recursively and check that only the file is deleted
+ EXPECT_TRUE(DeleteFile(directory_contents, false));
+ EXPECT_FALSE(PathExists(file_name));
+ EXPECT_TRUE(PathExists(subdir_path));
+
+ // Delete recursively and make sure all contents are deleted
+ EXPECT_TRUE(DeleteFile(directory_contents, true));
+ EXPECT_FALSE(PathExists(file_name));
+ EXPECT_FALSE(PathExists(subdir_path));
+}
+
+// TODO(erikkay): see if anyone's actually using this feature of the API
+TEST_F(FileUtilTest, DeleteNonExistantWildCard) {
+ // Create a file and a directory
+ FilePath subdir_path =
+ temp_dir_.path().Append(FPL("DeleteNonExistantWildCard"));
+ CreateDirectory(subdir_path);
+ ASSERT_TRUE(PathExists(subdir_path));
+
+ // Create the wildcard path
+ FilePath directory_contents = subdir_path;
+ directory_contents = directory_contents.Append(FPL("*"));
+
+ // Delete non-recursively and check nothing got deleted
+ EXPECT_TRUE(DeleteFile(directory_contents, false));
+ EXPECT_TRUE(PathExists(subdir_path));
+
+ // Delete recursively and check nothing got deleted
+ EXPECT_TRUE(DeleteFile(directory_contents, true));
+ EXPECT_TRUE(PathExists(subdir_path));
+}
+#endif
+
+// Tests non-recursive Delete() for a directory.
+TEST_F(FileUtilTest, DeleteDirNonRecursive) {
+ // Create a subdirectory and put a file and two directories inside.
+ FilePath test_subdir = temp_dir_.path().Append(FPL("DeleteDirNonRecursive"));
+ CreateDirectory(test_subdir);
+ ASSERT_TRUE(PathExists(test_subdir));
+
+ FilePath file_name = test_subdir.Append(FPL("Test DeleteDir.txt"));
+ CreateTextFile(file_name, bogus_content);
+ ASSERT_TRUE(PathExists(file_name));
+
+ FilePath subdir_path1 = test_subdir.Append(FPL("TestSubDir1"));
+ CreateDirectory(subdir_path1);
+ ASSERT_TRUE(PathExists(subdir_path1));
+
+ FilePath subdir_path2 = test_subdir.Append(FPL("TestSubDir2"));
+ CreateDirectory(subdir_path2);
+ ASSERT_TRUE(PathExists(subdir_path2));
+
+ // Delete non-recursively and check that the empty dir got deleted
+ EXPECT_TRUE(DeleteFile(subdir_path2, false));
+ EXPECT_FALSE(PathExists(subdir_path2));
+
+ // Delete non-recursively and check that nothing got deleted
+ EXPECT_FALSE(DeleteFile(test_subdir, false));
+ EXPECT_TRUE(PathExists(test_subdir));
+ EXPECT_TRUE(PathExists(file_name));
+ EXPECT_TRUE(PathExists(subdir_path1));
+}
+
+// Tests recursive Delete() for a directory.
+TEST_F(FileUtilTest, DeleteDirRecursive) {
+ // Create a subdirectory and put a file and two directories inside.
+ FilePath test_subdir = temp_dir_.path().Append(FPL("DeleteDirRecursive"));
+ CreateDirectory(test_subdir);
+ ASSERT_TRUE(PathExists(test_subdir));
+
+ FilePath file_name = test_subdir.Append(FPL("Test DeleteDirRecursive.txt"));
+ CreateTextFile(file_name, bogus_content);
+ ASSERT_TRUE(PathExists(file_name));
+
+ FilePath subdir_path1 = test_subdir.Append(FPL("TestSubDir1"));
+ CreateDirectory(subdir_path1);
+ ASSERT_TRUE(PathExists(subdir_path1));
+
+ FilePath subdir_path2 = test_subdir.Append(FPL("TestSubDir2"));
+ CreateDirectory(subdir_path2);
+ ASSERT_TRUE(PathExists(subdir_path2));
+
+ // Delete recursively and check that the empty dir got deleted
+ EXPECT_TRUE(DeleteFile(subdir_path2, true));
+ EXPECT_FALSE(PathExists(subdir_path2));
+
+ // Delete recursively and check that everything got deleted
+ EXPECT_TRUE(DeleteFile(test_subdir, true));
+ EXPECT_FALSE(PathExists(file_name));
+ EXPECT_FALSE(PathExists(subdir_path1));
+ EXPECT_FALSE(PathExists(test_subdir));
+}
+
+TEST_F(FileUtilTest, MoveFileNew) {
+ // Create a file
+ FilePath file_name_from =
+ temp_dir_.path().Append(FILE_PATH_LITERAL("Move_Test_File.txt"));
+ CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
+ ASSERT_TRUE(PathExists(file_name_from));
+
+ // The destination.
+ FilePath file_name_to = temp_dir_.path().Append(
+ FILE_PATH_LITERAL("Move_Test_File_Destination.txt"));
+ ASSERT_FALSE(PathExists(file_name_to));
+
+ EXPECT_TRUE(Move(file_name_from, file_name_to));
+
+ // Check everything has been moved.
+ EXPECT_FALSE(PathExists(file_name_from));
+ EXPECT_TRUE(PathExists(file_name_to));
+}
+
+TEST_F(FileUtilTest, MoveFileExists) {
+ // Create a file
+ FilePath file_name_from =
+ temp_dir_.path().Append(FILE_PATH_LITERAL("Move_Test_File.txt"));
+ CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
+ ASSERT_TRUE(PathExists(file_name_from));
+
+ // The destination name.
+ FilePath file_name_to = temp_dir_.path().Append(
+ FILE_PATH_LITERAL("Move_Test_File_Destination.txt"));
+ CreateTextFile(file_name_to, L"Old file content");
+ ASSERT_TRUE(PathExists(file_name_to));
+
+ EXPECT_TRUE(Move(file_name_from, file_name_to));
+
+ // Check everything has been moved.
+ EXPECT_FALSE(PathExists(file_name_from));
+ EXPECT_TRUE(PathExists(file_name_to));
+ EXPECT_TRUE(L"Gooooooooooooooooooooogle" == ReadTextFile(file_name_to));
+}
+
+TEST_F(FileUtilTest, MoveFileDirExists) {
+ // Create a file
+ FilePath file_name_from =
+ temp_dir_.path().Append(FILE_PATH_LITERAL("Move_Test_File.txt"));
+ CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
+ ASSERT_TRUE(PathExists(file_name_from));
+
+ // The destination directory
+ FilePath dir_name_to =
+ temp_dir_.path().Append(FILE_PATH_LITERAL("Destination"));
+ CreateDirectory(dir_name_to);
+ ASSERT_TRUE(PathExists(dir_name_to));
+
+ EXPECT_FALSE(Move(file_name_from, dir_name_to));
+}
+
+
+TEST_F(FileUtilTest, MoveNew) {
+ // Create a directory
+ FilePath dir_name_from =
+ temp_dir_.path().Append(FILE_PATH_LITERAL("Move_From_Subdir"));
+ CreateDirectory(dir_name_from);
+ ASSERT_TRUE(PathExists(dir_name_from));
+
+ // Create a file under the directory
+ FilePath txt_file_name(FILE_PATH_LITERAL("Move_Test_File.txt"));
+ FilePath file_name_from = dir_name_from.Append(txt_file_name);
+ CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
+ ASSERT_TRUE(PathExists(file_name_from));
+
+ // Move the directory.
+ FilePath dir_name_to =
+ temp_dir_.path().Append(FILE_PATH_LITERAL("Move_To_Subdir"));
+ FilePath file_name_to =
+ dir_name_to.Append(FILE_PATH_LITERAL("Move_Test_File.txt"));
+
+ ASSERT_FALSE(PathExists(dir_name_to));
+
+ EXPECT_TRUE(Move(dir_name_from, dir_name_to));
+
+ // Check everything has been moved.
+ EXPECT_FALSE(PathExists(dir_name_from));
+ EXPECT_FALSE(PathExists(file_name_from));
+ EXPECT_TRUE(PathExists(dir_name_to));
+ EXPECT_TRUE(PathExists(file_name_to));
+
+ // Test path traversal.
+ file_name_from = dir_name_to.Append(txt_file_name);
+ file_name_to = dir_name_to.Append(FILE_PATH_LITERAL(".."));
+ file_name_to = file_name_to.Append(txt_file_name);
+ EXPECT_FALSE(Move(file_name_from, file_name_to));
+ EXPECT_TRUE(PathExists(file_name_from));
+ EXPECT_FALSE(PathExists(file_name_to));
+ EXPECT_TRUE(internal::MoveUnsafe(file_name_from, file_name_to));
+ EXPECT_FALSE(PathExists(file_name_from));
+ EXPECT_TRUE(PathExists(file_name_to));
+}
+
+TEST_F(FileUtilTest, MoveExist) {
+ // Create a directory
+ FilePath dir_name_from =
+ temp_dir_.path().Append(FILE_PATH_LITERAL("Move_From_Subdir"));
+ CreateDirectory(dir_name_from);
+ ASSERT_TRUE(PathExists(dir_name_from));
+
+ // Create a file under the directory
+ FilePath file_name_from =
+ dir_name_from.Append(FILE_PATH_LITERAL("Move_Test_File.txt"));
+ CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
+ ASSERT_TRUE(PathExists(file_name_from));
+
+ // Move the directory
+ FilePath dir_name_exists =
+ temp_dir_.path().Append(FILE_PATH_LITERAL("Destination"));
+
+ FilePath dir_name_to =
+ dir_name_exists.Append(FILE_PATH_LITERAL("Move_To_Subdir"));
+ FilePath file_name_to =
+ dir_name_to.Append(FILE_PATH_LITERAL("Move_Test_File.txt"));
+
+ // Create the destination directory.
+ CreateDirectory(dir_name_exists);
+ ASSERT_TRUE(PathExists(dir_name_exists));
+
+ EXPECT_TRUE(Move(dir_name_from, dir_name_to));
+
+ // Check everything has been moved.
+ EXPECT_FALSE(PathExists(dir_name_from));
+ EXPECT_FALSE(PathExists(file_name_from));
+ EXPECT_TRUE(PathExists(dir_name_to));
+ EXPECT_TRUE(PathExists(file_name_to));
+}
+
+TEST_F(FileUtilTest, CopyDirectoryRecursivelyNew) {
+ // Create a directory.
+ FilePath dir_name_from =
+ temp_dir_.path().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
+ CreateDirectory(dir_name_from);
+ ASSERT_TRUE(PathExists(dir_name_from));
+
+ // Create a file under the directory.
+ FilePath file_name_from =
+ dir_name_from.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
+ CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
+ ASSERT_TRUE(PathExists(file_name_from));
+
+ // Create a subdirectory.
+ FilePath subdir_name_from =
+ dir_name_from.Append(FILE_PATH_LITERAL("Subdir"));
+ CreateDirectory(subdir_name_from);
+ ASSERT_TRUE(PathExists(subdir_name_from));
+
+ // Create a file under the subdirectory.
+ FilePath file_name2_from =
+ subdir_name_from.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
+ CreateTextFile(file_name2_from, L"Gooooooooooooooooooooogle");
+ ASSERT_TRUE(PathExists(file_name2_from));
+
+ // Copy the directory recursively.
+ FilePath dir_name_to =
+ temp_dir_.path().Append(FILE_PATH_LITERAL("Copy_To_Subdir"));
+ FilePath file_name_to =
+ dir_name_to.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
+ FilePath subdir_name_to =
+ dir_name_to.Append(FILE_PATH_LITERAL("Subdir"));
+ FilePath file_name2_to =
+ subdir_name_to.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
+
+ ASSERT_FALSE(PathExists(dir_name_to));
+
+ EXPECT_TRUE(CopyDirectory(dir_name_from, dir_name_to, true));
+
+ // Check everything has been copied.
+ EXPECT_TRUE(PathExists(dir_name_from));
+ EXPECT_TRUE(PathExists(file_name_from));
+ EXPECT_TRUE(PathExists(subdir_name_from));
+ EXPECT_TRUE(PathExists(file_name2_from));
+ EXPECT_TRUE(PathExists(dir_name_to));
+ EXPECT_TRUE(PathExists(file_name_to));
+ EXPECT_TRUE(PathExists(subdir_name_to));
+ EXPECT_TRUE(PathExists(file_name2_to));
+}
+
+TEST_F(FileUtilTest, CopyDirectoryRecursivelyExists) {
+ // Create a directory.
+ FilePath dir_name_from =
+ temp_dir_.path().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
+ CreateDirectory(dir_name_from);
+ ASSERT_TRUE(PathExists(dir_name_from));
+
+ // Create a file under the directory.
+ FilePath file_name_from =
+ dir_name_from.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
+ CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
+ ASSERT_TRUE(PathExists(file_name_from));
+
+ // Create a subdirectory.
+ FilePath subdir_name_from =
+ dir_name_from.Append(FILE_PATH_LITERAL("Subdir"));
+ CreateDirectory(subdir_name_from);
+ ASSERT_TRUE(PathExists(subdir_name_from));
+
+ // Create a file under the subdirectory.
+ FilePath file_name2_from =
+ subdir_name_from.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
+ CreateTextFile(file_name2_from, L"Gooooooooooooooooooooogle");
+ ASSERT_TRUE(PathExists(file_name2_from));
+
+ // Copy the directory recursively.
+ FilePath dir_name_exists =
+ temp_dir_.path().Append(FILE_PATH_LITERAL("Destination"));
+
+ FilePath dir_name_to =
+ dir_name_exists.Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
+ FilePath file_name_to =
+ dir_name_to.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
+ FilePath subdir_name_to =
+ dir_name_to.Append(FILE_PATH_LITERAL("Subdir"));
+ FilePath file_name2_to =
+ subdir_name_to.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
+
+ // Create the destination directory.
+ CreateDirectory(dir_name_exists);
+ ASSERT_TRUE(PathExists(dir_name_exists));
+
+ EXPECT_TRUE(CopyDirectory(dir_name_from, dir_name_exists, true));
+
+ // Check everything has been copied.
+ EXPECT_TRUE(PathExists(dir_name_from));
+ EXPECT_TRUE(PathExists(file_name_from));
+ EXPECT_TRUE(PathExists(subdir_name_from));
+ EXPECT_TRUE(PathExists(file_name2_from));
+ EXPECT_TRUE(PathExists(dir_name_to));
+ EXPECT_TRUE(PathExists(file_name_to));
+ EXPECT_TRUE(PathExists(subdir_name_to));
+ EXPECT_TRUE(PathExists(file_name2_to));
+}
+
+TEST_F(FileUtilTest, CopyDirectoryNew) {
+ // Create a directory.
+ FilePath dir_name_from =
+ temp_dir_.path().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
+ CreateDirectory(dir_name_from);
+ ASSERT_TRUE(PathExists(dir_name_from));
+
+ // Create a file under the directory.
+ FilePath file_name_from =
+ dir_name_from.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
+ CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
+ ASSERT_TRUE(PathExists(file_name_from));
+
+ // Create a subdirectory.
+ FilePath subdir_name_from =
+ dir_name_from.Append(FILE_PATH_LITERAL("Subdir"));
+ CreateDirectory(subdir_name_from);
+ ASSERT_TRUE(PathExists(subdir_name_from));
+
+ // Create a file under the subdirectory.
+ FilePath file_name2_from =
+ subdir_name_from.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
+ CreateTextFile(file_name2_from, L"Gooooooooooooooooooooogle");
+ ASSERT_TRUE(PathExists(file_name2_from));
+
+ // Copy the directory not recursively.
+ FilePath dir_name_to =
+ temp_dir_.path().Append(FILE_PATH_LITERAL("Copy_To_Subdir"));
+ FilePath file_name_to =
+ dir_name_to.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
+ FilePath subdir_name_to =
+ dir_name_to.Append(FILE_PATH_LITERAL("Subdir"));
+
+ ASSERT_FALSE(PathExists(dir_name_to));
+
+ EXPECT_TRUE(CopyDirectory(dir_name_from, dir_name_to, false));
+
+ // Check everything has been copied.
+ EXPECT_TRUE(PathExists(dir_name_from));
+ EXPECT_TRUE(PathExists(file_name_from));
+ EXPECT_TRUE(PathExists(subdir_name_from));
+ EXPECT_TRUE(PathExists(file_name2_from));
+ EXPECT_TRUE(PathExists(dir_name_to));
+ EXPECT_TRUE(PathExists(file_name_to));
+ EXPECT_FALSE(PathExists(subdir_name_to));
+}
+
+TEST_F(FileUtilTest, CopyDirectoryExists) {
+ // Create a directory.
+ FilePath dir_name_from =
+ temp_dir_.path().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
+ CreateDirectory(dir_name_from);
+ ASSERT_TRUE(PathExists(dir_name_from));
+
+ // Create a file under the directory.
+ FilePath file_name_from =
+ dir_name_from.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
+ CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
+ ASSERT_TRUE(PathExists(file_name_from));
+
+ // Create a subdirectory.
+ FilePath subdir_name_from =
+ dir_name_from.Append(FILE_PATH_LITERAL("Subdir"));
+ CreateDirectory(subdir_name_from);
+ ASSERT_TRUE(PathExists(subdir_name_from));
+
+ // Create a file under the subdirectory.
+ FilePath file_name2_from =
+ subdir_name_from.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
+ CreateTextFile(file_name2_from, L"Gooooooooooooooooooooogle");
+ ASSERT_TRUE(PathExists(file_name2_from));
+
+ // Copy the directory not recursively.
+ FilePath dir_name_to =
+ temp_dir_.path().Append(FILE_PATH_LITERAL("Copy_To_Subdir"));
+ FilePath file_name_to =
+ dir_name_to.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
+ FilePath subdir_name_to =
+ dir_name_to.Append(FILE_PATH_LITERAL("Subdir"));
+
+ // Create the destination directory.
+ CreateDirectory(dir_name_to);
+ ASSERT_TRUE(PathExists(dir_name_to));
+
+ EXPECT_TRUE(CopyDirectory(dir_name_from, dir_name_to, false));
+
+ // Check everything has been copied.
+ EXPECT_TRUE(PathExists(dir_name_from));
+ EXPECT_TRUE(PathExists(file_name_from));
+ EXPECT_TRUE(PathExists(subdir_name_from));
+ EXPECT_TRUE(PathExists(file_name2_from));
+ EXPECT_TRUE(PathExists(dir_name_to));
+ EXPECT_TRUE(PathExists(file_name_to));
+ EXPECT_FALSE(PathExists(subdir_name_to));
+}
+
+TEST_F(FileUtilTest, CopyFileWithCopyDirectoryRecursiveToNew) {
+ // Create a file
+ FilePath file_name_from =
+ temp_dir_.path().Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
+ CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
+ ASSERT_TRUE(PathExists(file_name_from));
+
+ // The destination name
+ FilePath file_name_to = temp_dir_.path().Append(
+ FILE_PATH_LITERAL("Copy_Test_File_Destination.txt"));
+ ASSERT_FALSE(PathExists(file_name_to));
+
+ EXPECT_TRUE(CopyDirectory(file_name_from, file_name_to, true));
+
+ // Check the has been copied
+ EXPECT_TRUE(PathExists(file_name_to));
+}
+
+TEST_F(FileUtilTest, CopyFileWithCopyDirectoryRecursiveToExisting) {
+ // Create a file
+ FilePath file_name_from =
+ temp_dir_.path().Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
+ CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
+ ASSERT_TRUE(PathExists(file_name_from));
+
+ // The destination name
+ FilePath file_name_to = temp_dir_.path().Append(
+ FILE_PATH_LITERAL("Copy_Test_File_Destination.txt"));
+ CreateTextFile(file_name_to, L"Old file content");
+ ASSERT_TRUE(PathExists(file_name_to));
+
+ EXPECT_TRUE(CopyDirectory(file_name_from, file_name_to, true));
+
+ // Check the has been copied
+ EXPECT_TRUE(PathExists(file_name_to));
+ EXPECT_TRUE(L"Gooooooooooooooooooooogle" == ReadTextFile(file_name_to));
+}
+
+TEST_F(FileUtilTest, CopyFileWithCopyDirectoryRecursiveToExistingDirectory) {
+ // Create a file
+ FilePath file_name_from =
+ temp_dir_.path().Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
+ CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
+ ASSERT_TRUE(PathExists(file_name_from));
+
+ // The destination
+ FilePath dir_name_to =
+ temp_dir_.path().Append(FILE_PATH_LITERAL("Destination"));
+ CreateDirectory(dir_name_to);
+ ASSERT_TRUE(PathExists(dir_name_to));
+ FilePath file_name_to =
+ dir_name_to.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
+
+ EXPECT_TRUE(CopyDirectory(file_name_from, dir_name_to, true));
+
+ // Check the has been copied
+ EXPECT_TRUE(PathExists(file_name_to));
+}
+
+TEST_F(FileUtilTest, CopyDirectoryWithTrailingSeparators) {
+ // Create a directory.
+ FilePath dir_name_from =
+ temp_dir_.path().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
+ CreateDirectory(dir_name_from);
+ ASSERT_TRUE(PathExists(dir_name_from));
+
+ // Create a file under the directory.
+ FilePath file_name_from =
+ dir_name_from.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
+ CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
+ ASSERT_TRUE(PathExists(file_name_from));
+
+ // Copy the directory recursively.
+ FilePath dir_name_to =
+ temp_dir_.path().Append(FILE_PATH_LITERAL("Copy_To_Subdir"));
+ FilePath file_name_to =
+ dir_name_to.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
+
+ // Create from path with trailing separators.
+#if defined(OS_WIN)
+ FilePath from_path =
+ temp_dir_.path().Append(FILE_PATH_LITERAL("Copy_From_Subdir\\\\\\"));
+#elif defined (OS_POSIX)
+ FilePath from_path =
+ temp_dir_.path().Append(FILE_PATH_LITERAL("Copy_From_Subdir///"));
+#endif
+
+ EXPECT_TRUE(CopyDirectory(from_path, dir_name_to, true));
+
+ // Check everything has been copied.
+ EXPECT_TRUE(PathExists(dir_name_from));
+ EXPECT_TRUE(PathExists(file_name_from));
+ EXPECT_TRUE(PathExists(dir_name_to));
+ EXPECT_TRUE(PathExists(file_name_to));
+}
+
+// Sets the source file to read-only.
+void SetReadOnly(const FilePath& path) {
+#if defined(OS_WIN)
+ // On Windows, it involves setting a bit.
+ DWORD attrs = GetFileAttributes(path.value().c_str());
+ ASSERT_NE(INVALID_FILE_ATTRIBUTES, attrs);
+ ASSERT_TRUE(SetFileAttributes(
+ path.value().c_str(), attrs | FILE_ATTRIBUTE_READONLY));
+ attrs = GetFileAttributes(path.value().c_str());
+ // Files in the temporary directory should not be indexed ever. If this
+ // assumption change, fix this unit test accordingly.
+ // FILE_ATTRIBUTE_NOT_CONTENT_INDEXED doesn't exist on XP.
+ DWORD expected = FILE_ATTRIBUTE_ARCHIVE | FILE_ATTRIBUTE_READONLY;
+ if (win::GetVersion() >= win::VERSION_VISTA)
+ expected |= FILE_ATTRIBUTE_NOT_CONTENT_INDEXED;
+ ASSERT_EQ(expected, attrs);
+#else
+ // On all other platforms, it involves removing the write bit.
+ EXPECT_TRUE(SetPosixFilePermissions(path, S_IRUSR));
+#endif
+}
+
+bool IsReadOnly(const FilePath& path) {
+#if defined(OS_WIN)
+ DWORD attrs = GetFileAttributes(path.value().c_str());
+ EXPECT_NE(INVALID_FILE_ATTRIBUTES, attrs);
+ return attrs & FILE_ATTRIBUTE_READONLY;
+#else
+ int mode = 0;
+ EXPECT_TRUE(GetPosixFilePermissions(path, &mode));
+ return !(mode & S_IWUSR);
+#endif
+}
+
+TEST_F(FileUtilTest, CopyDirectoryACL) {
+ // Create a directory.
+ FilePath src = temp_dir_.path().Append(FILE_PATH_LITERAL("src"));
+ CreateDirectory(src);
+ ASSERT_TRUE(PathExists(src));
+
+ // Create a file under the directory.
+ FilePath src_file = src.Append(FILE_PATH_LITERAL("src.txt"));
+ CreateTextFile(src_file, L"Gooooooooooooooooooooogle");
+ SetReadOnly(src_file);
+ ASSERT_TRUE(IsReadOnly(src_file));
+
+ // Copy the directory recursively.
+ FilePath dst = temp_dir_.path().Append(FILE_PATH_LITERAL("dst"));
+ FilePath dst_file = dst.Append(FILE_PATH_LITERAL("src.txt"));
+ EXPECT_TRUE(CopyDirectory(src, dst, true));
+
+ ASSERT_FALSE(IsReadOnly(dst_file));
+}
+
+TEST_F(FileUtilTest, CopyFile) {
+ // Create a directory
+ FilePath dir_name_from =
+ temp_dir_.path().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
+ CreateDirectory(dir_name_from);
+ ASSERT_TRUE(PathExists(dir_name_from));
+
+ // Create a file under the directory
+ FilePath file_name_from =
+ dir_name_from.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
+ const std::wstring file_contents(L"Gooooooooooooooooooooogle");
+ CreateTextFile(file_name_from, file_contents);
+ ASSERT_TRUE(PathExists(file_name_from));
+
+ // Copy the file.
+ FilePath dest_file = dir_name_from.Append(FILE_PATH_LITERAL("DestFile.txt"));
+ ASSERT_TRUE(CopyFile(file_name_from, dest_file));
+
+ // Copy the file to another location using '..' in the path.
+ FilePath dest_file2(dir_name_from);
+ dest_file2 = dest_file2.AppendASCII("..");
+ dest_file2 = dest_file2.AppendASCII("DestFile.txt");
+ ASSERT_FALSE(CopyFile(file_name_from, dest_file2));
+ ASSERT_TRUE(internal::CopyFileUnsafe(file_name_from, dest_file2));
+
+ FilePath dest_file2_test(dir_name_from);
+ dest_file2_test = dest_file2_test.DirName();
+ dest_file2_test = dest_file2_test.AppendASCII("DestFile.txt");
+
+ // Check everything has been copied.
+ EXPECT_TRUE(PathExists(file_name_from));
+ EXPECT_TRUE(PathExists(dest_file));
+ const std::wstring read_contents = ReadTextFile(dest_file);
+ EXPECT_EQ(file_contents, read_contents);
+ EXPECT_TRUE(PathExists(dest_file2_test));
+ EXPECT_TRUE(PathExists(dest_file2));
+}
+
+TEST_F(FileUtilTest, CopyFileACL) {
+ // While FileUtilTest.CopyFile asserts the content is correctly copied over,
+ // this test case asserts the access control bits are meeting expectations in
+ // CopyFileUnsafe().
+ FilePath src = temp_dir_.path().Append(FILE_PATH_LITERAL("src.txt"));
+ const std::wstring file_contents(L"Gooooooooooooooooooooogle");
+ CreateTextFile(src, file_contents);
+
+ // Set the source file to read-only.
+ ASSERT_FALSE(IsReadOnly(src));
+ SetReadOnly(src);
+ ASSERT_TRUE(IsReadOnly(src));
+
+ // Copy the file.
+ FilePath dst = temp_dir_.path().Append(FILE_PATH_LITERAL("dst.txt"));
+ ASSERT_TRUE(CopyFile(src, dst));
+ EXPECT_EQ(file_contents, ReadTextFile(dst));
+
+ ASSERT_FALSE(IsReadOnly(dst));
+}
+
+// file_util winds up using autoreleased objects on the Mac, so this needs
+// to be a PlatformTest.
+typedef PlatformTest ReadOnlyFileUtilTest;
+
+TEST_F(ReadOnlyFileUtilTest, ContentsEqual) {
+ FilePath data_dir;
+ ASSERT_TRUE(PathService::Get(DIR_TEST_DATA, &data_dir));
+ data_dir = data_dir.AppendASCII("file_util");
+ ASSERT_TRUE(PathExists(data_dir));
+
+ FilePath original_file =
+ data_dir.Append(FILE_PATH_LITERAL("original.txt"));
+ FilePath same_file =
+ data_dir.Append(FILE_PATH_LITERAL("same.txt"));
+ FilePath same_length_file =
+ data_dir.Append(FILE_PATH_LITERAL("same_length.txt"));
+ FilePath different_file =
+ data_dir.Append(FILE_PATH_LITERAL("different.txt"));
+ FilePath different_first_file =
+ data_dir.Append(FILE_PATH_LITERAL("different_first.txt"));
+ FilePath different_last_file =
+ data_dir.Append(FILE_PATH_LITERAL("different_last.txt"));
+ FilePath empty1_file =
+ data_dir.Append(FILE_PATH_LITERAL("empty1.txt"));
+ FilePath empty2_file =
+ data_dir.Append(FILE_PATH_LITERAL("empty2.txt"));
+ FilePath shortened_file =
+ data_dir.Append(FILE_PATH_LITERAL("shortened.txt"));
+ FilePath binary_file =
+ data_dir.Append(FILE_PATH_LITERAL("binary_file.bin"));
+ FilePath binary_file_same =
+ data_dir.Append(FILE_PATH_LITERAL("binary_file_same.bin"));
+ FilePath binary_file_diff =
+ data_dir.Append(FILE_PATH_LITERAL("binary_file_diff.bin"));
+
+ EXPECT_TRUE(ContentsEqual(original_file, original_file));
+ EXPECT_TRUE(ContentsEqual(original_file, same_file));
+ EXPECT_FALSE(ContentsEqual(original_file, same_length_file));
+ EXPECT_FALSE(ContentsEqual(original_file, different_file));
+ EXPECT_FALSE(ContentsEqual(FilePath(FILE_PATH_LITERAL("bogusname")),
+ FilePath(FILE_PATH_LITERAL("bogusname"))));
+ EXPECT_FALSE(ContentsEqual(original_file, different_first_file));
+ EXPECT_FALSE(ContentsEqual(original_file, different_last_file));
+ EXPECT_TRUE(ContentsEqual(empty1_file, empty2_file));
+ EXPECT_FALSE(ContentsEqual(original_file, shortened_file));
+ EXPECT_FALSE(ContentsEqual(shortened_file, original_file));
+ EXPECT_TRUE(ContentsEqual(binary_file, binary_file_same));
+ EXPECT_FALSE(ContentsEqual(binary_file, binary_file_diff));
+}
+
+TEST_F(ReadOnlyFileUtilTest, TextContentsEqual) {
+ FilePath data_dir;
+ ASSERT_TRUE(PathService::Get(DIR_TEST_DATA, &data_dir));
+ data_dir = data_dir.AppendASCII("file_util");
+ ASSERT_TRUE(PathExists(data_dir));
+
+ FilePath original_file =
+ data_dir.Append(FILE_PATH_LITERAL("original.txt"));
+ FilePath same_file =
+ data_dir.Append(FILE_PATH_LITERAL("same.txt"));
+ FilePath crlf_file =
+ data_dir.Append(FILE_PATH_LITERAL("crlf.txt"));
+ FilePath shortened_file =
+ data_dir.Append(FILE_PATH_LITERAL("shortened.txt"));
+ FilePath different_file =
+ data_dir.Append(FILE_PATH_LITERAL("different.txt"));
+ FilePath different_first_file =
+ data_dir.Append(FILE_PATH_LITERAL("different_first.txt"));
+ FilePath different_last_file =
+ data_dir.Append(FILE_PATH_LITERAL("different_last.txt"));
+ FilePath first1_file =
+ data_dir.Append(FILE_PATH_LITERAL("first1.txt"));
+ FilePath first2_file =
+ data_dir.Append(FILE_PATH_LITERAL("first2.txt"));
+ FilePath empty1_file =
+ data_dir.Append(FILE_PATH_LITERAL("empty1.txt"));
+ FilePath empty2_file =
+ data_dir.Append(FILE_PATH_LITERAL("empty2.txt"));
+ FilePath blank_line_file =
+ data_dir.Append(FILE_PATH_LITERAL("blank_line.txt"));
+ FilePath blank_line_crlf_file =
+ data_dir.Append(FILE_PATH_LITERAL("blank_line_crlf.txt"));
+
+ EXPECT_TRUE(TextContentsEqual(original_file, same_file));
+ EXPECT_TRUE(TextContentsEqual(original_file, crlf_file));
+ EXPECT_FALSE(TextContentsEqual(original_file, shortened_file));
+ EXPECT_FALSE(TextContentsEqual(original_file, different_file));
+ EXPECT_FALSE(TextContentsEqual(original_file, different_first_file));
+ EXPECT_FALSE(TextContentsEqual(original_file, different_last_file));
+ EXPECT_FALSE(TextContentsEqual(first1_file, first2_file));
+ EXPECT_TRUE(TextContentsEqual(empty1_file, empty2_file));
+ EXPECT_FALSE(TextContentsEqual(original_file, empty1_file));
+ EXPECT_TRUE(TextContentsEqual(blank_line_file, blank_line_crlf_file));
+}
+
+// We don't need equivalent functionality outside of Windows.
+#if defined(OS_WIN)
+TEST_F(FileUtilTest, CopyAndDeleteDirectoryTest) {
+ // Create a directory
+ FilePath dir_name_from =
+ temp_dir_.path().Append(FILE_PATH_LITERAL("CopyAndDelete_From_Subdir"));
+ CreateDirectory(dir_name_from);
+ ASSERT_TRUE(PathExists(dir_name_from));
+
+ // Create a file under the directory
+ FilePath file_name_from =
+ dir_name_from.Append(FILE_PATH_LITERAL("CopyAndDelete_Test_File.txt"));
+ CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
+ ASSERT_TRUE(PathExists(file_name_from));
+
+ // Move the directory by using CopyAndDeleteDirectory
+ FilePath dir_name_to = temp_dir_.path().Append(
+ FILE_PATH_LITERAL("CopyAndDelete_To_Subdir"));
+ FilePath file_name_to =
+ dir_name_to.Append(FILE_PATH_LITERAL("CopyAndDelete_Test_File.txt"));
+
+ ASSERT_FALSE(PathExists(dir_name_to));
+
+ EXPECT_TRUE(internal::CopyAndDeleteDirectory(dir_name_from,
+ dir_name_to));
+
+ // Check everything has been moved.
+ EXPECT_FALSE(PathExists(dir_name_from));
+ EXPECT_FALSE(PathExists(file_name_from));
+ EXPECT_TRUE(PathExists(dir_name_to));
+ EXPECT_TRUE(PathExists(file_name_to));
+}
+
+TEST_F(FileUtilTest, GetTempDirTest) {
+ static const TCHAR* kTmpKey = _T("TMP");
+ static const TCHAR* kTmpValues[] = {
+ _T(""), _T("C:"), _T("C:\\"), _T("C:\\tmp"), _T("C:\\tmp\\")
+ };
+ // Save the original $TMP.
+ size_t original_tmp_size;
+ TCHAR* original_tmp;
+ ASSERT_EQ(0, ::_tdupenv_s(&original_tmp, &original_tmp_size, kTmpKey));
+ // original_tmp may be NULL.
+
+ for (unsigned int i = 0; i < arraysize(kTmpValues); ++i) {
+ FilePath path;
+ ::_tputenv_s(kTmpKey, kTmpValues[i]);
+ GetTempDir(&path);
+ EXPECT_TRUE(path.IsAbsolute()) << "$TMP=" << kTmpValues[i] <<
+ " result=" << path.value();
+ }
+
+ // Restore the original $TMP.
+ if (original_tmp) {
+ ::_tputenv_s(kTmpKey, original_tmp);
+ free(original_tmp);
+ } else {
+ ::_tputenv_s(kTmpKey, _T(""));
+ }
+}
+#endif // OS_WIN
+
+TEST_F(FileUtilTest, CreateTemporaryFileTest) {
+ FilePath temp_files[3];
+ for (int i = 0; i < 3; i++) {
+ ASSERT_TRUE(CreateTemporaryFile(&(temp_files[i])));
+ EXPECT_TRUE(PathExists(temp_files[i]));
+ EXPECT_FALSE(DirectoryExists(temp_files[i]));
+ }
+ for (int i = 0; i < 3; i++)
+ EXPECT_FALSE(temp_files[i] == temp_files[(i+1)%3]);
+ for (int i = 0; i < 3; i++)
+ EXPECT_TRUE(DeleteFile(temp_files[i], false));
+}
+
+TEST_F(FileUtilTest, CreateAndOpenTemporaryFileTest) {
+ FilePath names[3];
+ FILE* fps[3];
+ int i;
+
+ // Create; make sure they are open and exist.
+ for (i = 0; i < 3; ++i) {
+ fps[i] = CreateAndOpenTemporaryFile(&(names[i]));
+ ASSERT_TRUE(fps[i]);
+ EXPECT_TRUE(PathExists(names[i]));
+ }
+
+ // Make sure all names are unique.
+ for (i = 0; i < 3; ++i) {
+ EXPECT_FALSE(names[i] == names[(i+1)%3]);
+ }
+
+ // Close and delete.
+ for (i = 0; i < 3; ++i) {
+ EXPECT_TRUE(CloseFile(fps[i]));
+ EXPECT_TRUE(DeleteFile(names[i], false));
+ }
+}
+
+TEST_F(FileUtilTest, FileToFILE) {
+ File file;
+ FILE* stream = FileToFILE(file.Pass(), "w");
+ EXPECT_FALSE(stream);
+
+ FilePath file_name = temp_dir_.path().Append(FPL("The file.txt"));
+ file = File(file_name, File::FLAG_CREATE | File::FLAG_WRITE);
+ EXPECT_TRUE(file.IsValid());
+
+ stream = FileToFILE(file.Pass(), "w");
+ EXPECT_TRUE(stream);
+ EXPECT_FALSE(file.IsValid());
+ EXPECT_TRUE(CloseFile(stream));
+}
+
+TEST_F(FileUtilTest, CreateNewTempDirectoryTest) {
+ FilePath temp_dir;
+ ASSERT_TRUE(CreateNewTempDirectory(FilePath::StringType(), &temp_dir));
+ EXPECT_TRUE(PathExists(temp_dir));
+ EXPECT_TRUE(DeleteFile(temp_dir, false));
+}
+
+TEST_F(FileUtilTest, CreateNewTemporaryDirInDirTest) {
+ FilePath new_dir;
+ ASSERT_TRUE(CreateTemporaryDirInDir(
+ temp_dir_.path(),
+ FILE_PATH_LITERAL("CreateNewTemporaryDirInDirTest"),
+ &new_dir));
+ EXPECT_TRUE(PathExists(new_dir));
+ EXPECT_TRUE(temp_dir_.path().IsParent(new_dir));
+ EXPECT_TRUE(DeleteFile(new_dir, false));
+}
+
+#if defined(OS_POSIX)
+TEST_F(FileUtilTest, GetShmemTempDirTest) {
+ FilePath dir;
+ EXPECT_TRUE(GetShmemTempDir(false, &dir));
+ EXPECT_TRUE(DirectoryExists(dir));
+}
+#endif
+
+TEST_F(FileUtilTest, GetHomeDirTest) {
+#if !defined(OS_ANDROID) // Not implemented on Android.
+ // We don't actually know what the home directory is supposed to be without
+ // calling some OS functions which would just duplicate the implementation.
+ // So here we just test that it returns something "reasonable".
+ FilePath home = GetHomeDir();
+ ASSERT_FALSE(home.empty());
+ ASSERT_TRUE(home.IsAbsolute());
+#endif
+}
+
+TEST_F(FileUtilTest, CreateDirectoryTest) {
+ FilePath test_root =
+ temp_dir_.path().Append(FILE_PATH_LITERAL("create_directory_test"));
+#if defined(OS_WIN)
+ FilePath test_path =
+ test_root.Append(FILE_PATH_LITERAL("dir\\tree\\likely\\doesnt\\exist\\"));
+#elif defined(OS_POSIX)
+ FilePath test_path =
+ test_root.Append(FILE_PATH_LITERAL("dir/tree/likely/doesnt/exist/"));
+#endif
+
+ EXPECT_FALSE(PathExists(test_path));
+ EXPECT_TRUE(CreateDirectory(test_path));
+ EXPECT_TRUE(PathExists(test_path));
+ // CreateDirectory returns true if the DirectoryExists returns true.
+ EXPECT_TRUE(CreateDirectory(test_path));
+
+ // Doesn't work to create it on top of a non-dir
+ test_path = test_path.Append(FILE_PATH_LITERAL("foobar.txt"));
+ EXPECT_FALSE(PathExists(test_path));
+ CreateTextFile(test_path, L"test file");
+ EXPECT_TRUE(PathExists(test_path));
+ EXPECT_FALSE(CreateDirectory(test_path));
+
+ EXPECT_TRUE(DeleteFile(test_root, true));
+ EXPECT_FALSE(PathExists(test_root));
+ EXPECT_FALSE(PathExists(test_path));
+
+ // Verify assumptions made by the Windows implementation:
+ // 1. The current directory always exists.
+ // 2. The root directory always exists.
+ ASSERT_TRUE(DirectoryExists(FilePath(FilePath::kCurrentDirectory)));
+ FilePath top_level = test_root;
+ while (top_level != top_level.DirName()) {
+ top_level = top_level.DirName();
+ }
+ ASSERT_TRUE(DirectoryExists(top_level));
+
+ // Given these assumptions hold, it should be safe to
+ // test that "creating" these directories succeeds.
+ EXPECT_TRUE(CreateDirectory(
+ FilePath(FilePath::kCurrentDirectory)));
+ EXPECT_TRUE(CreateDirectory(top_level));
+
+#if defined(OS_WIN)
+ FilePath invalid_drive(FILE_PATH_LITERAL("o:\\"));
+ FilePath invalid_path =
+ invalid_drive.Append(FILE_PATH_LITERAL("some\\inaccessible\\dir"));
+ if (!PathExists(invalid_drive)) {
+ EXPECT_FALSE(CreateDirectory(invalid_path));
+ }
+#endif
+}
+
+TEST_F(FileUtilTest, DetectDirectoryTest) {
+ // Check a directory
+ FilePath test_root =
+ temp_dir_.path().Append(FILE_PATH_LITERAL("detect_directory_test"));
+ EXPECT_FALSE(PathExists(test_root));
+ EXPECT_TRUE(CreateDirectory(test_root));
+ EXPECT_TRUE(PathExists(test_root));
+ EXPECT_TRUE(DirectoryExists(test_root));
+ // Check a file
+ FilePath test_path =
+ test_root.Append(FILE_PATH_LITERAL("foobar.txt"));
+ EXPECT_FALSE(PathExists(test_path));
+ CreateTextFile(test_path, L"test file");
+ EXPECT_TRUE(PathExists(test_path));
+ EXPECT_FALSE(DirectoryExists(test_path));
+ EXPECT_TRUE(DeleteFile(test_path, false));
+
+ EXPECT_TRUE(DeleteFile(test_root, true));
+}
+
+TEST_F(FileUtilTest, FileEnumeratorTest) {
+ // Test an empty directory.
+ FileEnumerator f0(temp_dir_.path(), true, FILES_AND_DIRECTORIES);
+ EXPECT_EQ(FPL(""), f0.Next().value());
+ EXPECT_EQ(FPL(""), f0.Next().value());
+
+ // Test an empty directory, non-recursively, including "..".
+ FileEnumerator f0_dotdot(temp_dir_.path(), false,
+ FILES_AND_DIRECTORIES | FileEnumerator::INCLUDE_DOT_DOT);
+ EXPECT_EQ(temp_dir_.path().Append(FPL("..")).value(),
+ f0_dotdot.Next().value());
+ EXPECT_EQ(FPL(""), f0_dotdot.Next().value());
+
+ // create the directories
+ FilePath dir1 = temp_dir_.path().Append(FPL("dir1"));
+ EXPECT_TRUE(CreateDirectory(dir1));
+ FilePath dir2 = temp_dir_.path().Append(FPL("dir2"));
+ EXPECT_TRUE(CreateDirectory(dir2));
+ FilePath dir2inner = dir2.Append(FPL("inner"));
+ EXPECT_TRUE(CreateDirectory(dir2inner));
+
+ // create the files
+ FilePath dir2file = dir2.Append(FPL("dir2file.txt"));
+ CreateTextFile(dir2file, std::wstring());
+ FilePath dir2innerfile = dir2inner.Append(FPL("innerfile.txt"));
+ CreateTextFile(dir2innerfile, std::wstring());
+ FilePath file1 = temp_dir_.path().Append(FPL("file1.txt"));
+ CreateTextFile(file1, std::wstring());
+ FilePath file2_rel = dir2.Append(FilePath::kParentDirectory)
+ .Append(FPL("file2.txt"));
+ CreateTextFile(file2_rel, std::wstring());
+ FilePath file2_abs = temp_dir_.path().Append(FPL("file2.txt"));
+
+ // Only enumerate files.
+ FileEnumerator f1(temp_dir_.path(), true, FileEnumerator::FILES);
+ FindResultCollector c1(f1);
+ EXPECT_TRUE(c1.HasFile(file1));
+ EXPECT_TRUE(c1.HasFile(file2_abs));
+ EXPECT_TRUE(c1.HasFile(dir2file));
+ EXPECT_TRUE(c1.HasFile(dir2innerfile));
+ EXPECT_EQ(4, c1.size());
+
+ // Only enumerate directories.
+ FileEnumerator f2(temp_dir_.path(), true, FileEnumerator::DIRECTORIES);
+ FindResultCollector c2(f2);
+ EXPECT_TRUE(c2.HasFile(dir1));
+ EXPECT_TRUE(c2.HasFile(dir2));
+ EXPECT_TRUE(c2.HasFile(dir2inner));
+ EXPECT_EQ(3, c2.size());
+
+ // Only enumerate directories non-recursively.
+ FileEnumerator f2_non_recursive(
+ temp_dir_.path(), false, FileEnumerator::DIRECTORIES);
+ FindResultCollector c2_non_recursive(f2_non_recursive);
+ EXPECT_TRUE(c2_non_recursive.HasFile(dir1));
+ EXPECT_TRUE(c2_non_recursive.HasFile(dir2));
+ EXPECT_EQ(2, c2_non_recursive.size());
+
+ // Only enumerate directories, non-recursively, including "..".
+ FileEnumerator f2_dotdot(temp_dir_.path(), false,
+ FileEnumerator::DIRECTORIES |
+ FileEnumerator::INCLUDE_DOT_DOT);
+ FindResultCollector c2_dotdot(f2_dotdot);
+ EXPECT_TRUE(c2_dotdot.HasFile(dir1));
+ EXPECT_TRUE(c2_dotdot.HasFile(dir2));
+ EXPECT_TRUE(c2_dotdot.HasFile(temp_dir_.path().Append(FPL(".."))));
+ EXPECT_EQ(3, c2_dotdot.size());
+
+ // Enumerate files and directories.
+ FileEnumerator f3(temp_dir_.path(), true, FILES_AND_DIRECTORIES);
+ FindResultCollector c3(f3);
+ EXPECT_TRUE(c3.HasFile(dir1));
+ EXPECT_TRUE(c3.HasFile(dir2));
+ EXPECT_TRUE(c3.HasFile(file1));
+ EXPECT_TRUE(c3.HasFile(file2_abs));
+ EXPECT_TRUE(c3.HasFile(dir2file));
+ EXPECT_TRUE(c3.HasFile(dir2inner));
+ EXPECT_TRUE(c3.HasFile(dir2innerfile));
+ EXPECT_EQ(7, c3.size());
+
+ // Non-recursive operation.
+ FileEnumerator f4(temp_dir_.path(), false, FILES_AND_DIRECTORIES);
+ FindResultCollector c4(f4);
+ EXPECT_TRUE(c4.HasFile(dir2));
+ EXPECT_TRUE(c4.HasFile(dir2));
+ EXPECT_TRUE(c4.HasFile(file1));
+ EXPECT_TRUE(c4.HasFile(file2_abs));
+ EXPECT_EQ(4, c4.size());
+
+ // Enumerate with a pattern.
+ FileEnumerator f5(temp_dir_.path(), true, FILES_AND_DIRECTORIES, FPL("dir*"));
+ FindResultCollector c5(f5);
+ EXPECT_TRUE(c5.HasFile(dir1));
+ EXPECT_TRUE(c5.HasFile(dir2));
+ EXPECT_TRUE(c5.HasFile(dir2file));
+ EXPECT_TRUE(c5.HasFile(dir2inner));
+ EXPECT_TRUE(c5.HasFile(dir2innerfile));
+ EXPECT_EQ(5, c5.size());
+
+#if defined(OS_WIN)
+ {
+ // Make dir1 point to dir2.
+ ReparsePoint reparse_point(dir1, dir2);
+ EXPECT_TRUE(reparse_point.IsValid());
+
+ if ((win::GetVersion() >= win::VERSION_VISTA)) {
+ // There can be a delay for the enumeration code to see the change on
+ // the file system so skip this test for XP.
+ // Enumerate the reparse point.
+ FileEnumerator f6(dir1, true, FILES_AND_DIRECTORIES);
+ FindResultCollector c6(f6);
+ FilePath inner2 = dir1.Append(FPL("inner"));
+ EXPECT_TRUE(c6.HasFile(inner2));
+ EXPECT_TRUE(c6.HasFile(inner2.Append(FPL("innerfile.txt"))));
+ EXPECT_TRUE(c6.HasFile(dir1.Append(FPL("dir2file.txt"))));
+ EXPECT_EQ(3, c6.size());
+ }
+
+ // No changes for non recursive operation.
+ FileEnumerator f7(temp_dir_.path(), false, FILES_AND_DIRECTORIES);
+ FindResultCollector c7(f7);
+ EXPECT_TRUE(c7.HasFile(dir2));
+ EXPECT_TRUE(c7.HasFile(dir2));
+ EXPECT_TRUE(c7.HasFile(file1));
+ EXPECT_TRUE(c7.HasFile(file2_abs));
+ EXPECT_EQ(4, c7.size());
+
+ // Should not enumerate inside dir1 when using recursion.
+ FileEnumerator f8(temp_dir_.path(), true, FILES_AND_DIRECTORIES);
+ FindResultCollector c8(f8);
+ EXPECT_TRUE(c8.HasFile(dir1));
+ EXPECT_TRUE(c8.HasFile(dir2));
+ EXPECT_TRUE(c8.HasFile(file1));
+ EXPECT_TRUE(c8.HasFile(file2_abs));
+ EXPECT_TRUE(c8.HasFile(dir2file));
+ EXPECT_TRUE(c8.HasFile(dir2inner));
+ EXPECT_TRUE(c8.HasFile(dir2innerfile));
+ EXPECT_EQ(7, c8.size());
+ }
+#endif
+
+ // Make sure the destructor closes the find handle while in the middle of a
+ // query to allow TearDown to delete the directory.
+ FileEnumerator f9(temp_dir_.path(), true, FILES_AND_DIRECTORIES);
+ EXPECT_FALSE(f9.Next().value().empty()); // Should have found something
+ // (we don't care what).
+}
+
+TEST_F(FileUtilTest, AppendToFile) {
+ FilePath data_dir =
+ temp_dir_.path().Append(FILE_PATH_LITERAL("FilePathTest"));
+
+ // Create a fresh, empty copy of this directory.
+ if (PathExists(data_dir)) {
+ ASSERT_TRUE(DeleteFile(data_dir, true));
+ }
+ ASSERT_TRUE(CreateDirectory(data_dir));
+
+ // Create a fresh, empty copy of this directory.
+ if (PathExists(data_dir)) {
+ ASSERT_TRUE(DeleteFile(data_dir, true));
+ }
+ ASSERT_TRUE(CreateDirectory(data_dir));
+ FilePath foobar(data_dir.Append(FILE_PATH_LITERAL("foobar.txt")));
+
+ std::string data("hello");
+ EXPECT_EQ(-1, AppendToFile(foobar, data.c_str(), data.length()));
+ EXPECT_EQ(static_cast<int>(data.length()),
+ WriteFile(foobar, data.c_str(), data.length()));
+ EXPECT_EQ(static_cast<int>(data.length()),
+ AppendToFile(foobar, data.c_str(), data.length()));
+
+ const std::wstring read_content = ReadTextFile(foobar);
+ EXPECT_EQ(L"hellohello", read_content);
+}
+
+TEST_F(FileUtilTest, ReadFile) {
+ // Create a test file to be read.
+ const std::string kTestData("The quick brown fox jumps over the lazy dog.");
+ FilePath file_path =
+ temp_dir_.path().Append(FILE_PATH_LITERAL("ReadFileTest"));
+
+ ASSERT_EQ(static_cast<int>(kTestData.size()),
+ WriteFile(file_path, kTestData.data(), kTestData.size()));
+
+ // Make buffers with various size.
+ std::vector<char> small_buffer(kTestData.size() / 2);
+ std::vector<char> exact_buffer(kTestData.size());
+ std::vector<char> large_buffer(kTestData.size() * 2);
+
+ // Read the file with smaller buffer.
+ int bytes_read_small = ReadFile(
+ file_path, &small_buffer[0], static_cast<int>(small_buffer.size()));
+ EXPECT_EQ(static_cast<int>(small_buffer.size()), bytes_read_small);
+ EXPECT_EQ(
+ std::string(kTestData.begin(), kTestData.begin() + small_buffer.size()),
+ std::string(small_buffer.begin(), small_buffer.end()));
+
+ // Read the file with buffer which have exactly same size.
+ int bytes_read_exact = ReadFile(
+ file_path, &exact_buffer[0], static_cast<int>(exact_buffer.size()));
+ EXPECT_EQ(static_cast<int>(kTestData.size()), bytes_read_exact);
+ EXPECT_EQ(kTestData, std::string(exact_buffer.begin(), exact_buffer.end()));
+
+ // Read the file with larger buffer.
+ int bytes_read_large = ReadFile(
+ file_path, &large_buffer[0], static_cast<int>(large_buffer.size()));
+ EXPECT_EQ(static_cast<int>(kTestData.size()), bytes_read_large);
+ EXPECT_EQ(kTestData, std::string(large_buffer.begin(),
+ large_buffer.begin() + kTestData.size()));
+
+ // Make sure the return value is -1 if the file doesn't exist.
+ FilePath file_path_not_exist =
+ temp_dir_.path().Append(FILE_PATH_LITERAL("ReadFileNotExistTest"));
+ EXPECT_EQ(-1,
+ ReadFile(file_path_not_exist,
+ &exact_buffer[0],
+ static_cast<int>(exact_buffer.size())));
+}
+
+TEST_F(FileUtilTest, ReadFileToString) {
+ const char kTestData[] = "0123";
+ std::string data;
+
+ FilePath file_path =
+ temp_dir_.path().Append(FILE_PATH_LITERAL("ReadFileToStringTest"));
+ FilePath file_path_dangerous =
+ temp_dir_.path().Append(FILE_PATH_LITERAL("..")).
+ Append(temp_dir_.path().BaseName()).
+ Append(FILE_PATH_LITERAL("ReadFileToStringTest"));
+
+ // Create test file.
+ ASSERT_EQ(4, WriteFile(file_path, kTestData, 4));
+
+ EXPECT_TRUE(ReadFileToString(file_path, &data));
+ EXPECT_EQ(kTestData, data);
+
+ data = "temp";
+ EXPECT_FALSE(ReadFileToString(file_path, &data, 0));
+ EXPECT_EQ(0u, data.length());
+
+ data = "temp";
+ EXPECT_FALSE(ReadFileToString(file_path, &data, 2));
+ EXPECT_EQ("01", data);
+
+ data.clear();
+ EXPECT_FALSE(ReadFileToString(file_path, &data, 3));
+ EXPECT_EQ("012", data);
+
+ data.clear();
+ EXPECT_TRUE(ReadFileToString(file_path, &data, 4));
+ EXPECT_EQ("0123", data);
+
+ data.clear();
+ EXPECT_TRUE(ReadFileToString(file_path, &data, 6));
+ EXPECT_EQ("0123", data);
+
+ EXPECT_TRUE(ReadFileToString(file_path, NULL, 6));
+
+ EXPECT_TRUE(ReadFileToString(file_path, NULL));
+
+ data = "temp";
+ EXPECT_FALSE(ReadFileToString(file_path_dangerous, &data));
+ EXPECT_EQ(0u, data.length());
+
+ // Delete test file.
+ EXPECT_TRUE(base::DeleteFile(file_path, false));
+
+ data = "temp";
+ EXPECT_FALSE(ReadFileToString(file_path, &data));
+ EXPECT_EQ(0u, data.length());
+
+ data = "temp";
+ EXPECT_FALSE(ReadFileToString(file_path, &data, 6));
+ EXPECT_EQ(0u, data.length());
+}
+
+TEST_F(FileUtilTest, TouchFile) {
+ FilePath data_dir =
+ temp_dir_.path().Append(FILE_PATH_LITERAL("FilePathTest"));
+
+ // Create a fresh, empty copy of this directory.
+ if (PathExists(data_dir)) {
+ ASSERT_TRUE(DeleteFile(data_dir, true));
+ }
+ ASSERT_TRUE(CreateDirectory(data_dir));
+
+ FilePath foobar(data_dir.Append(FILE_PATH_LITERAL("foobar.txt")));
+ std::string data("hello");
+ ASSERT_TRUE(WriteFile(foobar, data.c_str(), data.length()));
+
+ Time access_time;
+ // This timestamp is divisible by one day (in local timezone),
+ // to make it work on FAT too.
+ ASSERT_TRUE(Time::FromString("Wed, 16 Nov 1994, 00:00:00",
+ &access_time));
+
+ Time modification_time;
+ // Note that this timestamp is divisible by two (seconds) - FAT stores
+ // modification times with 2s resolution.
+ ASSERT_TRUE(Time::FromString("Tue, 15 Nov 1994, 12:45:26 GMT",
+ &modification_time));
+
+ ASSERT_TRUE(TouchFile(foobar, access_time, modification_time));
+ File::Info file_info;
+ ASSERT_TRUE(GetFileInfo(foobar, &file_info));
+ EXPECT_EQ(access_time.ToInternalValue(),
+ file_info.last_accessed.ToInternalValue());
+ EXPECT_EQ(modification_time.ToInternalValue(),
+ file_info.last_modified.ToInternalValue());
+}
+
+TEST_F(FileUtilTest, IsDirectoryEmpty) {
+ FilePath empty_dir = temp_dir_.path().Append(FILE_PATH_LITERAL("EmptyDir"));
+
+ ASSERT_FALSE(PathExists(empty_dir));
+
+ ASSERT_TRUE(CreateDirectory(empty_dir));
+
+ EXPECT_TRUE(IsDirectoryEmpty(empty_dir));
+
+ FilePath foo(empty_dir.Append(FILE_PATH_LITERAL("foo.txt")));
+ std::string bar("baz");
+ ASSERT_TRUE(WriteFile(foo, bar.c_str(), bar.length()));
+
+ EXPECT_FALSE(IsDirectoryEmpty(empty_dir));
+}
+
+#if defined(OS_POSIX)
+
+// Testing VerifyPathControlledByAdmin() is hard, because there is no
+// way a test can make a file owned by root, or change file paths
+// at the root of the file system. VerifyPathControlledByAdmin()
+// is implemented as a call to VerifyPathControlledByUser, which gives
+// us the ability to test with paths under the test's temp directory,
+// using a user id we control.
+// Pull tests of VerifyPathControlledByUserTest() into a separate test class
+// with a common SetUp() method.
+class VerifyPathControlledByUserTest : public FileUtilTest {
+ protected:
+ virtual void SetUp() OVERRIDE {
+ FileUtilTest::SetUp();
+
+ // Create a basic structure used by each test.
+ // base_dir_
+ // |-> sub_dir_
+ // |-> text_file_
+
+ base_dir_ = temp_dir_.path().AppendASCII("base_dir");
+ ASSERT_TRUE(CreateDirectory(base_dir_));
+
+ sub_dir_ = base_dir_.AppendASCII("sub_dir");
+ ASSERT_TRUE(CreateDirectory(sub_dir_));
+
+ text_file_ = sub_dir_.AppendASCII("file.txt");
+ CreateTextFile(text_file_, L"This text file has some text in it.");
+
+ // Get the user and group files are created with from |base_dir_|.
+ struct stat stat_buf;
+ ASSERT_EQ(0, stat(base_dir_.value().c_str(), &stat_buf));
+ uid_ = stat_buf.st_uid;
+ ok_gids_.insert(stat_buf.st_gid);
+ bad_gids_.insert(stat_buf.st_gid + 1);
+
+ ASSERT_EQ(uid_, getuid()); // This process should be the owner.
+
+ // To ensure that umask settings do not cause the initial state
+ // of permissions to be different from what we expect, explicitly
+ // set permissions on the directories we create.
+ // Make all files and directories non-world-writable.
+
+ // Users and group can read, write, traverse
+ int enabled_permissions =
+ FILE_PERMISSION_USER_MASK | FILE_PERMISSION_GROUP_MASK;
+ // Other users can't read, write, traverse
+ int disabled_permissions = FILE_PERMISSION_OTHERS_MASK;
+
+ ASSERT_NO_FATAL_FAILURE(
+ ChangePosixFilePermissions(
+ base_dir_, enabled_permissions, disabled_permissions));
+ ASSERT_NO_FATAL_FAILURE(
+ ChangePosixFilePermissions(
+ sub_dir_, enabled_permissions, disabled_permissions));
+ }
+
+ FilePath base_dir_;
+ FilePath sub_dir_;
+ FilePath text_file_;
+ uid_t uid_;
+
+ std::set<gid_t> ok_gids_;
+ std::set<gid_t> bad_gids_;
+};
+
+TEST_F(VerifyPathControlledByUserTest, BadPaths) {
+ // File does not exist.
+ FilePath does_not_exist = base_dir_.AppendASCII("does")
+ .AppendASCII("not")
+ .AppendASCII("exist");
+ EXPECT_FALSE(
+ base::VerifyPathControlledByUser(
+ base_dir_, does_not_exist, uid_, ok_gids_));
+
+ // |base| not a subpath of |path|.
+ EXPECT_FALSE(
+ base::VerifyPathControlledByUser(
+ sub_dir_, base_dir_, uid_, ok_gids_));
+
+ // An empty base path will fail to be a prefix for any path.
+ FilePath empty;
+ EXPECT_FALSE(
+ base::VerifyPathControlledByUser(
+ empty, base_dir_, uid_, ok_gids_));
+
+ // Finding that a bad call fails proves nothing unless a good call succeeds.
+ EXPECT_TRUE(
+ base::VerifyPathControlledByUser(
+ base_dir_, sub_dir_, uid_, ok_gids_));
+}
+
+TEST_F(VerifyPathControlledByUserTest, Symlinks) {
+ // Symlinks in the path should cause failure.
+
+ // Symlink to the file at the end of the path.
+ FilePath file_link = base_dir_.AppendASCII("file_link");
+ ASSERT_TRUE(CreateSymbolicLink(text_file_, file_link))
+ << "Failed to create symlink.";
+
+ EXPECT_FALSE(
+ base::VerifyPathControlledByUser(
+ base_dir_, file_link, uid_, ok_gids_));
+ EXPECT_FALSE(
+ base::VerifyPathControlledByUser(
+ file_link, file_link, uid_, ok_gids_));
+
+ // Symlink from one directory to another within the path.
+ FilePath link_to_sub_dir = base_dir_.AppendASCII("link_to_sub_dir");
+ ASSERT_TRUE(CreateSymbolicLink(sub_dir_, link_to_sub_dir))
+ << "Failed to create symlink.";
+
+ FilePath file_path_with_link = link_to_sub_dir.AppendASCII("file.txt");
+ ASSERT_TRUE(PathExists(file_path_with_link));
+
+ EXPECT_FALSE(
+ base::VerifyPathControlledByUser(
+ base_dir_, file_path_with_link, uid_, ok_gids_));
+
+ EXPECT_FALSE(
+ base::VerifyPathControlledByUser(
+ link_to_sub_dir, file_path_with_link, uid_, ok_gids_));
+
+ // Symlinks in parents of base path are allowed.
+ EXPECT_TRUE(
+ base::VerifyPathControlledByUser(
+ file_path_with_link, file_path_with_link, uid_, ok_gids_));
+}
+
+TEST_F(VerifyPathControlledByUserTest, OwnershipChecks) {
+ // Get a uid that is not the uid of files we create.
+ uid_t bad_uid = uid_ + 1;
+
+ // Make all files and directories non-world-writable.
+ ASSERT_NO_FATAL_FAILURE(
+ ChangePosixFilePermissions(base_dir_, 0u, S_IWOTH));
+ ASSERT_NO_FATAL_FAILURE(
+ ChangePosixFilePermissions(sub_dir_, 0u, S_IWOTH));
+ ASSERT_NO_FATAL_FAILURE(
+ ChangePosixFilePermissions(text_file_, 0u, S_IWOTH));
+
+ // We control these paths.
+ EXPECT_TRUE(
+ base::VerifyPathControlledByUser(
+ base_dir_, sub_dir_, uid_, ok_gids_));
+ EXPECT_TRUE(
+ base::VerifyPathControlledByUser(
+ base_dir_, text_file_, uid_, ok_gids_));
+ EXPECT_TRUE(
+ base::VerifyPathControlledByUser(
+ sub_dir_, text_file_, uid_, ok_gids_));
+
+ // Another user does not control these paths.
+ EXPECT_FALSE(
+ base::VerifyPathControlledByUser(
+ base_dir_, sub_dir_, bad_uid, ok_gids_));
+ EXPECT_FALSE(
+ base::VerifyPathControlledByUser(
+ base_dir_, text_file_, bad_uid, ok_gids_));
+ EXPECT_FALSE(
+ base::VerifyPathControlledByUser(
+ sub_dir_, text_file_, bad_uid, ok_gids_));
+
+ // Another group does not control the paths.
+ EXPECT_FALSE(
+ base::VerifyPathControlledByUser(
+ base_dir_, sub_dir_, uid_, bad_gids_));
+ EXPECT_FALSE(
+ base::VerifyPathControlledByUser(
+ base_dir_, text_file_, uid_, bad_gids_));
+ EXPECT_FALSE(
+ base::VerifyPathControlledByUser(
+ sub_dir_, text_file_, uid_, bad_gids_));
+}
+
+TEST_F(VerifyPathControlledByUserTest, GroupWriteTest) {
+ // Make all files and directories writable only by their owner.
+ ASSERT_NO_FATAL_FAILURE(
+ ChangePosixFilePermissions(base_dir_, 0u, S_IWOTH|S_IWGRP));
+ ASSERT_NO_FATAL_FAILURE(
+ ChangePosixFilePermissions(sub_dir_, 0u, S_IWOTH|S_IWGRP));
+ ASSERT_NO_FATAL_FAILURE(
+ ChangePosixFilePermissions(text_file_, 0u, S_IWOTH|S_IWGRP));
+
+ // Any group is okay because the path is not group-writable.
+ EXPECT_TRUE(
+ base::VerifyPathControlledByUser(
+ base_dir_, sub_dir_, uid_, ok_gids_));
+ EXPECT_TRUE(
+ base::VerifyPathControlledByUser(
+ base_dir_, text_file_, uid_, ok_gids_));
+ EXPECT_TRUE(
+ base::VerifyPathControlledByUser(
+ sub_dir_, text_file_, uid_, ok_gids_));
+
+ EXPECT_TRUE(
+ base::VerifyPathControlledByUser(
+ base_dir_, sub_dir_, uid_, bad_gids_));
+ EXPECT_TRUE(
+ base::VerifyPathControlledByUser(
+ base_dir_, text_file_, uid_, bad_gids_));
+ EXPECT_TRUE(
+ base::VerifyPathControlledByUser(
+ sub_dir_, text_file_, uid_, bad_gids_));
+
+ // No group is okay, because we don't check the group
+ // if no group can write.
+ std::set<gid_t> no_gids; // Empty set of gids.
+ EXPECT_TRUE(
+ base::VerifyPathControlledByUser(
+ base_dir_, sub_dir_, uid_, no_gids));
+ EXPECT_TRUE(
+ base::VerifyPathControlledByUser(
+ base_dir_, text_file_, uid_, no_gids));
+ EXPECT_TRUE(
+ base::VerifyPathControlledByUser(
+ sub_dir_, text_file_, uid_, no_gids));
+
+
+ // Make all files and directories writable by their group.
+ ASSERT_NO_FATAL_FAILURE(
+ ChangePosixFilePermissions(base_dir_, S_IWGRP, 0u));
+ ASSERT_NO_FATAL_FAILURE(
+ ChangePosixFilePermissions(sub_dir_, S_IWGRP, 0u));
+ ASSERT_NO_FATAL_FAILURE(
+ ChangePosixFilePermissions(text_file_, S_IWGRP, 0u));
+
+ // Now |ok_gids_| works, but |bad_gids_| fails.
+ EXPECT_TRUE(
+ base::VerifyPathControlledByUser(
+ base_dir_, sub_dir_, uid_, ok_gids_));
+ EXPECT_TRUE(
+ base::VerifyPathControlledByUser(
+ base_dir_, text_file_, uid_, ok_gids_));
+ EXPECT_TRUE(
+ base::VerifyPathControlledByUser(
+ sub_dir_, text_file_, uid_, ok_gids_));
+
+ EXPECT_FALSE(
+ base::VerifyPathControlledByUser(
+ base_dir_, sub_dir_, uid_, bad_gids_));
+ EXPECT_FALSE(
+ base::VerifyPathControlledByUser(
+ base_dir_, text_file_, uid_, bad_gids_));
+ EXPECT_FALSE(
+ base::VerifyPathControlledByUser(
+ sub_dir_, text_file_, uid_, bad_gids_));
+
+ // Because any group in the group set is allowed,
+ // the union of good and bad gids passes.
+
+ std::set<gid_t> multiple_gids;
+ std::set_union(
+ ok_gids_.begin(), ok_gids_.end(),
+ bad_gids_.begin(), bad_gids_.end(),
+ std::inserter(multiple_gids, multiple_gids.begin()));
+
+ EXPECT_TRUE(
+ base::VerifyPathControlledByUser(
+ base_dir_, sub_dir_, uid_, multiple_gids));
+ EXPECT_TRUE(
+ base::VerifyPathControlledByUser(
+ base_dir_, text_file_, uid_, multiple_gids));
+ EXPECT_TRUE(
+ base::VerifyPathControlledByUser(
+ sub_dir_, text_file_, uid_, multiple_gids));
+}
+
+TEST_F(VerifyPathControlledByUserTest, WriteBitChecks) {
+ // Make all files and directories non-world-writable.
+ ASSERT_NO_FATAL_FAILURE(
+ ChangePosixFilePermissions(base_dir_, 0u, S_IWOTH));
+ ASSERT_NO_FATAL_FAILURE(
+ ChangePosixFilePermissions(sub_dir_, 0u, S_IWOTH));
+ ASSERT_NO_FATAL_FAILURE(
+ ChangePosixFilePermissions(text_file_, 0u, S_IWOTH));
+
+ // Initialy, we control all parts of the path.
+ EXPECT_TRUE(
+ base::VerifyPathControlledByUser(
+ base_dir_, sub_dir_, uid_, ok_gids_));
+ EXPECT_TRUE(
+ base::VerifyPathControlledByUser(
+ base_dir_, text_file_, uid_, ok_gids_));
+ EXPECT_TRUE(
+ base::VerifyPathControlledByUser(
+ sub_dir_, text_file_, uid_, ok_gids_));
+
+ // Make base_dir_ world-writable.
+ ASSERT_NO_FATAL_FAILURE(
+ ChangePosixFilePermissions(base_dir_, S_IWOTH, 0u));
+ EXPECT_FALSE(
+ base::VerifyPathControlledByUser(
+ base_dir_, sub_dir_, uid_, ok_gids_));
+ EXPECT_FALSE(
+ base::VerifyPathControlledByUser(
+ base_dir_, text_file_, uid_, ok_gids_));
+ EXPECT_TRUE(
+ base::VerifyPathControlledByUser(
+ sub_dir_, text_file_, uid_, ok_gids_));
+
+ // Make sub_dir_ world writable.
+ ASSERT_NO_FATAL_FAILURE(
+ ChangePosixFilePermissions(sub_dir_, S_IWOTH, 0u));
+ EXPECT_FALSE(
+ base::VerifyPathControlledByUser(
+ base_dir_, sub_dir_, uid_, ok_gids_));
+ EXPECT_FALSE(
+ base::VerifyPathControlledByUser(
+ base_dir_, text_file_, uid_, ok_gids_));
+ EXPECT_FALSE(
+ base::VerifyPathControlledByUser(
+ sub_dir_, text_file_, uid_, ok_gids_));
+
+ // Make text_file_ world writable.
+ ASSERT_NO_FATAL_FAILURE(
+ ChangePosixFilePermissions(text_file_, S_IWOTH, 0u));
+ EXPECT_FALSE(
+ base::VerifyPathControlledByUser(
+ base_dir_, sub_dir_, uid_, ok_gids_));
+ EXPECT_FALSE(
+ base::VerifyPathControlledByUser(
+ base_dir_, text_file_, uid_, ok_gids_));
+ EXPECT_FALSE(
+ base::VerifyPathControlledByUser(
+ sub_dir_, text_file_, uid_, ok_gids_));
+
+ // Make sub_dir_ non-world writable.
+ ASSERT_NO_FATAL_FAILURE(
+ ChangePosixFilePermissions(sub_dir_, 0u, S_IWOTH));
+ EXPECT_FALSE(
+ base::VerifyPathControlledByUser(
+ base_dir_, sub_dir_, uid_, ok_gids_));
+ EXPECT_FALSE(
+ base::VerifyPathControlledByUser(
+ base_dir_, text_file_, uid_, ok_gids_));
+ EXPECT_FALSE(
+ base::VerifyPathControlledByUser(
+ sub_dir_, text_file_, uid_, ok_gids_));
+
+ // Make base_dir_ non-world-writable.
+ ASSERT_NO_FATAL_FAILURE(
+ ChangePosixFilePermissions(base_dir_, 0u, S_IWOTH));
+ EXPECT_TRUE(
+ base::VerifyPathControlledByUser(
+ base_dir_, sub_dir_, uid_, ok_gids_));
+ EXPECT_FALSE(
+ base::VerifyPathControlledByUser(
+ base_dir_, text_file_, uid_, ok_gids_));
+ EXPECT_FALSE(
+ base::VerifyPathControlledByUser(
+ sub_dir_, text_file_, uid_, ok_gids_));
+
+ // Back to the initial state: Nothing is writable, so every path
+ // should pass.
+ ASSERT_NO_FATAL_FAILURE(
+ ChangePosixFilePermissions(text_file_, 0u, S_IWOTH));
+ EXPECT_TRUE(
+ base::VerifyPathControlledByUser(
+ base_dir_, sub_dir_, uid_, ok_gids_));
+ EXPECT_TRUE(
+ base::VerifyPathControlledByUser(
+ base_dir_, text_file_, uid_, ok_gids_));
+ EXPECT_TRUE(
+ base::VerifyPathControlledByUser(
+ sub_dir_, text_file_, uid_, ok_gids_));
+}
+
+#if defined(OS_ANDROID)
+TEST_F(FileUtilTest, ValidContentUriTest) {
+ // Get the test image path.
+ FilePath data_dir;
+ ASSERT_TRUE(PathService::Get(DIR_TEST_DATA, &data_dir));
+ data_dir = data_dir.AppendASCII("file_util");
+ ASSERT_TRUE(PathExists(data_dir));
+ FilePath image_file = data_dir.Append(FILE_PATH_LITERAL("red.png"));
+ int64 image_size;
+ GetFileSize(image_file, &image_size);
+ EXPECT_LT(0, image_size);
+
+ // Insert the image into MediaStore. MediaStore will do some conversions, and
+ // return the content URI.
+ FilePath path = base::InsertImageIntoMediaStore(image_file);
+ EXPECT_TRUE(path.IsContentUri());
+ EXPECT_TRUE(PathExists(path));
+ // The file size may not equal to the input image as MediaStore may convert
+ // the image.
+ int64 content_uri_size;
+ GetFileSize(path, &content_uri_size);
+ EXPECT_EQ(image_size, content_uri_size);
+
+ // We should be able to read the file.
+ char* buffer = new char[image_size];
+ File file = OpenContentUriForRead(path);
+ EXPECT_TRUE(file.IsValid());
+ EXPECT_TRUE(file.ReadAtCurrentPos(buffer, image_size));
+ delete[] buffer;
+}
+
+TEST_F(FileUtilTest, NonExistentContentUriTest) {
+ FilePath path("content://foo.bar");
+ EXPECT_TRUE(path.IsContentUri());
+ EXPECT_FALSE(PathExists(path));
+ // Size should be smaller than 0.
+ int64 size;
+ EXPECT_FALSE(GetFileSize(path, &size));
+
+ // We should not be able to read the file.
+ File file = OpenContentUriForRead(path);
+ EXPECT_FALSE(file.IsValid());
+}
+#endif
+
+TEST(ScopedFD, ScopedFDDoesClose) {
+ int fds[2];
+ char c = 0;
+ ASSERT_EQ(0, pipe(fds));
+ const int write_end = fds[1];
+ base::ScopedFD read_end_closer(fds[0]);
+ {
+ base::ScopedFD write_end_closer(fds[1]);
+ }
+ // This is the only thread. This file descriptor should no longer be valid.
+ int ret = close(write_end);
+ EXPECT_EQ(-1, ret);
+ EXPECT_EQ(EBADF, errno);
+ // Make sure read(2) won't block.
+ ASSERT_EQ(0, fcntl(fds[0], F_SETFL, O_NONBLOCK));
+ // Reading the pipe should EOF.
+ EXPECT_EQ(0, read(fds[0], &c, 1));
+}
+
+#if defined(GTEST_HAS_DEATH_TEST)
+void CloseWithScopedFD(int fd) {
+ base::ScopedFD fd_closer(fd);
+}
+#endif
+
+TEST(ScopedFD, ScopedFDCrashesOnCloseFailure) {
+ int fds[2];
+ ASSERT_EQ(0, pipe(fds));
+ base::ScopedFD read_end_closer(fds[0]);
+ EXPECT_EQ(0, IGNORE_EINTR(close(fds[1])));
+#if defined(GTEST_HAS_DEATH_TEST)
+ // This is the only thread. This file descriptor should no longer be valid.
+ // Trying to close it should crash. This is important for security.
+ EXPECT_DEATH(CloseWithScopedFD(fds[1]), "");
+#endif
+}
+
+#endif // defined(OS_POSIX)
+
+} // namespace
+
+} // namespace base
diff --git a/base/files/file_util_win.cc b/base/files/file_util_win.cc
new file mode 100644
index 0000000..82b53c5
--- /dev/null
+++ b/base/files/file_util_win.cc
@@ -0,0 +1,810 @@
+// Copyright (c) 2012 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "base/files/file_util.h"
+
+#include <windows.h>
+#include <io.h>
+#include <psapi.h>
+#include <shellapi.h>
+#include <shlobj.h>
+#include <time.h>
+
+#include <algorithm>
+#include <limits>
+#include <string>
+
+#include "base/files/file_enumerator.h"
+#include "base/files/file_path.h"
+#include "base/logging.h"
+#include "base/metrics/histogram.h"
+#include "base/process/process_handle.h"
+#include "base/rand_util.h"
+#include "base/strings/string_number_conversions.h"
+#include "base/strings/string_util.h"
+#include "base/strings/utf_string_conversions.h"
+#include "base/threading/thread_restrictions.h"
+#include "base/time/time.h"
+#include "base/win/scoped_handle.h"
+#include "base/win/windows_version.h"
+
+namespace base {
+
+namespace {
+
+const DWORD kFileShareAll =
+ FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
+
+} // namespace
+
+FilePath MakeAbsoluteFilePath(const FilePath& input) {
+ ThreadRestrictions::AssertIOAllowed();
+ wchar_t file_path[MAX_PATH];
+ if (!_wfullpath(file_path, input.value().c_str(), MAX_PATH))
+ return FilePath();
+ return FilePath(file_path);
+}
+
+bool DeleteFile(const FilePath& path, bool recursive) {
+ ThreadRestrictions::AssertIOAllowed();
+
+ if (path.value().length() >= MAX_PATH)
+ return false;
+
+ // On XP SHFileOperation will return ERROR_ACCESS_DENIED instead of
+ // ERROR_FILE_NOT_FOUND, so just shortcut this here.
+ if (path.empty())
+ return true;
+
+ if (!recursive) {
+ // If not recursing, then first check to see if |path| is a directory.
+ // If it is, then remove it with RemoveDirectory.
+ File::Info file_info;
+ if (GetFileInfo(path, &file_info) && file_info.is_directory)
+ return RemoveDirectory(path.value().c_str()) != 0;
+
+ // Otherwise, it's a file, wildcard or non-existant. Try DeleteFile first
+ // because it should be faster. If DeleteFile fails, then we fall through
+ // to SHFileOperation, which will do the right thing.
+ if (::DeleteFile(path.value().c_str()) != 0)
+ return true;
+ }
+
+ // SHFILEOPSTRUCT wants the path to be terminated with two NULLs,
+ // so we have to use wcscpy because wcscpy_s writes non-NULLs
+ // into the rest of the buffer.
+ wchar_t double_terminated_path[MAX_PATH + 1] = {0};
+#pragma warning(suppress:4996) // don't complain about wcscpy deprecation
+ wcscpy(double_terminated_path, path.value().c_str());
+
+ SHFILEOPSTRUCT file_operation = {0};
+ file_operation.wFunc = FO_DELETE;
+ file_operation.pFrom = double_terminated_path;
+ file_operation.fFlags = FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMATION;
+ if (!recursive)
+ file_operation.fFlags |= FOF_NORECURSION | FOF_FILESONLY;
+ int err = SHFileOperation(&file_operation);
+
+ // Since we're passing flags to the operation telling it to be silent,
+ // it's possible for the operation to be aborted/cancelled without err
+ // being set (although MSDN doesn't give any scenarios for how this can
+ // happen). See MSDN for SHFileOperation and SHFILEOPTSTRUCT.
+ if (file_operation.fAnyOperationsAborted)
+ return false;
+
+ // Some versions of Windows return ERROR_FILE_NOT_FOUND (0x2) when deleting
+ // an empty directory and some return 0x402 when they should be returning
+ // ERROR_FILE_NOT_FOUND. MSDN says Vista and up won't return 0x402. Windows 7
+ // can return DE_INVALIDFILES (0x7C) for nonexistent directories.
+ return (err == 0 || err == ERROR_FILE_NOT_FOUND || err == 0x402 ||
+ err == 0x7C);
+}
+
+bool DeleteFileAfterReboot(const FilePath& path) {
+ ThreadRestrictions::AssertIOAllowed();
+
+ if (path.value().length() >= MAX_PATH)
+ return false;
+
+ return MoveFileEx(path.value().c_str(), NULL,
+ MOVEFILE_DELAY_UNTIL_REBOOT |
+ MOVEFILE_REPLACE_EXISTING) != FALSE;
+}
+
+bool ReplaceFile(const FilePath& from_path,
+ const FilePath& to_path,
+ File::Error* error) {
+ ThreadRestrictions::AssertIOAllowed();
+ // Try a simple move first. It will only succeed when |to_path| doesn't
+ // already exist.
+ if (::MoveFile(from_path.value().c_str(), to_path.value().c_str()))
+ return true;
+ // Try the full-blown replace if the move fails, as ReplaceFile will only
+ // succeed when |to_path| does exist. When writing to a network share, we may
+ // not be able to change the ACLs. Ignore ACL errors then
+ // (REPLACEFILE_IGNORE_MERGE_ERRORS).
+ if (::ReplaceFile(to_path.value().c_str(), from_path.value().c_str(), NULL,
+ REPLACEFILE_IGNORE_MERGE_ERRORS, NULL, NULL)) {
+ return true;
+ }
+ if (error)
+ *error = File::OSErrorToFileError(GetLastError());
+ return false;
+}
+
+bool CopyDirectory(const FilePath& from_path, const FilePath& to_path,
+ bool recursive) {
+ // NOTE(maruel): Previous version of this function used to call
+ // SHFileOperation(). This used to copy the file attributes and extended
+ // attributes, OLE structured storage, NTFS file system alternate data
+ // streams, SECURITY_DESCRIPTOR. In practice, this is not what we want, we
+ // want the containing directory to propagate its SECURITY_DESCRIPTOR.
+ ThreadRestrictions::AssertIOAllowed();
+
+ // NOTE: I suspect we could support longer paths, but that would involve
+ // analyzing all our usage of files.
+ if (from_path.value().length() >= MAX_PATH ||
+ to_path.value().length() >= MAX_PATH) {
+ return false;
+ }
+
+ // This function does not properly handle destinations within the source.
+ FilePath real_to_path = to_path;
+ if (PathExists(real_to_path)) {
+ real_to_path = MakeAbsoluteFilePath(real_to_path);
+ if (real_to_path.empty())
+ return false;
+ } else {
+ real_to_path = MakeAbsoluteFilePath(real_to_path.DirName());
+ if (real_to_path.empty())
+ return false;
+ }
+ FilePath real_from_path = MakeAbsoluteFilePath(from_path);
+ if (real_from_path.empty())
+ return false;
+ if (real_to_path.value().size() >= real_from_path.value().size() &&
+ real_to_path.value().compare(0, real_from_path.value().size(),
+ real_from_path.value()) == 0) {
+ return false;
+ }
+
+ int traverse_type = FileEnumerator::FILES;
+ if (recursive)
+ traverse_type |= FileEnumerator::DIRECTORIES;
+ FileEnumerator traversal(from_path, recursive, traverse_type);
+
+ if (!PathExists(from_path)) {
+ DLOG(ERROR) << "CopyDirectory() couldn't stat source directory: "
+ << from_path.value().c_str();
+ return false;
+ }
+ // TODO(maruel): This is not necessary anymore.
+ DCHECK(recursive || DirectoryExists(from_path));
+
+ FilePath current = from_path;
+ bool from_is_dir = DirectoryExists(from_path);
+ bool success = true;
+ FilePath from_path_base = from_path;
+ if (recursive && DirectoryExists(to_path)) {
+ // If the destination already exists and is a directory, then the
+ // top level of source needs to be copied.
+ from_path_base = from_path.DirName();
+ }
+
+ while (success && !current.empty()) {
+ // current is the source path, including from_path, so append
+ // the suffix after from_path to to_path to create the target_path.
+ FilePath target_path(to_path);
+ if (from_path_base != current) {
+ if (!from_path_base.AppendRelativePath(current, &target_path)) {
+ success = false;
+ break;
+ }
+ }
+
+ if (from_is_dir) {
+ if (!DirectoryExists(target_path) &&
+ !::CreateDirectory(target_path.value().c_str(), NULL)) {
+ DLOG(ERROR) << "CopyDirectory() couldn't create directory: "
+ << target_path.value().c_str();
+ success = false;
+ }
+ } else if (!internal::CopyFileUnsafe(current, target_path)) {
+ DLOG(ERROR) << "CopyDirectory() couldn't create file: "
+ << target_path.value().c_str();
+ success = false;
+ }
+
+ current = traversal.Next();
+ if (!current.empty())
+ from_is_dir = traversal.GetInfo().IsDirectory();
+ }
+
+ return success;
+}
+
+bool PathExists(const FilePath& path) {
+ ThreadRestrictions::AssertIOAllowed();
+ return (GetFileAttributes(path.value().c_str()) != INVALID_FILE_ATTRIBUTES);
+}
+
+bool PathIsWritable(const FilePath& path) {
+ ThreadRestrictions::AssertIOAllowed();
+ HANDLE dir =
+ CreateFile(path.value().c_str(), FILE_ADD_FILE, kFileShareAll,
+ NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
+
+ if (dir == INVALID_HANDLE_VALUE)
+ return false;
+
+ CloseHandle(dir);
+ return true;
+}
+
+bool DirectoryExists(const FilePath& path) {
+ ThreadRestrictions::AssertIOAllowed();
+ DWORD fileattr = GetFileAttributes(path.value().c_str());
+ if (fileattr != INVALID_FILE_ATTRIBUTES)
+ return (fileattr & FILE_ATTRIBUTE_DIRECTORY) != 0;
+ return false;
+}
+
+bool GetTempDir(FilePath* path) {
+ wchar_t temp_path[MAX_PATH + 1];
+ DWORD path_len = ::GetTempPath(MAX_PATH, temp_path);
+ if (path_len >= MAX_PATH || path_len <= 0)
+ return false;
+ // TODO(evanm): the old behavior of this function was to always strip the
+ // trailing slash. We duplicate this here, but it shouldn't be necessary
+ // when everyone is using the appropriate FilePath APIs.
+ *path = FilePath(temp_path).StripTrailingSeparators();
+ return true;
+}
+
+FilePath GetHomeDir() {
+ char16 result[MAX_PATH];
+ if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_PROFILE, NULL, SHGFP_TYPE_CURRENT,
+ result)) &&
+ result[0]) {
+ return FilePath(result);
+ }
+
+ // Fall back to the temporary directory on failure.
+ FilePath temp;
+ if (GetTempDir(&temp))
+ return temp;
+
+ // Last resort.
+ return FilePath(L"C:\\");
+}
+
+bool CreateTemporaryFile(FilePath* path) {
+ ThreadRestrictions::AssertIOAllowed();
+
+ FilePath temp_file;
+
+ if (!GetTempDir(path))
+ return false;
+
+ if (CreateTemporaryFileInDir(*path, &temp_file)) {
+ *path = temp_file;
+ return true;
+ }
+
+ return false;
+}
+
+// On POSIX we have semantics to create and open a temporary file
+// atomically.
+// TODO(jrg): is there equivalent call to use on Windows instead of
+// going 2-step?
+FILE* CreateAndOpenTemporaryFileInDir(const FilePath& dir, FilePath* path) {
+ ThreadRestrictions::AssertIOAllowed();
+ if (!CreateTemporaryFileInDir(dir, path)) {
+ return NULL;
+ }
+ // Open file in binary mode, to avoid problems with fwrite. On Windows
+ // it replaces \n's with \r\n's, which may surprise you.
+ // Reference: http://msdn.microsoft.com/en-us/library/h9t88zwz(VS.71).aspx
+ return OpenFile(*path, "wb+");
+}
+
+bool CreateTemporaryFileInDir(const FilePath& dir, FilePath* temp_file) {
+ ThreadRestrictions::AssertIOAllowed();
+
+ wchar_t temp_name[MAX_PATH + 1];
+
+ if (!GetTempFileName(dir.value().c_str(), L"", 0, temp_name)) {
+ DPLOG(WARNING) << "Failed to get temporary file name in "
+ << UTF16ToUTF8(dir.value());
+ return false;
+ }
+
+ wchar_t long_temp_name[MAX_PATH + 1];
+ DWORD long_name_len = GetLongPathName(temp_name, long_temp_name, MAX_PATH);
+ if (long_name_len > MAX_PATH || long_name_len == 0) {
+ // GetLongPathName() failed, but we still have a temporary file.
+ *temp_file = FilePath(temp_name);
+ return true;
+ }
+
+ FilePath::StringType long_temp_name_str;
+ long_temp_name_str.assign(long_temp_name, long_name_len);
+ *temp_file = FilePath(long_temp_name_str);
+ return true;
+}
+
+bool CreateTemporaryDirInDir(const FilePath& base_dir,
+ const FilePath::StringType& prefix,
+ FilePath* new_dir) {
+ ThreadRestrictions::AssertIOAllowed();
+
+ FilePath path_to_create;
+
+ for (int count = 0; count < 50; ++count) {
+ // Try create a new temporary directory with random generated name. If
+ // the one exists, keep trying another path name until we reach some limit.
+ string16 new_dir_name;
+ new_dir_name.assign(prefix);
+ new_dir_name.append(IntToString16(GetCurrentProcId()));
+ new_dir_name.push_back('_');
+ new_dir_name.append(IntToString16(RandInt(0, kint16max)));
+
+ path_to_create = base_dir.Append(new_dir_name);
+ if (::CreateDirectory(path_to_create.value().c_str(), NULL)) {
+ *new_dir = path_to_create;
+ return true;
+ }
+ }
+
+ return false;
+}
+
+bool CreateNewTempDirectory(const FilePath::StringType& prefix,
+ FilePath* new_temp_path) {
+ ThreadRestrictions::AssertIOAllowed();
+
+ FilePath system_temp_dir;
+ if (!GetTempDir(&system_temp_dir))
+ return false;
+
+ return CreateTemporaryDirInDir(system_temp_dir, prefix, new_temp_path);
+}
+
+bool CreateDirectoryAndGetError(const FilePath& full_path,
+ File::Error* error) {
+ ThreadRestrictions::AssertIOAllowed();
+
+ // If the path exists, we've succeeded if it's a directory, failed otherwise.
+ const wchar_t* full_path_str = full_path.value().c_str();
+ DWORD fileattr = ::GetFileAttributes(full_path_str);
+ if (fileattr != INVALID_FILE_ATTRIBUTES) {
+ if ((fileattr & FILE_ATTRIBUTE_DIRECTORY) != 0) {
+ DVLOG(1) << "CreateDirectory(" << full_path_str << "), "
+ << "directory already exists.";
+ return true;
+ }
+ DLOG(WARNING) << "CreateDirectory(" << full_path_str << "), "
+ << "conflicts with existing file.";
+ if (error) {
+ *error = File::FILE_ERROR_NOT_A_DIRECTORY;
+ }
+ return false;
+ }
+
+ // Invariant: Path does not exist as file or directory.
+
+ // Attempt to create the parent recursively. This will immediately return
+ // true if it already exists, otherwise will create all required parent
+ // directories starting with the highest-level missing parent.
+ FilePath parent_path(full_path.DirName());
+ if (parent_path.value() == full_path.value()) {
+ if (error) {
+ *error = File::FILE_ERROR_NOT_FOUND;
+ }
+ return false;
+ }
+ if (!CreateDirectoryAndGetError(parent_path, error)) {
+ DLOG(WARNING) << "Failed to create one of the parent directories.";
+ if (error) {
+ DCHECK(*error != File::FILE_OK);
+ }
+ return false;
+ }
+
+ if (!::CreateDirectory(full_path_str, NULL)) {
+ DWORD error_code = ::GetLastError();
+ if (error_code == ERROR_ALREADY_EXISTS && DirectoryExists(full_path)) {
+ // This error code ERROR_ALREADY_EXISTS doesn't indicate whether we
+ // were racing with someone creating the same directory, or a file
+ // with the same path. If DirectoryExists() returns true, we lost the
+ // race to create the same directory.
+ return true;
+ } else {
+ if (error)
+ *error = File::OSErrorToFileError(error_code);
+ DLOG(WARNING) << "Failed to create directory " << full_path_str
+ << ", last error is " << error_code << ".";
+ return false;
+ }
+ } else {
+ return true;
+ }
+}
+
+bool NormalizeFilePath(const FilePath& path, FilePath* real_path) {
+ ThreadRestrictions::AssertIOAllowed();
+ FilePath mapped_file;
+ if (!NormalizeToNativeFilePath(path, &mapped_file))
+ return false;
+ // NormalizeToNativeFilePath() will return a path that starts with
+ // "\Device\Harddisk...". Helper DevicePathToDriveLetterPath()
+ // will find a drive letter which maps to the path's device, so
+ // that we return a path starting with a drive letter.
+ return DevicePathToDriveLetterPath(mapped_file, real_path);
+}
+
+bool DevicePathToDriveLetterPath(const FilePath& nt_device_path,
+ FilePath* out_drive_letter_path) {
+ ThreadRestrictions::AssertIOAllowed();
+
+ // Get the mapping of drive letters to device paths.
+ const int kDriveMappingSize = 1024;
+ wchar_t drive_mapping[kDriveMappingSize] = {'\0'};
+ if (!::GetLogicalDriveStrings(kDriveMappingSize - 1, drive_mapping)) {
+ DLOG(ERROR) << "Failed to get drive mapping.";
+ return false;
+ }
+
+ // The drive mapping is a sequence of null terminated strings.
+ // The last string is empty.
+ wchar_t* drive_map_ptr = drive_mapping;
+ wchar_t device_path_as_string[MAX_PATH];
+ wchar_t drive[] = L" :";
+
+ // For each string in the drive mapping, get the junction that links
+ // to it. If that junction is a prefix of |device_path|, then we
+ // know that |drive| is the real path prefix.
+ while (*drive_map_ptr) {
+ drive[0] = drive_map_ptr[0]; // Copy the drive letter.
+
+ if (QueryDosDevice(drive, device_path_as_string, MAX_PATH)) {
+ FilePath device_path(device_path_as_string);
+ if (device_path == nt_device_path ||
+ device_path.IsParent(nt_device_path)) {
+ *out_drive_letter_path = FilePath(drive +
+ nt_device_path.value().substr(wcslen(device_path_as_string)));
+ return true;
+ }
+ }
+ // Move to the next drive letter string, which starts one
+ // increment after the '\0' that terminates the current string.
+ while (*drive_map_ptr++);
+ }
+
+ // No drive matched. The path does not start with a device junction
+ // that is mounted as a drive letter. This means there is no drive
+ // letter path to the volume that holds |device_path|, so fail.
+ return false;
+}
+
+bool NormalizeToNativeFilePath(const FilePath& path, FilePath* nt_path) {
+ ThreadRestrictions::AssertIOAllowed();
+ // In Vista, GetFinalPathNameByHandle() would give us the real path
+ // from a file handle. If we ever deprecate XP, consider changing the
+ // code below to a call to GetFinalPathNameByHandle(). The method this
+ // function uses is explained in the following msdn article:
+ // http://msdn.microsoft.com/en-us/library/aa366789(VS.85).aspx
+ base::win::ScopedHandle file_handle(
+ ::CreateFile(path.value().c_str(),
+ GENERIC_READ,
+ kFileShareAll,
+ NULL,
+ OPEN_EXISTING,
+ FILE_ATTRIBUTE_NORMAL,
+ NULL));
+ if (!file_handle)
+ return false;
+
+ // Create a file mapping object. Can't easily use MemoryMappedFile, because
+ // we only map the first byte, and need direct access to the handle. You can
+ // not map an empty file, this call fails in that case.
+ base::win::ScopedHandle file_map_handle(
+ ::CreateFileMapping(file_handle.Get(),
+ NULL,
+ PAGE_READONLY,
+ 0,
+ 1, // Just one byte. No need to look at the data.
+ NULL));
+ if (!file_map_handle)
+ return false;
+
+ // Use a view of the file to get the path to the file.
+ void* file_view = MapViewOfFile(file_map_handle.Get(),
+ FILE_MAP_READ, 0, 0, 1);
+ if (!file_view)
+ return false;
+
+ // The expansion of |path| into a full path may make it longer.
+ // GetMappedFileName() will fail if the result is longer than MAX_PATH.
+ // Pad a bit to be safe. If kMaxPathLength is ever changed to be less
+ // than MAX_PATH, it would be nessisary to test that GetMappedFileName()
+ // not return kMaxPathLength. This would mean that only part of the
+ // path fit in |mapped_file_path|.
+ const int kMaxPathLength = MAX_PATH + 10;
+ wchar_t mapped_file_path[kMaxPathLength];
+ bool success = false;
+ HANDLE cp = GetCurrentProcess();
+ if (::GetMappedFileNameW(cp, file_view, mapped_file_path, kMaxPathLength)) {
+ *nt_path = FilePath(mapped_file_path);
+ success = true;
+ }
+ ::UnmapViewOfFile(file_view);
+ return success;
+}
+
+// TODO(rkc): Work out if we want to handle NTFS junctions here or not, handle
+// them if we do decide to.
+bool IsLink(const FilePath& file_path) {
+ return false;
+}
+
+bool GetFileInfo(const FilePath& file_path, File::Info* results) {
+ ThreadRestrictions::AssertIOAllowed();
+
+ WIN32_FILE_ATTRIBUTE_DATA attr;
+ if (!GetFileAttributesEx(file_path.value().c_str(),
+ GetFileExInfoStandard, &attr)) {
+ return false;
+ }
+
+ ULARGE_INTEGER size;
+ size.HighPart = attr.nFileSizeHigh;
+ size.LowPart = attr.nFileSizeLow;
+ results->size = size.QuadPart;
+
+ results->is_directory =
+ (attr.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
+ results->last_modified = Time::FromFileTime(attr.ftLastWriteTime);
+ results->last_accessed = Time::FromFileTime(attr.ftLastAccessTime);
+ results->creation_time = Time::FromFileTime(attr.ftCreationTime);
+
+ return true;
+}
+
+FILE* OpenFile(const FilePath& filename, const char* mode) {
+ ThreadRestrictions::AssertIOAllowed();
+ std::wstring w_mode = ASCIIToWide(std::string(mode));
+ return _wfsopen(filename.value().c_str(), w_mode.c_str(), _SH_DENYNO);
+}
+
+FILE* FileToFILE(File file, const char* mode) {
+ if (!file.IsValid())
+ return NULL;
+ int fd =
+ _open_osfhandle(reinterpret_cast<intptr_t>(file.GetPlatformFile()), 0);
+ if (fd < 0)
+ return NULL;
+ file.TakePlatformFile();
+ FILE* stream = _fdopen(fd, mode);
+ if (!stream)
+ _close(fd);
+ return stream;
+}
+
+int ReadFile(const FilePath& filename, char* data, int max_size) {
+ ThreadRestrictions::AssertIOAllowed();
+ base::win::ScopedHandle file(CreateFile(filename.value().c_str(),
+ GENERIC_READ,
+ FILE_SHARE_READ | FILE_SHARE_WRITE,
+ NULL,
+ OPEN_EXISTING,
+ FILE_FLAG_SEQUENTIAL_SCAN,
+ NULL));
+ if (!file)
+ return -1;
+
+ DWORD read;
+ if (::ReadFile(file, data, max_size, &read, NULL))
+ return read;
+
+ return -1;
+}
+
+int WriteFile(const FilePath& filename, const char* data, int size) {
+ ThreadRestrictions::AssertIOAllowed();
+ base::win::ScopedHandle file(CreateFile(filename.value().c_str(),
+ GENERIC_WRITE,
+ 0,
+ NULL,
+ CREATE_ALWAYS,
+ 0,
+ NULL));
+ if (!file) {
+ DPLOG(WARNING) << "CreateFile failed for path "
+ << UTF16ToUTF8(filename.value());
+ return -1;
+ }
+
+ DWORD written;
+ BOOL result = ::WriteFile(file, data, size, &written, NULL);
+ if (result && static_cast<int>(written) == size)
+ return written;
+
+ if (!result) {
+ // WriteFile failed.
+ DPLOG(WARNING) << "writing file " << UTF16ToUTF8(filename.value())
+ << " failed";
+ } else {
+ // Didn't write all the bytes.
+ DLOG(WARNING) << "wrote" << written << " bytes to "
+ << UTF16ToUTF8(filename.value()) << " expected " << size;
+ }
+ return -1;
+}
+
+int AppendToFile(const FilePath& filename, const char* data, int size) {
+ ThreadRestrictions::AssertIOAllowed();
+ base::win::ScopedHandle file(CreateFile(filename.value().c_str(),
+ FILE_APPEND_DATA,
+ 0,
+ NULL,
+ OPEN_EXISTING,
+ 0,
+ NULL));
+ if (!file) {
+ DPLOG(WARNING) << "CreateFile failed for path "
+ << UTF16ToUTF8(filename.value());
+ return -1;
+ }
+
+ DWORD written;
+ BOOL result = ::WriteFile(file, data, size, &written, NULL);
+ if (result && static_cast<int>(written) == size)
+ return written;
+
+ if (!result) {
+ // WriteFile failed.
+ DPLOG(WARNING) << "writing file " << UTF16ToUTF8(filename.value())
+ << " failed";
+ } else {
+ // Didn't write all the bytes.
+ DLOG(WARNING) << "wrote" << written << " bytes to "
+ << UTF16ToUTF8(filename.value()) << " expected " << size;
+ }
+ return -1;
+}
+
+// Gets the current working directory for the process.
+bool GetCurrentDirectory(FilePath* dir) {
+ ThreadRestrictions::AssertIOAllowed();
+
+ wchar_t system_buffer[MAX_PATH];
+ system_buffer[0] = 0;
+ DWORD len = ::GetCurrentDirectory(MAX_PATH, system_buffer);
+ if (len == 0 || len > MAX_PATH)
+ return false;
+ // TODO(evanm): the old behavior of this function was to always strip the
+ // trailing slash. We duplicate this here, but it shouldn't be necessary
+ // when everyone is using the appropriate FilePath APIs.
+ std::wstring dir_str(system_buffer);
+ *dir = FilePath(dir_str).StripTrailingSeparators();
+ return true;
+}
+
+// Sets the current working directory for the process.
+bool SetCurrentDirectory(const FilePath& directory) {
+ ThreadRestrictions::AssertIOAllowed();
+ BOOL ret = ::SetCurrentDirectory(directory.value().c_str());
+ return ret != 0;
+}
+
+int GetMaximumPathComponentLength(const FilePath& path) {
+ ThreadRestrictions::AssertIOAllowed();
+
+ wchar_t volume_path[MAX_PATH];
+ if (!GetVolumePathNameW(path.NormalizePathSeparators().value().c_str(),
+ volume_path,
+ arraysize(volume_path))) {
+ return -1;
+ }
+
+ DWORD max_length = 0;
+ if (!GetVolumeInformationW(volume_path, NULL, 0, NULL, &max_length, NULL,
+ NULL, 0)) {
+ return -1;
+ }
+
+ // Length of |path| with path separator appended.
+ size_t prefix = path.StripTrailingSeparators().value().size() + 1;
+ // The whole path string must be shorter than MAX_PATH. That is, it must be
+ // prefix + component_length < MAX_PATH (or equivalently, <= MAX_PATH - 1).
+ int whole_path_limit = std::max(0, MAX_PATH - 1 - static_cast<int>(prefix));
+ return std::min(whole_path_limit, static_cast<int>(max_length));
+}
+
+// -----------------------------------------------------------------------------
+
+namespace internal {
+
+bool MoveUnsafe(const FilePath& from_path, const FilePath& to_path) {
+ ThreadRestrictions::AssertIOAllowed();
+
+ // NOTE: I suspect we could support longer paths, but that would involve
+ // analyzing all our usage of files.
+ if (from_path.value().length() >= MAX_PATH ||
+ to_path.value().length() >= MAX_PATH) {
+ return false;
+ }
+ if (MoveFileEx(from_path.value().c_str(), to_path.value().c_str(),
+ MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING) != 0)
+ return true;
+
+ // Keep the last error value from MoveFileEx around in case the below
+ // fails.
+ bool ret = false;
+ DWORD last_error = ::GetLastError();
+
+ if (DirectoryExists(from_path)) {
+ // MoveFileEx fails if moving directory across volumes. We will simulate
+ // the move by using Copy and Delete. Ideally we could check whether
+ // from_path and to_path are indeed in different volumes.
+ ret = internal::CopyAndDeleteDirectory(from_path, to_path);
+ }
+
+ if (!ret) {
+ // Leave a clue about what went wrong so that it can be (at least) picked
+ // up by a PLOG entry.
+ ::SetLastError(last_error);
+ }
+
+ return ret;
+}
+
+bool CopyFileUnsafe(const FilePath& from_path, const FilePath& to_path) {
+ ThreadRestrictions::AssertIOAllowed();
+
+ // NOTE: I suspect we could support longer paths, but that would involve
+ // analyzing all our usage of files.
+ if (from_path.value().length() >= MAX_PATH ||
+ to_path.value().length() >= MAX_PATH) {
+ return false;
+ }
+
+ // Unlike the posix implementation that copies the file manually and discards
+ // the ACL bits, CopyFile() copies the complete SECURITY_DESCRIPTOR and access
+ // bits, which is usually not what we want. We can't do much about the
+ // SECURITY_DESCRIPTOR but at least remove the read only bit.
+ const wchar_t* dest = to_path.value().c_str();
+ if (!::CopyFile(from_path.value().c_str(), dest, false)) {
+ // Copy failed.
+ return false;
+ }
+ DWORD attrs = GetFileAttributes(dest);
+ if (attrs == INVALID_FILE_ATTRIBUTES) {
+ return false;
+ }
+ if (attrs & FILE_ATTRIBUTE_READONLY) {
+ SetFileAttributes(dest, attrs & ~FILE_ATTRIBUTE_READONLY);
+ }
+ return true;
+}
+
+bool CopyAndDeleteDirectory(const FilePath& from_path,
+ const FilePath& to_path) {
+ ThreadRestrictions::AssertIOAllowed();
+ if (CopyDirectory(from_path, to_path, true)) {
+ if (DeleteFile(from_path, true))
+ return true;
+
+ // Like Move, this function is not transactional, so we just
+ // leave the copied bits behind if deleting from_path fails.
+ // If to_path exists previously then we have already overwritten
+ // it by now, we don't get better off by deleting the new bits.
+ }
+ return false;
+}
+
+} // namespace internal
+} // namespace base
diff --git a/base/files/important_file_writer.cc b/base/files/important_file_writer.cc
index bf4e003..6e3be2a 100644
--- a/base/files/important_file_writer.cc
+++ b/base/files/important_file_writer.cc
@@ -10,9 +10,9 @@
#include "base/bind.h"
#include "base/critical_closure.h"
-#include "base/file_util.h"
#include "base/files/file.h"
#include "base/files/file_path.h"
+#include "base/files/file_util.h"
#include "base/logging.h"
#include "base/metrics/histogram.h"
#include "base/strings/string_number_conversions.h"
diff --git a/base/files/important_file_writer_unittest.cc b/base/files/important_file_writer_unittest.cc
index 3f62fe4..c55f0cc 100644
--- a/base/files/important_file_writer_unittest.cc
+++ b/base/files/important_file_writer_unittest.cc
@@ -6,8 +6,8 @@
#include "base/bind.h"
#include "base/compiler_specific.h"
-#include "base/file_util.h"
#include "base/files/file_path.h"
+#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/logging.h"
#include "base/message_loop/message_loop.h"
diff --git a/base/files/memory_mapped_file_unittest.cc b/base/files/memory_mapped_file_unittest.cc
index 21b0df4..6627d40 100644
--- a/base/files/memory_mapped_file_unittest.cc
+++ b/base/files/memory_mapped_file_unittest.cc
@@ -4,8 +4,8 @@
#include "base/files/memory_mapped_file.h"
-#include "base/file_util.h"
#include "base/files/file_path.h"
+#include "base/files/file_util.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/platform_test.h"
diff --git a/base/files/scoped_temp_dir.cc b/base/files/scoped_temp_dir.cc
index b893b02..27b758e 100644
--- a/base/files/scoped_temp_dir.cc
+++ b/base/files/scoped_temp_dir.cc
@@ -4,7 +4,7 @@
#include "base/files/scoped_temp_dir.h"
-#include "base/file_util.h"
+#include "base/files/file_util.h"
#include "base/logging.h"
namespace base {
diff --git a/base/files/scoped_temp_dir_unittest.cc b/base/files/scoped_temp_dir_unittest.cc
index da22230..a19f34d 100644
--- a/base/files/scoped_temp_dir_unittest.cc
+++ b/base/files/scoped_temp_dir_unittest.cc
@@ -4,8 +4,8 @@
#include <string>
-#include "base/file_util.h"
#include "base/files/file.h"
+#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "testing/gtest/include/gtest/gtest.h"