#include "base/files/file_util.h"
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <algorithm>
#include <fstream>
#include <initializer_list>
#include <memory>
#include <optional>
#include <set>
#include <utility>
#include <vector>
#include "base/base_paths.h"
#include "base/command_line.h"
#include "base/compiler_specific.h"
#include "base/environment.h"
#include "base/files/file.h"
#include "base/files/file_enumerator.h"
#include "base/files/file_path.h"
#include "base/files/platform_file.h"
#include "base/files/scoped_file.h"
#include "base/files/scoped_temp_dir.h"
#include "base/functional/bind.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/rand_util.h"
#include "base/scoped_environment_variable_override.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/bind.h"
#include "base/test/multiprocess_test.h"
#include "base/test/scoped_logging_settings.h"
#include "base/test/task_environment.h"
#include "base/test/test_file_util.h"
#include "base/test/test_timeouts.h"
#include "base/threading/platform_thread.h"
#include "base/threading/thread.h"
#include "base/time/time.h"
#include "base/uuid.h"
#include "build/branding_buildflags.h"
#include "build/build_config.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/multiprocess_func_list.h"
#include "testing/platform_test.h"
#include "third_party/abseil-cpp/absl/cleanup/cleanup.h"
#include "third_party/fuzztest/src/fuzztest/fuzztest.h"
#if BUILDFLAG(IS_WIN)
#include <tchar.h>
#include <windows.h>
#include <fileapi.h>
#include <shellapi.h>
#include <shlobj.h>
#include "base/scoped_native_library.h"
#include "base/strings/string_number_conversions.h"
#include "base/test/file_path_reparse_point_win.h"
#include "base/test/gtest_util.h"
#include "base/win/scoped_handle.h"
#include "base/win/windows_handle_util.h"
#endif
#if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
#include <errno.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <unistd.h>
#endif
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID)
#include <sys/socket.h>
#endif
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
#include <linux/fs.h>
#endif
#if BUILDFLAG(IS_ANDROID)
#include "base/test/android/content_uri_test_utils.h"
#endif
#if BUILDFLAG(IS_FUCHSIA)
#include "base/test/scoped_dev_zero_fuchsia.h"
#endif
#define FPL(x) FILE_PATH_LITERAL(x)
namespace base {
namespace {
const size_t kLargeFileSize = (1 << 16) + 3;
#if BUILDFLAG(IS_WIN)
FilePath MakeShortFilePath(const FilePath& input) {
DWORD path_short_len = ::GetShortPathName(input.value().c_str(), nullptr, 0);
if (path_short_len == 0UL) {
return FilePath();
}
std::wstring path_short_str;
path_short_len = ::GetShortPathName(
input.value().c_str(), WriteInto(&path_short_str, path_short_len),
path_short_len);
if (path_short_len == 0UL) {
return FilePath();
}
return FilePath(path_short_str);
}
#endif
#if BUILDFLAG(IS_MAC)
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
#if !BUILDFLAG(IS_FUCHSIA)
void SetReadOnly(const FilePath& path, bool read_only) {
#if BUILDFLAG(IS_WIN)
DWORD attrs = GetFileAttributes(path.value().c_str());
ASSERT_NE(INVALID_FILE_ATTRIBUTES, attrs);
ASSERT_TRUE(SetFileAttributes(
path.value().c_str(), read_only ? (attrs | FILE_ATTRIBUTE_READONLY)
: (attrs & ~FILE_ATTRIBUTE_READONLY)));
DWORD expected =
read_only
? ((attrs & (FILE_ATTRIBUTE_ARCHIVE | FILE_ATTRIBUTE_DIRECTORY)) |
FILE_ATTRIBUTE_READONLY)
: (attrs & (FILE_ATTRIBUTE_ARCHIVE | FILE_ATTRIBUTE_DIRECTORY));
attrs = GetFileAttributes(path.value().c_str()) &
~(FILE_ATTRIBUTE_NOT_CONTENT_INDEXED | FILE_ATTRIBUTE_COMPRESSED);
ASSERT_EQ(expected, attrs);
#else
mode_t mode = read_only ? S_IRUSR : (S_IRUSR | S_IWUSR);
EXPECT_TRUE(SetPosixFilePermissions(
path, DirectoryExists(path) ? (mode | S_IXUSR) : mode));
#endif
}
bool IsReadOnly(const FilePath& path) {
#if BUILDFLAG(IS_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
}
#endif
const wchar_t bogus_content[] = L"I'm cannon fodder.";
const int FILES_AND_DIRECTORIES =
FileEnumerator::FILES | FileEnumerator::DIRECTORIES;
class FileUtilTest : public PlatformTest {
protected:
void SetUp() override {
PlatformTest::SetUp();
ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
}
#if BUILDFLAG(IS_WIN)
bool AreShortFilePathsEnabled() {
static const bool enabled = [this] {
using AreShortNamesEnabledFunction = decltype(&::AreShortNamesEnabled);
AreShortNamesEnabledFunction short_names_func =
reinterpret_cast<AreShortNamesEnabledFunction>(GetProcAddress(
::GetModuleHandleW(L"kernel32.dll"), "AreShortNamesEnabled"));
if (!short_names_func) {
return true;
}
base::File temp_dir(temp_dir_.GetPath(),
base::File::FLAG_OPEN_ALWAYS |
base::File::FLAG_WIN_BACKUP_SEMANTICS |
base::File::FLAG_READ);
BOOL enabled = false;
if (!short_names_func(temp_dir.GetPlatformFile(), &enabled)) {
DPLOG(ERROR) << "Call to AreShortNamesEnabled failed.";
return true;
}
return !!enabled;
}();
return enabled;
}
#endif
ScopedTempDir temp_dir_;
};
class FindResultCollector {
public:
explicit FindResultCollector(FileEnumerator* enumerator) {
FilePath cur_file;
while (!(cur_file = enumerator->Next()).value().empty()) {
FilePath::StringType path = cur_file.value();
EXPECT_TRUE(files_.end() == files_.find(path))
<< "Same file returned twice";
files_.insert(path);
}
}
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_;
};
void CreateTextFile(const FilePath& filename, const std::wstring& contents) {
std::wofstream file;
#if BUILDFLAG(IS_WIN)
file.open(filename.value().c_str());
#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
file.open(filename.value());
#endif
ASSERT_TRUE(file.is_open());
file << contents;
file.close();
}
std::wstring ReadTextFile(const FilePath& filename) {
wchar_t contents[64];
std::wifstream file;
#if BUILDFLAG(IS_WIN)
file.open(filename.value().c_str());
#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
file.open(filename.value());
#endif
EXPECT_TRUE(file.is_open());
file.getline(contents, std::size(contents));
file.close();
return std::wstring(contents);
}
void GetIsInheritable(FILE* stream, bool* is_inheritable) {
#if BUILDFLAG(IS_WIN)
HANDLE handle = reinterpret_cast<HANDLE>(_get_osfhandle(_fileno(stream)));
ASSERT_NE(INVALID_HANDLE_VALUE, handle);
DWORD info = 0;
ASSERT_EQ(TRUE, ::GetHandleInformation(handle, &info));
*is_inheritable = ((info & HANDLE_FLAG_INHERIT) != 0);
#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
int fd = fileno(stream);
ASSERT_NE(-1, fd);
int flags = fcntl(fd, F_GETFD, 0);
ASSERT_NE(-1, flags);
*is_inheritable = ((flags & FD_CLOEXEC) == 0);
#else
#error Not implemented
#endif
}
#if BUILDFLAG(IS_POSIX)
class ScopedWorkingDirectory {
public:
explicit ScopedWorkingDirectory(const FilePath& new_working_dir) {
CHECK(base::GetCurrentDirectory(&original_working_directory_));
CHECK(base::SetCurrentDirectory(new_working_dir));
}
~ScopedWorkingDirectory() {
CHECK(base::SetCurrentDirectory(original_working_directory_));
}
private:
base::FilePath original_working_directory_;
};
TEST_F(FileUtilTest, MakeAbsoluteFilePathNoResolveSymbolicLinks) {
FilePath cwd;
ASSERT_TRUE(GetCurrentDirectory(&cwd));
const std::pair<FilePath, std::optional<FilePath>> kExpectedResults[]{
{FilePath(), std::nullopt},
{FilePath("."), cwd},
{FilePath(".."), cwd.DirName()},
{FilePath("a/.."), cwd},
{FilePath("a/b/.."), cwd.Append(FPL("a"))},
{FilePath("/tmp/../.."), FilePath("/")},
{FilePath("/tmp/../"), FilePath("/")},
{FilePath("/tmp/a/b/../c/../.."), FilePath("/tmp")},
{FilePath("/././tmp/./a/./b/../c/./../.."), FilePath("/tmp")},
{FilePath("/.././../tmp"), FilePath("/tmp")},
{FilePath("/..///.////..////tmp"), FilePath("/tmp")},
{FilePath("//..///.////..////tmp"), FilePath("//tmp")},
{FilePath("///..///.////..////tmp"), FilePath("/tmp")},
};
for (auto& expected_result : kExpectedResults) {
EXPECT_EQ(MakeAbsoluteFilePathNoResolveSymbolicLinks(expected_result.first),
expected_result.second);
}
const FilePath temp_dir_path = temp_dir_.GetPath();
ScopedWorkingDirectory scoped_cwd(temp_dir_path);
ASSERT_TRUE(temp_dir_.Delete());
ASSERT_FALSE(
MakeAbsoluteFilePathNoResolveSymbolicLinks(FilePath("relative_file_path"))
.has_value());
}
#endif
TEST_F(FileUtilTest, FileAndDirectorySize) {
FilePath file_01 = temp_dir_.GetPath().Append(FPL("The file 01.txt"));
CreateTextFile(file_01, L"12345678901234567890");
std::optional<int64_t> size_f1 = GetFileSize(file_01);
ASSERT_THAT(size_f1, testing::Optional(20));
std::optional<int64_t> size_f1_out = GetFileSize(file_01);
ASSERT_TRUE(size_f1_out.has_value());
EXPECT_EQ(size_f1.value(), size_f1_out.value());
FilePath subdir_path = temp_dir_.GetPath().Append(FPL("Level2"));
CreateDirectory(subdir_path);
FilePath file_02 = subdir_path.Append(FPL("The file 02.txt"));
CreateTextFile(file_02, L"123456789012345678901234567890");
std::optional<int64_t> size_f2 = GetFileSize(file_02);
ASSERT_THAT(size_f2, testing::Optional(30));
std::optional<int64_t> size_f2_out = GetFileSize(file_02);
ASSERT_TRUE(size_f2_out.has_value());
EXPECT_EQ(size_f2.value(), size_f2_out.value());
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_t computed_size = ComputeDirectorySize(temp_dir_.GetPath());
EXPECT_EQ(size_f1.value() + size_f2.value() + 3, computed_size);
}
TEST_F(FileUtilTest, NormalizeFilePathBasic) {
FilePath file_a_path = temp_dir_.GetPath().Append(FPL("file_a"));
FilePath dir_path = temp_dir_.GetPath().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));
ASSERT_FALSE(normalized_file_a_path.empty());
ASSERT_TRUE(PathExists(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));
ASSERT_FALSE(normalized_file_b_path.empty());
ASSERT_TRUE(PathExists(normalized_file_b_path));
ASSERT_TRUE(normalized_file_a_path.DirName().IsParent(
normalized_file_b_path.DirName()));
}
#if BUILDFLAG(IS_WIN)
TEST_F(FileUtilTest, NormalizeFileEmptyFile) {
const wchar_t empty_content[] = L"";
FilePath file_a_path = temp_dir_.GetPath().Append(FPL("file_empty_a"));
FilePath dir_path = temp_dir_.GetPath().Append(FPL("dir"));
FilePath file_b_path = dir_path.Append(FPL("file_empty_b"));
ASSERT_TRUE(CreateDirectory(dir_path));
FilePath normalized_file_a_path, normalized_file_b_path;
ASSERT_FALSE(PathExists(file_a_path));
EXPECT_FALSE(NormalizeFilePath(file_a_path, &normalized_file_a_path))
<< "NormalizeFilePath() should fail on nonexistent paths.";
CreateTextFile(file_a_path, empty_content);
ASSERT_TRUE(PathExists(file_a_path));
EXPECT_TRUE(NormalizeFilePath(file_a_path, &normalized_file_a_path));
EXPECT_FALSE(normalized_file_a_path.empty());
EXPECT_TRUE(PathExists(normalized_file_a_path));
CreateTextFile(file_b_path, empty_content);
ASSERT_TRUE(PathExists(file_b_path));
EXPECT_TRUE(NormalizeFilePath(file_b_path, &normalized_file_b_path));
EXPECT_FALSE(normalized_file_b_path.empty());
EXPECT_TRUE(PathExists(normalized_file_b_path));
EXPECT_TRUE(normalized_file_a_path.DirName().IsParent(
normalized_file_b_path.DirName()));
}
TEST_F(FileUtilTest, NormalizeFilePathReparsePoints) {
FilePath base_a = temp_dir_.GetPath().Append(FPL("base_a"));
std::wstring temp_base_a = base_a.value();
ASSERT_FALSE(temp_base_a.empty());
temp_base_a[0] = ToUpperASCII(char16_t{temp_base_a[0]});
base_a = FilePath(temp_base_a);
ASSERT_TRUE(CreateDirectory(base_a));
base_a = MakeLongFilePath(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);
FilePath sub_long_rel(FPL("sub_long"));
FilePath deep_txt(FPL("deepfile.txt"));
int target_length = MAX_PATH - 1;
target_length -= (sub_a.value().length() + 1);
target_length -= (sub_long_rel.Append(deep_txt).value().length() + 1);
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(static_cast<size_t>(MAX_PATH - 1), 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_.GetPath().Append(FPL("base_b"));
ASSERT_TRUE(CreateDirectory(base_b));
base_b = MakeLongFilePath(base_b);
FilePath to_sub_a = base_b.Append(FPL("to_sub_a"));
ASSERT_TRUE(CreateDirectory(to_sub_a));
FilePath normalized_path;
{
auto reparse_to_sub_a = test::FilePathReparsePoint::Create(to_sub_a, sub_a);
ASSERT_TRUE(reparse_to_sub_a.has_value());
FilePath to_base_b = base_b.Append(FPL("to_base_b"));
ASSERT_TRUE(CreateDirectory(to_base_b));
auto reparse_to_base_b =
test::FilePathReparsePoint::Create(to_base_b, base_b);
ASSERT_TRUE(reparse_to_base_b.has_value());
FilePath to_sub_long = base_b.Append(FPL("to_sub_long"));
ASSERT_TRUE(CreateDirectory(to_sub_long));
auto reparse_to_sub_long =
test::FilePathReparsePoint::Create(to_sub_long, sub_long);
ASSERT_TRUE(reparse_to_sub_long.has_value());
ASSERT_TRUE(NormalizeFilePath(file_txt, &normalized_path));
ASSERT_EQ(file_txt.value(), normalized_path.value());
ASSERT_TRUE(
NormalizeFilePath(to_sub_a.Append(FPL("file.txt")), &normalized_path));
ASSERT_EQ(file_txt.value(), normalized_path.value());
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_EQ(file_txt.value(), normalized_path.value());
FilePath long_path = base_b;
const int kLengthLimit = MAX_PATH + 40;
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));
ASSERT_TRUE(
NormalizeFilePath(to_sub_long.Append(deep_txt), &normalized_path));
ASSERT_EQ(normalized_path, deep_file);
}
ASSERT_FALSE(
NormalizeFilePath(to_sub_a.Append(FPL("file.txt")), &normalized_path));
}
TEST_F(FileUtilTest, NormalizeFilePathWithLongPath) {
const FilePath::StringType kPathPrefix(FPL("\\\\?\\"));
constexpr int kLengthLimit = MAX_PATH + 40;
FilePath long_path = temp_dir_.GetPath();
while (long_path.value().length() <= kLengthLimit) {
long_path = long_path.Append(FPL("to_base_b"));
const auto path_with_no_check = kPathPrefix + long_path.value();
ASSERT_TRUE(::CreateDirectoryW(path_with_no_check.c_str(), nullptr));
}
auto path_with_no_check = kPathPrefix + long_path.value();
long_path = FilePath(path_with_no_check);
FilePath normalized_path;
ASSERT_FALSE(NormalizeFilePath(long_path, &normalized_path));
}
TEST_F(FileUtilTest, NormalizeFilePathWithNetworkPath) {
FilePath temp_path = temp_dir_.GetPath();
const std::string kTestData("The quick brown fox jumps over the lazy dog.");
const FilePath::StringType kTestFileName = FPL("NetworkPathTest");
FilePath file_path = temp_path.Append(kTestFileName);
ASSERT_TRUE(WriteFile(file_path, kTestData));
base::FilePath::CharType drive_letter =
base::ToLowerASCII(temp_path.value().at(0));
EXPECT_GE(drive_letter, 'a');
EXPECT_LE(drive_letter, 'z');
EXPECT_EQ(temp_path.value().at(1), ':');
EXPECT_EQ(temp_path.value().at(2), '\\');
base::FilePath temp_path_network(
base::FilePath::StringType(FPL("\\\\localhost\\")) + drive_letter +
FPL("$\\") + temp_path.value().substr(3));
EXPECT_LT(temp_path_network.value().length(), MAX_PATH);
FilePath normalized_path;
ASSERT_TRUE(NormalizeFilePath(temp_path_network, &normalized_path));
EXPECT_FALSE(normalized_path.empty());
EXPECT_TRUE(PathExists(normalized_path));
std::string read_data;
ASSERT_TRUE(
ReadFileToString(normalized_path.Append(kTestFileName), &read_data));
EXPECT_EQ(kTestData, read_data);
}
TEST_F(FileUtilTest, RemoveWindowsExtendedPathPrefix) {
EXPECT_EQ(
FilePath(FPL(R"(C:\path\to\file)")),
RemoveWindowsExtendedPathPrefixForTesting(LR"(\\?\C:\path\to\file)"));
EXPECT_EQ(FilePath(FPL(R"(\\server\share\path)")),
RemoveWindowsExtendedPathPrefixForTesting(
LR"(\\?\UNC\server\share\path)"));
EXPECT_TRUE(
RemoveWindowsExtendedPathPrefixForTesting(LR"(\\.\pipe\test_pipe)")
.empty());
}
class FileUtilFuzzTest {
public:
FileUtilFuzzTest() {
logging::SetMinLogLevel(logging::LOGGING_ERROR);
}
void RemoveWindowsExtendedPathPrefixNoCrash(const std::wstring& input) {
RemoveWindowsExtendedPathPrefixForTesting(input);
}
private:
logging::ScopedLoggingSettings scoped_logging_settings_;
};
FUZZ_TEST_F(FileUtilFuzzTest, RemoveWindowsExtendedPathPrefixNoCrash)
.WithSeeds({
LR"(\\?\C:\path\to\file)",
LR"(\\?\UNC\server\share\path)",
LR"(\\.\pipe\test_pipe)",
});
TEST_F(FileUtilTest, DevicePathToDriveLetter) {
std::wstring real_drive_letter = AsWString(
ToUpperASCII(AsStringPiece16(temp_dir_.GetPath().value().substr(0, 2))));
if (!IsAsciiAlpha(real_drive_letter[0]) || ':' != real_drive_letter[1]) {
LOG(ERROR) << "Can't get a drive letter to test with.";
return;
}
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;
ASSERT_TRUE(DevicePathToDriveLetterPath(actual_device_path, &win32_path));
ASSERT_EQ(real_drive_letter, win32_path.value());
FilePath kRelativePath(FPL("dir1\\dir2\\file.txt"));
ASSERT_TRUE(DevicePathToDriveLetterPath(
actual_device_path.Append(kRelativePath), &win32_path));
EXPECT_EQ(FilePath(real_drive_letter + FILE_PATH_LITERAL("\\"))
.Append(kRelativePath)
.value(),
win32_path.value());
size_t path_length = actual_device_path.value().length();
size_t new_length = path_length - 4;
ASSERT_GT(new_length, 0u);
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));
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, AreShortFilePathsEnabled) {
constexpr FilePath::CharType kLongDirName[] = FPL("A long path");
FilePath long_test_dir = temp_dir_.GetPath().Append(kLongDirName);
ASSERT_TRUE(CreateDirectory(long_test_dir));
FilePath short_test_dir = MakeShortFilePath(long_test_dir);
ASSERT_EQ(AreShortFilePathsEnabled(), short_test_dir != long_test_dir);
}
TEST_F(FileUtilTest, CreateTemporaryFileInDirLongPathTest) {
if (!AreShortFilePathsEnabled()) {
GTEST_SKIP() << "Short filepaths are not supported on this system.";
}
constexpr FilePath::CharType kLongDirName[] = FPL("A long path");
constexpr FilePath::CharType kTestSubDirName[] = FPL("test");
FilePath long_test_dir = temp_dir_.GetPath().Append(kLongDirName);
ASSERT_TRUE(CreateDirectory(long_test_dir));
FilePath short_test_dir = MakeShortFilePath(long_test_dir);
ASSERT_FALSE(short_test_dir.empty());
ASSERT_NE(kLongDirName, short_test_dir.BaseName().value());
FilePath temp_file;
ASSERT_TRUE(CreateTemporaryFileInDir(short_test_dir, &temp_file));
EXPECT_EQ(kLongDirName, temp_file.DirName().BaseName().value());
EXPECT_TRUE(PathExists(temp_file));
FilePath access_test_dir = long_test_dir.Append(kTestSubDirName);
ASSERT_TRUE(CreateDirectory(access_test_dir));
FilePermissionRestorer long_test_dir_restorer(long_test_dir);
ASSERT_TRUE(MakeFileUnreadable(long_test_dir));
ASSERT_TRUE(CreateTemporaryFileInDir(short_test_dir.Append(kTestSubDirName),
&temp_file));
EXPECT_TRUE(PathExists(temp_file));
EXPECT_TRUE(short_test_dir.IsParent(temp_file.DirName()));
FilePath temp_file_long = MakeLongFilePath(temp_file);
ASSERT_TRUE(temp_file_long.empty());
}
TEST_F(FileUtilTest, MakeLongFilePathTest) {
if (!AreShortFilePathsEnabled()) {
GTEST_SKIP() << "Short filepaths are not supported on this system.";
}
FilePath temp_dir_long = MakeLongFilePath(temp_dir_.GetPath());
ASSERT_FALSE(temp_dir_long.empty());
FilePath long_test_dir = temp_dir_long.Append(FPL("A long directory name"));
ASSERT_TRUE(CreateDirectory(long_test_dir));
FilePath short_test_dir = MakeShortFilePath(long_test_dir);
ASSERT_FALSE(short_test_dir.empty());
EXPECT_NE(long_test_dir, short_test_dir);
EXPECT_EQ(long_test_dir, MakeLongFilePath(short_test_dir));
FilePath long_test_file = long_test_dir.Append(FPL("A long file name.1234"));
CreateTextFile(long_test_file, bogus_content);
ASSERT_TRUE(PathExists(long_test_file));
FilePath short_test_file = MakeShortFilePath(long_test_file);
ASSERT_FALSE(short_test_file.empty());
EXPECT_NE(long_test_file, short_test_file);
EXPECT_EQ(long_test_file, MakeLongFilePath(short_test_file));
EXPECT_TRUE(DeleteFile(short_test_file));
EXPECT_TRUE(MakeLongFilePath(short_test_file).empty());
EXPECT_TRUE(DeleteFile(short_test_dir));
EXPECT_TRUE(MakeLongFilePath(short_test_dir).empty());
}
TEST_F(FileUtilTest, CreateWinHardlinkTest) {
FilePath test_dir = temp_dir_.GetPath().Append(FPL("test"));
ASSERT_TRUE(CreateDirectory(test_dir));
FilePath temp_file;
ASSERT_TRUE(CreateTemporaryFileInDir(temp_dir_.GetPath(), &temp_file));
FilePath link_to_file = test_dir.Append(FPL("linked_name"));
EXPECT_TRUE(CreateWinHardLink(link_to_file, temp_file));
EXPECT_TRUE(PathExists(link_to_file));
EXPECT_FALSE(CreateWinHardLink(temp_dir_.GetPath(), test_dir));
}
TEST_F(FileUtilTest, PreventExecuteMappingNewFile) {
FilePath file = temp_dir_.GetPath().Append(FPL("afile.txt"));
ASSERT_FALSE(PathExists(file));
{
File new_file(file, File::FLAG_WRITE | File::FLAG_WIN_NO_EXECUTE |
File::FLAG_CREATE_ALWAYS);
ASSERT_TRUE(new_file.IsValid());
}
{
File open_file(file, File::FLAG_READ | File::FLAG_WIN_EXECUTE |
File::FLAG_OPEN_ALWAYS);
EXPECT_FALSE(open_file.IsValid());
}
EXPECT_TRUE(DeleteFile(file));
}
TEST_F(FileUtilTest, PreventExecuteMappingExisting) {
FilePath file = temp_dir_.GetPath().Append(FPL("afile.txt"));
CreateTextFile(file, bogus_content);
ASSERT_TRUE(PathExists(file));
{
File open_file(file, File::FLAG_READ | File::FLAG_WIN_EXECUTE |
File::FLAG_OPEN_ALWAYS);
EXPECT_TRUE(open_file.IsValid());
}
EXPECT_TRUE(PreventExecuteMapping(file));
{
File open_file(file, File::FLAG_READ | File::FLAG_WIN_EXECUTE |
File::FLAG_OPEN_ALWAYS);
EXPECT_FALSE(open_file.IsValid());
}
EXPECT_TRUE(DeleteFile(file));
}
TEST_F(FileUtilTest, PreventExecuteMappingOpenFile) {
FilePath file = temp_dir_.GetPath().Append(FPL("afile.txt"));
CreateTextFile(file, bogus_content);
ASSERT_TRUE(PathExists(file));
File open_file(file, File::FLAG_READ | File::FLAG_WRITE |
File::FLAG_WIN_EXECUTE | File::FLAG_OPEN_ALWAYS);
EXPECT_TRUE(open_file.IsValid());
EXPECT_TRUE(PreventExecuteMapping(file));
{
File second_open_file(
file, File::FLAG_READ | File::FLAG_WRITE | File::FLAG_OPEN_ALWAYS);
EXPECT_TRUE(second_open_file.IsValid());
}
{
File third_open_file(file, File::FLAG_READ | File::FLAG_WIN_EXECUTE |
File::FLAG_OPEN_ALWAYS);
EXPECT_FALSE(third_open_file.IsValid());
}
open_file.Close();
EXPECT_TRUE(DeleteFile(file));
}
TEST(FileUtilDeathTest, DisallowNoExecuteOnUnsafeFile) {
base::FilePath local_app_data;
ASSERT_TRUE(
base::PathService::Get(base::DIR_LOCAL_APP_DATA, &local_app_data));
base::FilePath file_path;
EXPECT_DCHECK_DEATH_WITH(
{
{
base::File temp_file =
base::CreateAndOpenTemporaryFileInDir(local_app_data, &file_path);
}
File reopen_file(file_path, File::FLAG_READ | File::FLAG_WRITE |
File::FLAG_WIN_NO_EXECUTE |
File::FLAG_OPEN_ALWAYS |
File::FLAG_DELETE_ON_CLOSE);
},
"Unsafe to deny execute access to path");
}
MULTIPROCESS_TEST_MAIN(NoExecuteOnSafeFileMain) {
base::FilePath temp_file;
CHECK(base::CreateTemporaryFile(&temp_file));
File reopen_file(temp_file, File::FLAG_READ | File::FLAG_WRITE |
File::FLAG_WIN_NO_EXECUTE |
File::FLAG_OPEN_ALWAYS |
File::FLAG_DELETE_ON_CLOSE);
return 0;
}
TEST_F(FileUtilTest, NoExecuteOnSafeFile) {
FilePath new_dir;
ASSERT_TRUE(CreateTemporaryDirInDir(
temp_dir_.GetPath(), FILE_PATH_LITERAL("NoExecuteOnSafeFileLongPath"),
&new_dir));
FilePath short_dir = base::MakeShortFilePath(new_dir);
LaunchOptions options;
options.environment[L"TMP"] = short_dir.value();
CommandLine child_command_line(GetMultiProcessTestChildBaseCommandLine());
Process child_process = SpawnMultiProcessTestChild(
"NoExecuteOnSafeFileMain", child_command_line, options);
ASSERT_TRUE(child_process.IsValid());
int rv = -1;
ASSERT_TRUE(WaitForMultiprocessTestChildExit(
child_process, TestTimeouts::action_timeout(), &rv));
ASSERT_EQ(0, rv);
}
TEST_F(FileUtilTest, ExecuteEnforcement) {
FilePath dir_exe;
EXPECT_TRUE(PathService::Get(DIR_EXE, &dir_exe));
FilePath test_dll(dir_exe.Append(FPL("scoped_handle_test_dll.dll")));
EXPECT_TRUE(base::PathExists(test_dll));
FilePath dll_copy_path = temp_dir_.GetPath().Append(FPL("test.dll"));
ASSERT_TRUE(CopyFile(test_dll, dll_copy_path));
ASSERT_TRUE(PreventExecuteMapping(dll_copy_path));
ScopedNativeLibrary module(dll_copy_path);
EXPECT_FALSE(module.is_valid());
}
#endif
#if BUILDFLAG(IS_POSIX)
TEST_F(FileUtilTest, CreateAndReadSymlinks) {
FilePath link_from = temp_dir_.GetPath().Append(FPL("from_file"));
FilePath link_to = temp_dir_.GetPath().Append(FPL("to_file"));
CreateTextFile(link_to, bogus_content);
ASSERT_TRUE(CreateSymbolicLink(link_to, link_from))
<< "Failed to create file symlink.";
EXPECT_EQ(bogus_content, ReadTextFile(link_from));
FilePath result;
ASSERT_TRUE(ReadSymbolicLink(link_from, &result));
EXPECT_EQ(link_to.value(), result.value());
link_from = temp_dir_.GetPath().Append(FPL("from_dir"));
link_to = temp_dir_.GetPath().Append(FPL("to_dir"));
ASSERT_TRUE(CreateDirectory(link_to));
ASSERT_TRUE(CreateSymbolicLink(link_to, link_from))
<< "Failed to create directory symlink.";
EXPECT_FALSE(CreateSymbolicLink(link_to, link_to));
EXPECT_FALSE(ReadSymbolicLink(link_to, &result));
FilePath missing = temp_dir_.GetPath().Append(FPL("missing"));
EXPECT_FALSE(ReadSymbolicLink(missing, &result));
}
TEST_F(FileUtilTest, CreateAndReadRelativeSymlinks) {
FilePath link_from = temp_dir_.GetPath().Append(FPL("from_file"));
FilePath filename_link_to("to_file");
FilePath link_to = temp_dir_.GetPath().Append(filename_link_to);
FilePath link_from_in_subdir =
temp_dir_.GetPath().Append(FPL("subdir")).Append(FPL("from_file"));
FilePath link_to_in_subdir = FilePath(FPL("..")).Append(filename_link_to);
CreateTextFile(link_to, bogus_content);
ASSERT_TRUE(CreateDirectory(link_from_in_subdir.DirName()));
ASSERT_TRUE(CreateSymbolicLink(link_to_in_subdir, link_from_in_subdir));
ASSERT_TRUE(CreateSymbolicLink(filename_link_to, link_from))
<< "Failed to create file symlink.";
EXPECT_EQ(bogus_content, ReadTextFile(link_from));
EXPECT_EQ(bogus_content, ReadTextFile(link_from_in_subdir));
FilePath result;
ASSERT_TRUE(ReadSymbolicLink(link_from, &result));
EXPECT_EQ(filename_link_to.value(), result.value());
std::optional<FilePath> absolute_link = ReadSymbolicLinkAbsolute(link_from);
ASSERT_TRUE(absolute_link);
EXPECT_EQ(link_to.value(), absolute_link->value());
absolute_link = ReadSymbolicLinkAbsolute(link_from_in_subdir);
ASSERT_TRUE(absolute_link);
EXPECT_EQ(link_to.value(), absolute_link->value());
link_from = temp_dir_.GetPath().Append(FPL("from_dir"));
filename_link_to = FilePath("to_dir");
link_to = temp_dir_.GetPath().Append(filename_link_to);
ASSERT_TRUE(CreateDirectory(link_to));
ASSERT_TRUE(CreateSymbolicLink(filename_link_to, link_from))
<< "Failed to create relative directory symlink.";
ASSERT_TRUE(ReadSymbolicLink(link_from, &result));
EXPECT_EQ(filename_link_to.value(), result.value());
absolute_link = ReadSymbolicLinkAbsolute(link_from);
ASSERT_TRUE(absolute_link);
EXPECT_EQ(link_to.value(), absolute_link->value());
EXPECT_FALSE(CreateSymbolicLink(link_to, link_to));
EXPECT_FALSE(ReadSymbolicLink(link_to, &result));
}
TEST_F(FileUtilTest, NormalizeFilePathSymlinks) {
FilePath link_from = temp_dir_.GetPath().Append(FPL("from_file"));
FilePath link_to = temp_dir_.GetPath().Append(FPL("to_file"));
CreateTextFile(link_to, bogus_content);
ASSERT_TRUE(CreateSymbolicLink(link_to, link_from))
<< "Failed to create file symlink.";
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_from = temp_dir_.GetPath().Append(FPL("from_dir"));
link_to = temp_dir_.GetPath().Append(FPL("to_dir"));
ASSERT_TRUE(CreateDirectory(link_to));
ASSERT_TRUE(CreateSymbolicLink(link_to, link_from))
<< "Failed to create directory symlink.";
EXPECT_TRUE(NormalizeFilePath(link_from, &normalized_path))
<< "Links to directories should return true.";
link_from = temp_dir_.GetPath().Append(FPL("link_a"));
link_to = temp_dir_.GetPath().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.";
EXPECT_FALSE(NormalizeFilePath(link_from, &normalized_path));
}
TEST_F(FileUtilTest, DeleteSymlinkToExistentFile) {
FilePath file_name = temp_dir_.GetPath().Append(FPL("Test DeleteFile 2.txt"));
CreateTextFile(file_name, bogus_content);
ASSERT_TRUE(PathExists(file_name));
FilePath file_link = temp_dir_.GetPath().Append("file_link_2");
ASSERT_TRUE(CreateSymbolicLink(file_name, file_link))
<< "Failed to create symlink.";
EXPECT_TRUE(DeleteFile(file_link));
EXPECT_FALSE(PathExists(file_link));
EXPECT_TRUE(PathExists(file_name));
}
TEST_F(FileUtilTest, DeleteSymlinkToNonExistentFile) {
FilePath non_existent =
temp_dir_.GetPath().Append(FPL("Test DeleteFile 3.txt"));
EXPECT_FALSE(PathExists(non_existent));
FilePath file_link = temp_dir_.GetPath().Append("file_link_3");
ASSERT_TRUE(CreateSymbolicLink(non_existent, file_link))
<< "Failed to create symlink.";
EXPECT_TRUE(IsLink(file_link));
EXPECT_FALSE(PathExists(file_link));
EXPECT_TRUE(DeleteFile(file_link));
EXPECT_FALSE(IsLink(file_link));
}
TEST_F(FileUtilTest, CopyFileFollowsSymlinks) {
FilePath link_from = temp_dir_.GetPath().Append(FPL("from_file"));
FilePath link_to = temp_dir_.GetPath().Append(FPL("to_file"));
CreateTextFile(link_to, bogus_content);
ASSERT_TRUE(CreateSymbolicLink(link_to, link_from));
EXPECT_EQ(bogus_content, ReadTextFile(link_from));
FilePath result;
ASSERT_TRUE(ReadSymbolicLink(link_from, &result));
EXPECT_EQ(link_to.value(), result.value());
FilePath src_file = temp_dir_.GetPath().Append(FPL("src.txt"));
const std::wstring file_contents(L"Gooooooooooooooooooooogle");
CreateTextFile(src_file, file_contents);
ASSERT_TRUE(CopyFile(src_file, link_from));
EXPECT_TRUE(IsLink(link_from));
EXPECT_EQ(file_contents, ReadTextFile(link_from));
EXPECT_EQ(file_contents, ReadTextFile(link_to));
}
TEST_F(FileUtilTest, ChangeFilePermissionsAndRead) {
FilePath file_name =
temp_dir_.GetPath().Append(FPL("Test Readable File.txt"));
EXPECT_FALSE(PathExists(file_name));
EXPECT_FALSE(PathIsReadable(file_name));
static constexpr char kData[] = "hello";
static constexpr int kDataSize = sizeof(kData) - 1;
char buffer[kDataSize];
EXPECT_TRUE(WriteFile(file_name, kData));
EXPECT_TRUE(PathExists(file_name));
int32_t mode = 0;
EXPECT_TRUE(GetPosixFilePermissions(file_name, &mode));
EXPECT_TRUE(mode & FILE_PERMISSION_READ_BY_USER);
EXPECT_TRUE(PathIsReadable(file_name));
EXPECT_TRUE(SetPosixFilePermissions(file_name, 0u));
EXPECT_TRUE(GetPosixFilePermissions(file_name, &mode));
EXPECT_FALSE(mode & FILE_PERMISSION_READ_BY_USER);
EXPECT_FALSE(PathIsReadable(file_name));
EXPECT_EQ(ReadFile(file_name, buffer), std::nullopt);
EXPECT_TRUE(SetPosixFilePermissions(file_name, FILE_PERMISSION_READ_BY_USER));
EXPECT_TRUE(GetPosixFilePermissions(file_name, &mode));
EXPECT_TRUE(mode & FILE_PERMISSION_READ_BY_USER);
EXPECT_TRUE(PathIsReadable(file_name));
EXPECT_EQ(ReadFile(file_name, buffer), kDataSize);
EXPECT_TRUE(DeleteFile(file_name));
EXPECT_FALSE(PathExists(file_name));
}
TEST_F(FileUtilTest, ChangeFilePermissionsAndWrite) {
FilePath file_name =
temp_dir_.GetPath().Append(FPL("Test Readable File.txt"));
EXPECT_FALSE(PathExists(file_name));
const std::string kData("hello");
EXPECT_TRUE(WriteFile(file_name, kData));
EXPECT_TRUE(PathExists(file_name));
int mode = 0;
EXPECT_TRUE(GetPosixFilePermissions(file_name, &mode));
EXPECT_TRUE(mode & FILE_PERMISSION_WRITE_BY_USER);
EXPECT_TRUE(PathIsWritable(file_name));
EXPECT_TRUE(SetPosixFilePermissions(file_name, 0u));
EXPECT_TRUE(GetPosixFilePermissions(file_name, &mode));
EXPECT_FALSE(mode & FILE_PERMISSION_WRITE_BY_USER);
EXPECT_FALSE(WriteFile(file_name, kData));
EXPECT_FALSE(PathIsWritable(file_name));
EXPECT_TRUE(
SetPosixFilePermissions(file_name, FILE_PERMISSION_WRITE_BY_USER));
EXPECT_TRUE(GetPosixFilePermissions(file_name, &mode));
EXPECT_TRUE(mode & FILE_PERMISSION_WRITE_BY_USER);
EXPECT_TRUE(WriteFile(file_name, kData));
EXPECT_TRUE(PathIsWritable(file_name));
EXPECT_TRUE(DeleteFile(file_name));
EXPECT_FALSE(PathExists(file_name));
}
TEST_F(FileUtilTest, ChangeDirectoryPermissionsAndEnumerate) {
FilePath subdir_path = temp_dir_.GetPath().Append(FPL("PermissionTest1"));
CreateDirectory(subdir_path);
ASSERT_TRUE(PathExists(subdir_path));
FilePath file_name = subdir_path.Append(FPL("Test Readable File.txt"));
EXPECT_FALSE(PathExists(file_name));
const std::string kData("hello");
EXPECT_TRUE(WriteFile(file_name, kData));
EXPECT_TRUE(PathExists(file_name));
int mode = 0;
EXPECT_TRUE(GetPosixFilePermissions(subdir_path, &mode));
EXPECT_EQ(FILE_PERMISSION_USER_MASK, mode & FILE_PERMISSION_USER_MASK);
EXPECT_TRUE(SetPosixFilePermissions(subdir_path, 0u));
EXPECT_TRUE(GetPosixFilePermissions(subdir_path, &mode));
EXPECT_FALSE(mode & FILE_PERMISSION_USER_MASK);
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));
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);
FileEnumerator f2(subdir_path, true, FileEnumerator::FILES);
FindResultCollector c2(&f2);
EXPECT_TRUE(c2.HasFile(file_name));
EXPECT_EQ(1, c2.size());
EXPECT_TRUE(DeletePathRecursively(subdir_path));
EXPECT_FALSE(PathExists(subdir_path));
}
TEST_F(FileUtilTest, ExecutableExistsInPath) {
const FilePath::CharType kDir1[] = FPL("dir1");
const FilePath::CharType kDir2[] = FPL("dir2");
FilePath dir1 = temp_dir_.GetPath().Append(kDir1);
FilePath dir2 = temp_dir_.GetPath().Append(kDir2);
ASSERT_TRUE(CreateDirectory(dir1));
ASSERT_TRUE(CreateDirectory(dir2));
ScopedEnvironmentVariableOverride scoped_env(
"PATH", dir1.value() + ":" + dir2.value());
ASSERT_TRUE(scoped_env.IsOverridden());
const FilePath::CharType kRegularFileName[] = FPL("regular_file");
const FilePath::CharType kExeFileName[] = FPL("exe");
const FilePath::CharType kDneFileName[] = FPL("does_not_exist");
const FilePath kExePath = dir1.Append(kExeFileName);
const FilePath kRegularFilePath = dir2.Append(kRegularFileName);
const std::string kData("hello");
ASSERT_TRUE(WriteFile(kExePath, kData));
ASSERT_TRUE(PathExists(kExePath));
ASSERT_TRUE(WriteFile(kRegularFilePath, kData));
ASSERT_TRUE(PathExists(kRegularFilePath));
ASSERT_TRUE(SetPosixFilePermissions(dir1.Append(kExeFileName),
FILE_PERMISSION_EXECUTE_BY_USER));
EXPECT_TRUE(ExecutableExistsInPath(scoped_env.GetEnv(), kExeFileName));
EXPECT_FALSE(ExecutableExistsInPath(scoped_env.GetEnv(), kRegularFileName));
EXPECT_FALSE(ExecutableExistsInPath(scoped_env.GetEnv(), kDneFileName));
}
TEST_F(FileUtilTest, CopyDirectoryPermissions) {
FilePath dir_name_from =
temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
CreateDirectory(dir_name_from);
ASSERT_TRUE(PathExists(dir_name_from));
FilePath file_name_from =
dir_name_from.Append(FILE_PATH_LITERAL("Reggy-1.txt"));
CreateTextFile(file_name_from, L"Mordecai");
ASSERT_TRUE(PathExists(file_name_from));
ASSERT_TRUE(SetPosixFilePermissions(file_name_from, 0755));
FilePath file2_name_from =
dir_name_from.Append(FILE_PATH_LITERAL("Reggy-2.txt"));
CreateTextFile(file2_name_from, L"Rigby");
ASSERT_TRUE(PathExists(file2_name_from));
ASSERT_TRUE(SetPosixFilePermissions(file2_name_from, 0777));
FilePath file3_name_from =
dir_name_from.Append(FILE_PATH_LITERAL("Reggy-3.txt"));
CreateTextFile(file3_name_from, L"Benson");
ASSERT_TRUE(PathExists(file3_name_from));
ASSERT_TRUE(SetPosixFilePermissions(file3_name_from, 0400));
FilePath dir_name_to =
temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_To_Subdir"));
FilePath file_name_to = dir_name_to.Append(FILE_PATH_LITERAL("Reggy-1.txt"));
FilePath file2_name_to = dir_name_to.Append(FILE_PATH_LITERAL("Reggy-2.txt"));
FilePath file3_name_to = dir_name_to.Append(FILE_PATH_LITERAL("Reggy-3.txt"));
ASSERT_FALSE(PathExists(dir_name_to));
EXPECT_TRUE(CopyDirectory(dir_name_from, dir_name_to, true));
ASSERT_TRUE(PathExists(file_name_to));
ASSERT_TRUE(PathExists(file2_name_to));
ASSERT_TRUE(PathExists(file3_name_to));
int mode = 0;
int expected_mode;
ASSERT_TRUE(GetPosixFilePermissions(file_name_to, &mode));
#if BUILDFLAG(IS_APPLE)
expected_mode = 0755;
#elif BUILDFLAG(IS_CHROMEOS)
expected_mode = 0644;
#else
expected_mode = 0600;
#endif
EXPECT_EQ(expected_mode, mode);
ASSERT_TRUE(GetPosixFilePermissions(file2_name_to, &mode));
#if BUILDFLAG(IS_APPLE)
expected_mode = 0755;
#elif BUILDFLAG(IS_CHROMEOS)
expected_mode = 0644;
#else
expected_mode = 0600;
#endif
EXPECT_EQ(expected_mode, mode);
ASSERT_TRUE(GetPosixFilePermissions(file3_name_to, &mode));
#if BUILDFLAG(IS_APPLE)
expected_mode = 0600;
#elif BUILDFLAG(IS_CHROMEOS)
expected_mode = 0644;
#else
expected_mode = 0600;
#endif
EXPECT_EQ(expected_mode, mode);
}
TEST_F(FileUtilTest, CopyDirectoryPermissionsOverExistingFile) {
FilePath dir_name_from =
temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
CreateDirectory(dir_name_from);
ASSERT_TRUE(PathExists(dir_name_from));
FilePath file_name_from =
dir_name_from.Append(FILE_PATH_LITERAL("Reggy-1.txt"));
CreateTextFile(file_name_from, L"Mordecai");
ASSERT_TRUE(PathExists(file_name_from));
ASSERT_TRUE(SetPosixFilePermissions(file_name_from, 0644));
FilePath dir_name_to =
temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_To_Subdir"));
CreateDirectory(dir_name_to);
ASSERT_TRUE(PathExists(dir_name_to));
FilePath file_name_to = dir_name_to.Append(FILE_PATH_LITERAL("Reggy-1.txt"));
CreateTextFile(file_name_to, L"Rigby");
ASSERT_TRUE(PathExists(file_name_to));
ASSERT_TRUE(SetPosixFilePermissions(file_name_to, 0777));
EXPECT_TRUE(CopyDirectory(dir_name_from, dir_name_to, false));
ASSERT_TRUE(PathExists(file_name_to));
ASSERT_EQ(L"Mordecai", ReadTextFile(file_name_to));
int mode = 0;
ASSERT_TRUE(GetPosixFilePermissions(file_name_to, &mode));
EXPECT_EQ(0777, mode);
}
TEST_F(FileUtilTest, CopyDirectoryExclDoesNotOverwrite) {
FilePath dir_name_from =
temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
CreateDirectory(dir_name_from);
ASSERT_TRUE(PathExists(dir_name_from));
FilePath file_name_from =
dir_name_from.Append(FILE_PATH_LITERAL("Reggy-1.txt"));
CreateTextFile(file_name_from, L"Mordecai");
ASSERT_TRUE(PathExists(file_name_from));
FilePath dir_name_to =
temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_To_Subdir"));
CreateDirectory(dir_name_to);
ASSERT_TRUE(PathExists(dir_name_to));
FilePath file_name_to = dir_name_to.Append(FILE_PATH_LITERAL("Reggy-1.txt"));
CreateTextFile(file_name_to, L"Rigby");
ASSERT_TRUE(PathExists(file_name_to));
EXPECT_FALSE(CopyDirectoryExcl(dir_name_from, dir_name_to, false));
ASSERT_TRUE(PathExists(file_name_to));
ASSERT_EQ(L"Rigby", ReadTextFile(file_name_to));
}
TEST_F(FileUtilTest, CopyDirectoryExclDirectoryOverExistingFile) {
FilePath dir_name_from =
temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
CreateDirectory(dir_name_from);
ASSERT_TRUE(PathExists(dir_name_from));
FilePath subdir_name_from = dir_name_from.Append(FILE_PATH_LITERAL("Subsub"));
CreateDirectory(subdir_name_from);
ASSERT_TRUE(PathExists(subdir_name_from));
FilePath dir_name_to =
temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_To_Subdir"));
CreateDirectory(dir_name_to);
ASSERT_TRUE(PathExists(dir_name_to));
FilePath file_name_to = dir_name_to.Append(FILE_PATH_LITERAL("Subsub"));
CreateTextFile(file_name_to, L"Rigby");
ASSERT_TRUE(PathExists(file_name_to));
EXPECT_FALSE(CopyDirectoryExcl(dir_name_from, dir_name_to, false));
ASSERT_TRUE(PathExists(file_name_to));
ASSERT_EQ(L"Rigby", ReadTextFile(file_name_to));
}
TEST_F(FileUtilTest, CopyDirectoryExclDirectoryOverExistingDirectory) {
FilePath dir_name_from =
temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
CreateDirectory(dir_name_from);
ASSERT_TRUE(PathExists(dir_name_from));
FilePath subdir_name_from = dir_name_from.Append(FILE_PATH_LITERAL("Subsub"));
CreateDirectory(subdir_name_from);
ASSERT_TRUE(PathExists(subdir_name_from));
FilePath dir_name_to =
temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_To_Subdir"));
CreateDirectory(dir_name_to);
ASSERT_TRUE(PathExists(dir_name_to));
FilePath subdir_name_to = dir_name_to.Append(FILE_PATH_LITERAL("Subsub"));
CreateDirectory(subdir_name_to);
ASSERT_TRUE(PathExists(subdir_name_to));
EXPECT_FALSE(CopyDirectoryExcl(dir_name_from, dir_name_to, false));
}
TEST_F(FileUtilTest, CopyFileExecutablePermission) {
FilePath src = temp_dir_.GetPath().Append(FPL("src.txt"));
const std::wstring file_contents(L"Gooooooooooooooooooooogle");
CreateTextFile(src, file_contents);
ASSERT_TRUE(SetPosixFilePermissions(src, 0755));
int mode = 0;
ASSERT_TRUE(GetPosixFilePermissions(src, &mode));
EXPECT_EQ(0755, mode);
FilePath dst = temp_dir_.GetPath().Append(FPL("dst.txt"));
ASSERT_TRUE(CopyFile(src, dst));
EXPECT_EQ(file_contents, ReadTextFile(dst));
ASSERT_TRUE(GetPosixFilePermissions(dst, &mode));
int expected_mode;
#if BUILDFLAG(IS_APPLE)
expected_mode = 0755;
#elif BUILDFLAG(IS_CHROMEOS)
expected_mode = 0644;
#else
expected_mode = 0600;
#endif
EXPECT_EQ(expected_mode, mode);
ASSERT_TRUE(DeleteFile(dst));
ASSERT_TRUE(SetPosixFilePermissions(src, 0777));
ASSERT_TRUE(GetPosixFilePermissions(src, &mode));
EXPECT_EQ(0777, mode);
ASSERT_TRUE(CopyFile(src, dst));
EXPECT_EQ(file_contents, ReadTextFile(dst));
ASSERT_TRUE(GetPosixFilePermissions(dst, &mode));
#if BUILDFLAG(IS_APPLE)
expected_mode = 0755;
#elif BUILDFLAG(IS_CHROMEOS)
expected_mode = 0644;
#else
expected_mode = 0600;
#endif
EXPECT_EQ(expected_mode, mode);
ASSERT_TRUE(DeleteFile(dst));
ASSERT_TRUE(SetPosixFilePermissions(src, 0400));
ASSERT_TRUE(GetPosixFilePermissions(src, &mode));
EXPECT_EQ(0400, mode);
ASSERT_TRUE(CopyFile(src, dst));
EXPECT_EQ(file_contents, ReadTextFile(dst));
ASSERT_TRUE(GetPosixFilePermissions(dst, &mode));
#if BUILDFLAG(IS_APPLE)
expected_mode = 0600;
#elif BUILDFLAG(IS_CHROMEOS)
expected_mode = 0644;
#else
expected_mode = 0600;
#endif
EXPECT_EQ(expected_mode, mode);
ASSERT_TRUE(SetPosixFilePermissions(dst, 0777));
ASSERT_TRUE(GetPosixFilePermissions(dst, &mode));
EXPECT_EQ(0777, mode);
ASSERT_TRUE(CopyFile(src, dst));
EXPECT_EQ(file_contents, ReadTextFile(dst));
ASSERT_TRUE(GetPosixFilePermissions(dst, &mode));
EXPECT_EQ(0777, mode);
}
#endif
#if !BUILDFLAG(IS_FUCHSIA)
TEST_F(FileUtilTest, CopyFileACL) {
FilePath src = temp_dir_.GetPath().Append(FILE_PATH_LITERAL("src.txt"));
const std::wstring file_contents(L"Gooooooooooooooooooooogle");
CreateTextFile(src, file_contents);
ASSERT_FALSE(IsReadOnly(src));
SetReadOnly(src, true);
ASSERT_TRUE(IsReadOnly(src));
FilePath dst = temp_dir_.GetPath().Append(FILE_PATH_LITERAL("dst.txt"));
ASSERT_TRUE(CopyFile(src, dst));
EXPECT_EQ(file_contents, ReadTextFile(dst));
ASSERT_FALSE(IsReadOnly(dst));
}
TEST_F(FileUtilTest, CopyDirectoryACL) {
FilePath src = temp_dir_.GetPath().Append(FILE_PATH_LITERAL("src"));
FilePath src_subdir = src.Append(FILE_PATH_LITERAL("subdir"));
CreateDirectory(src_subdir);
ASSERT_TRUE(PathExists(src_subdir));
FilePath src_file = src.Append(FILE_PATH_LITERAL("src.txt"));
CreateTextFile(src_file, L"Gooooooooooooooooooooogle");
SetReadOnly(src_file, true);
ASSERT_TRUE(IsReadOnly(src_file));
SetReadOnly(src_subdir, true);
ASSERT_TRUE(IsReadOnly(src_subdir));
FilePath dst = temp_dir_.GetPath().Append(FILE_PATH_LITERAL("dst"));
FilePath dst_file = dst.Append(FILE_PATH_LITERAL("src.txt"));
EXPECT_TRUE(CopyDirectory(src, dst, true));
FilePath dst_subdir = dst.Append(FILE_PATH_LITERAL("subdir"));
ASSERT_FALSE(IsReadOnly(dst_subdir));
ASSERT_FALSE(IsReadOnly(dst_file));
SetReadOnly(src_subdir, false);
ASSERT_FALSE(IsReadOnly(src_subdir));
}
#endif
TEST_F(FileUtilTest, DeleteNonExistent) {
FilePath non_existent =
temp_dir_.GetPath().AppendASCII("bogus_file_dne.foobar");
ASSERT_FALSE(PathExists(non_existent));
EXPECT_TRUE(DeleteFile(non_existent));
ASSERT_FALSE(PathExists(non_existent));
EXPECT_TRUE(DeletePathRecursively(non_existent));
ASSERT_FALSE(PathExists(non_existent));
}
TEST_F(FileUtilTest, DeleteNonExistentWithNonExistentParent) {
FilePath non_existent = temp_dir_.GetPath().AppendASCII("bogus_topdir");
non_existent = non_existent.AppendASCII("bogus_subdir");
ASSERT_FALSE(PathExists(non_existent));
EXPECT_TRUE(DeleteFile(non_existent));
ASSERT_FALSE(PathExists(non_existent));
EXPECT_TRUE(DeletePathRecursively(non_existent));
ASSERT_FALSE(PathExists(non_existent));
}
TEST_F(FileUtilTest, DeleteFile) {
FilePath file_name = temp_dir_.GetPath().Append(FPL("Test DeleteFile 1.txt"));
CreateTextFile(file_name, bogus_content);
ASSERT_TRUE(PathExists(file_name));
EXPECT_TRUE(DeleteFile(file_name));
EXPECT_FALSE(PathExists(file_name));
file_name = temp_dir_.GetPath().Append(FPL("Test DeleteFile 2.txt"));
CreateTextFile(file_name, bogus_content);
ASSERT_TRUE(PathExists(file_name));
EXPECT_TRUE(DeletePathRecursively(file_name));
EXPECT_FALSE(PathExists(file_name));
}
#if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
TEST_F(FileUtilTest, DeleteDeep) {
const FilePath dir_path = temp_dir_.GetPath().AppendASCII("deep");
ASSERT_EQ(mkdir(dir_path.value().c_str(), 0777), 0);
{
ScopedFD fd(
HANDLE_EINTR(open(dir_path.value().c_str(), O_DIRECTORY | O_CLOEXEC)));
ASSERT_TRUE(fd.is_valid()) << strerror(errno);
for (char c = 'a'; c <= 'z'; ++c) {
const std::string name(NAME_MAX, c);
ASSERT_EQ(HANDLE_EINTR(mkdirat(fd.get(), name.c_str(), 0777)), 0)
<< strerror(errno);
fd = ScopedFD(HANDLE_EINTR(
openat(fd.get(), name.c_str(), O_DIRECTORY | O_CLOEXEC)));
ASSERT_TRUE(fd.is_valid()) << strerror(errno);
}
#if !BUILDFLAG(IS_FUCHSIA)
ASSERT_EQ(HANDLE_EINTR(symlinkat("..", fd.get(), "up")), 0)
<< strerror(errno);
#endif
fd = ScopedFD(HANDLE_EINTR(openat(
fd.get(), "file.txt", O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, 0666)));
ASSERT_TRUE(fd.is_valid()) << strerror(errno);
const std::string_view s = "This is a deep file";
ASSERT_EQ(HANDLE_EINTR(write(fd.get(), s.data(), s.size())),
static_cast<ssize_t>(s.size()));
}
EXPECT_TRUE(PathExists(dir_path));
EXPECT_TRUE(DeletePathRecursively(dir_path));
EXPECT_FALSE(PathExists(dir_path));
}
#endif
#if BUILDFLAG(IS_ANDROID)
TEST_F(FileUtilTest, ContentUriPathExists) {
FilePath dir = temp_dir_.GetPath().Append("dir");
CreateDirectory(dir);
FilePath file = dir.Append("file.txt");
WriteFile(file, "file-content");
FilePath no_such_file = dir.Append("no-such-file.txt");
FilePath content_uri_document_dir =
*test::android::GetInMemoryContentTreeUriFromCacheDirDirectory(dir);
FilePath content_uri_document_file =
*test::android::GetInMemoryContentDocumentUriFromCacheDirFilePath(file);
FilePath content_uri_document_no_such_file =
*test::android::GetInMemoryContentDocumentUriFromCacheDirFilePath(
no_such_file);
FilePath virtual_path_dir =
*test::android::GetVirtualDocumentPathFromCacheDirDirectory(dir);
FilePath virtual_path_file = virtual_path_dir.Append("file.txt");
FilePath virtual_path_no_such_file =
virtual_path_dir.Append("no-such-file.txt");
EXPECT_TRUE(PathExists(content_uri_document_dir));
EXPECT_TRUE(PathExists(content_uri_document_file));
EXPECT_FALSE(PathExists(content_uri_document_no_such_file));
EXPECT_TRUE(PathExists(virtual_path_dir));
EXPECT_TRUE(PathExists(virtual_path_file));
EXPECT_FALSE(PathExists(virtual_path_no_such_file));
}
TEST_F(FileUtilTest, ContentUriGetInfo) {
FilePath file = temp_dir_.GetPath().Append("file.txt");
FilePath dir = temp_dir_.GetPath().Append("dir");
WriteFile(file, "file-content");
CreateDirectory(dir);
FilePath content_uri_file =
*test::android::GetContentUriFromCacheDirFilePath(file);
FilePath content_uri_dir =
*test::android::GetContentUriFromCacheDirFilePath(dir);
FilePath content_uri_file_in_memory =
*test::android::GetInMemoryContentUriFromCacheDirFilePath(file);
FilePath content_uri_dir_in_memory =
*test::android::GetInMemoryContentUriFromCacheDirFilePath(dir);
FilePath content_uri_document =
*test::android::GetInMemoryContentDocumentUriFromCacheDirFilePath(file);
FilePath content_uri_document_tree =
*test::android::GetInMemoryContentTreeUriFromCacheDirDirectory(dir);
File::Info info;
File::Info content_uri_info;
File::Info content_uri_in_memory_info;
File::Info content_uri_document_info;
EXPECT_TRUE(GetFileInfo(file, &info));
EXPECT_TRUE(GetFileInfo(content_uri_file, &content_uri_info));
EXPECT_TRUE(GetFileInfo(content_uri_document, &content_uri_document_info));
EXPECT_TRUE(
GetFileInfo(content_uri_file_in_memory, &content_uri_in_memory_info));
EXPECT_EQ(12u, info.size);
EXPECT_EQ(12u, content_uri_info.size);
EXPECT_EQ(12u, content_uri_in_memory_info.size);
EXPECT_EQ(12u, content_uri_document_info.size);
EXPECT_EQ(info.last_modified, content_uri_info.last_modified);
EXPECT_EQ(content_uri_in_memory_info.last_modified, Time::FromTimeT(0));
EXPECT_EQ(info.last_modified.ToTimeT(),
content_uri_document_info.last_modified.ToTimeT());
EXPECT_FALSE(info.is_directory);
EXPECT_FALSE(content_uri_info.is_directory);
EXPECT_FALSE(content_uri_in_memory_info.is_directory);
EXPECT_FALSE(content_uri_document_info.is_directory);
EXPECT_TRUE(GetFileInfo(dir, &info));
EXPECT_TRUE(GetFileInfo(content_uri_dir, &content_uri_info));
EXPECT_FALSE(
GetFileInfo(content_uri_dir_in_memory, &content_uri_in_memory_info));
File::Info content_uri_tree_info;
EXPECT_TRUE(GetFileInfo(content_uri_document_tree, &content_uri_tree_info));
EXPECT_EQ(info.last_modified, content_uri_info.last_modified);
EXPECT_EQ(info.last_modified.ToTimeT(),
content_uri_tree_info.last_modified.ToTimeT());
EXPECT_TRUE(info.is_directory);
#if BUILDFLAG(IS_WIN)
EXPECT_EQ(info.size, 0u);
#endif
EXPECT_TRUE(content_uri_info.is_directory);
EXPECT_TRUE(content_uri_tree_info.is_directory);
int mode = 0;
EXPECT_TRUE(GetPosixFilePermissions(file, &mode));
EXPECT_TRUE(GetPosixFilePermissions(dir, &mode));
EXPECT_FALSE(GetPosixFilePermissions(content_uri_file, &mode));
EXPECT_FALSE(GetPosixFilePermissions(content_uri_dir, &mode));
}
TEST_F(FileUtilTest, OpenFileContentUri) {
FilePath dir = temp_dir_.GetPath().Append("dir");
CreateDirectory(dir);
FilePath file = dir.Append("file.txt");
WriteFile(file, "abc");
FilePath no_such_file = dir.Append("no-such-file.txt");
FilePath content_uri_document_file =
*test::android::GetInMemoryContentDocumentUriFromCacheDirFilePath(file);
FilePath content_uri_document_no_such_file =
*test::android::GetInMemoryContentDocumentUriFromCacheDirFilePath(
no_such_file);
FilePath virtual_path_dir =
*test::android::GetVirtualDocumentPathFromCacheDirDirectory(dir);
FilePath virtual_path_file = virtual_path_dir.Append("file.txt");
FilePath virtual_path_no_such_file =
virtual_path_dir.Append("no-such-file.txt");
ScopedFILE cu_f(OpenFile(content_uri_document_file, "r"));
std::string cu_s;
EXPECT_TRUE(ReadStreamToStringWithMaxSize(cu_f.get(), 4, &cu_s));
EXPECT_EQ(cu_s, "abc");
EXPECT_FALSE(OpenFile(content_uri_document_no_such_file, "r"));
ScopedFILE vp_f(OpenFile(virtual_path_file, "r"));
std::string vp_s;
EXPECT_TRUE(ReadStreamToStringWithMaxSize(vp_f.get(), 4, &vp_s));
EXPECT_EQ(vp_s, "abc");
EXPECT_FALSE(OpenFile(virtual_path_no_such_file, "r"));
}
TEST_F(FileUtilTest, DeleteContentUri) {
FilePath data_dir;
ASSERT_TRUE(PathService::Get(DIR_TEST_DATA, &data_dir));
data_dir = data_dir.Append(FPL("file_util"));
ASSERT_TRUE(PathExists(data_dir));
FilePath image_file = data_dir.Append(FPL("red.png"));
ASSERT_TRUE(PathExists(image_file));
FilePath image_copy = data_dir.Append(FPL("redcopy.png"));
ASSERT_TRUE(CopyFile(image_file, image_copy));
FilePath uri_path = InsertImageIntoMediaStore(image_copy);
ASSERT_TRUE(uri_path.IsContentUri());
ASSERT_TRUE(PathExists(uri_path));
EXPECT_TRUE(DeleteFile(uri_path));
EXPECT_FALSE(PathExists(image_copy));
EXPECT_FALSE(PathExists(uri_path));
}
TEST_F(FileUtilTest, WriteFileContentUri) {
FilePath dir = temp_dir_.GetPath().Append("dir");
CreateDirectory(dir);
FilePath dir_vp =
*test::android::GetVirtualDocumentPathFromCacheDirDirectory(dir);
FilePath file_vp = dir_vp.Append("file.txt");
ASSERT_TRUE(file_vp.IsVirtualDocumentPath());
ASSERT_FALSE(PathExists(file_vp));
EXPECT_TRUE(WriteFile(file_vp, "x"));
ASSERT_TRUE(PathExists(file_vp));
FilePath file_content_uri = *ResolveToContentUri(file_vp);
EXPECT_TRUE(WriteFile(file_content_uri, "foo"));
File::Info info;
ASSERT_TRUE(GetFileInfo(file_content_uri, &info));
ASSERT_EQ(info.size, 3u);
}
TEST_F(FileUtilTest, ResolveToContentUri) {
FilePath dir = temp_dir_.GetPath().Append("dir");
CreateDirectory(dir);
FilePath file = dir.Append("file.txt");
WriteFile(file, "file-content");
FilePath dir_vp =
*test::android::GetVirtualDocumentPathFromCacheDirDirectory(dir);
FilePath file_vp = dir_vp.Append("file.txt");
ASSERT_TRUE(file_vp.IsVirtualDocumentPath());
FilePath file_content_uri = *ResolveToContentUri(file_vp);
ASSERT_TRUE(file_content_uri.IsContentUri());
File::Info info;
ASSERT_TRUE(GetFileInfo(file_content_uri, &info));
ASSERT_EQ(info.size, 12u);
}
TEST_F(FileUtilTest, ResolveToVirtualDocumentPath) {
FilePath dir = temp_dir_.GetPath().Append("dir");
CreateDirectory(dir);
FilePath file = dir.Append("file.txt");
WriteFile(file, "file-content");
FilePath dir_content_uri =
*test::android::GetInMemoryContentTreeUriFromCacheDirDirectory(dir);
FilePath dir_vp = *ResolveToVirtualDocumentPath(dir_content_uri);
ASSERT_TRUE(dir_vp.IsVirtualDocumentPath());
FilePath file_vp = dir_vp.Append("file.txt");
File::Info info;
ASSERT_TRUE(GetFileInfo(file_vp, &info));
ASSERT_TRUE(!info.is_directory);
}
#endif
#if BUILDFLAG(IS_WIN)
TEST_F(FileUtilTest, DeleteWildCard) {
FilePath file_name =
temp_dir_.GetPath().Append(FPL("Test DeleteWildCard.txt"));
CreateTextFile(file_name, bogus_content);
ASSERT_TRUE(PathExists(file_name));
FilePath subdir_path = temp_dir_.GetPath().Append(FPL("DeleteWildCardDir"));
CreateDirectory(subdir_path);
ASSERT_TRUE(PathExists(subdir_path));
FilePath directory_contents = temp_dir_.GetPath();
directory_contents = directory_contents.Append(FPL("*"));
EXPECT_TRUE(DeleteFile(directory_contents));
EXPECT_FALSE(PathExists(file_name));
EXPECT_TRUE(PathExists(subdir_path));
EXPECT_TRUE(DeletePathRecursively(directory_contents));
EXPECT_FALSE(PathExists(file_name));
EXPECT_FALSE(PathExists(subdir_path));
}
TEST_F(FileUtilTest, DeleteNonExistantWildCard) {
FilePath subdir_path =
temp_dir_.GetPath().Append(FPL("DeleteNonExistantWildCard"));
CreateDirectory(subdir_path);
ASSERT_TRUE(PathExists(subdir_path));
FilePath directory_contents = subdir_path;
directory_contents = directory_contents.Append(FPL("*"));
EXPECT_TRUE(DeleteFile(directory_contents));
EXPECT_TRUE(PathExists(subdir_path));
EXPECT_TRUE(DeletePathRecursively(directory_contents));
EXPECT_TRUE(PathExists(subdir_path));
}
#endif
TEST_F(FileUtilTest, DeleteDirNonRecursive) {
FilePath test_subdir =
temp_dir_.GetPath().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));
EXPECT_TRUE(DeleteFile(subdir_path2));
EXPECT_FALSE(PathExists(subdir_path2));
EXPECT_FALSE(DeleteFile(test_subdir));
EXPECT_TRUE(PathExists(test_subdir));
EXPECT_TRUE(PathExists(file_name));
EXPECT_TRUE(PathExists(subdir_path1));
}
TEST_F(FileUtilTest, DeleteDirRecursive) {
FilePath test_subdir = temp_dir_.GetPath().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));
EXPECT_TRUE(DeletePathRecursively(subdir_path2));
EXPECT_FALSE(PathExists(subdir_path2));
EXPECT_TRUE(DeletePathRecursively(test_subdir));
EXPECT_FALSE(PathExists(file_name));
EXPECT_FALSE(PathExists(subdir_path1));
EXPECT_FALSE(PathExists(test_subdir));
}
TEST_F(FileUtilTest, DeleteDirRecursiveWithOpenFile) {
FilePath test_subdir = temp_dir_.GetPath().Append(FPL("DeleteWithOpenFile"));
CreateDirectory(test_subdir);
ASSERT_TRUE(PathExists(test_subdir));
FilePath file_name1 = test_subdir.Append(FPL("Undeletebable File1.txt"));
File file1(file_name1,
File::FLAG_CREATE | File::FLAG_READ | File::FLAG_WRITE);
ASSERT_TRUE(PathExists(file_name1));
FilePath file_name2 = test_subdir.Append(FPL("Deleteable File2.txt"));
CreateTextFile(file_name2, bogus_content);
ASSERT_TRUE(PathExists(file_name2));
FilePath file_name3 = test_subdir.Append(FPL("Undeletebable File3.txt"));
File file3(file_name3,
File::FLAG_CREATE | File::FLAG_READ | File::FLAG_WRITE);
ASSERT_TRUE(PathExists(file_name3));
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
int flags;
bool file_attrs_supported =
ioctl(file1.GetPlatformFile(), FS_IOC_GETFLAGS, &flags) == 0;
if (file_attrs_supported) {
flags |= FS_IMMUTABLE_FL;
ioctl(file1.GetPlatformFile(), FS_IOC_SETFLAGS, &flags);
ioctl(file3.GetPlatformFile(), FS_IOC_SETFLAGS, &flags);
}
#endif
DeletePathRecursively(test_subdir);
EXPECT_FALSE(PathExists(file_name2));
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
if (file_attrs_supported) {
flags &= ~FS_IMMUTABLE_FL;
ioctl(file1.GetPlatformFile(), FS_IOC_SETFLAGS, &flags);
ioctl(file3.GetPlatformFile(), FS_IOC_SETFLAGS, &flags);
}
#endif
}
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
TEST_F(FileUtilTest, TestNonBlockingFileReadLinux) {
FilePath fifo_path = temp_dir_.GetPath().Append(FPL("fifo"));
int res = mkfifo(fifo_path.MaybeAsASCII().c_str(),
S_IWUSR | S_IRUSR | S_IWGRP | S_IWGRP);
ASSERT_NE(res, -1);
base::ScopedFD fd(open(fifo_path.MaybeAsASCII().c_str(), O_RDWR));
ASSERT_TRUE(fd.is_valid());
std::string result;
ASSERT_FALSE(ReadFileToStringNonBlocking(fifo_path, &result));
EXPECT_EQ(errno, EWOULDBLOCK);
EXPECT_TRUE(result.empty());
ASSERT_EQ(write(fd.get(), "a", 1), 1);
ASSERT_FALSE(ReadFileToStringNonBlocking(fifo_path, &result));
EXPECT_EQ(errno, EWOULDBLOCK);
ASSERT_EQ(result.size(), 1u);
EXPECT_EQ(result[0], 'a');
}
#endif
TEST_F(FileUtilTest, MoveFileNew) {
FilePath file_name_from =
temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Move_Test_File.txt"));
CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
ASSERT_TRUE(PathExists(file_name_from));
FilePath file_name_to = temp_dir_.GetPath().Append(
FILE_PATH_LITERAL("Move_Test_File_Destination.txt"));
ASSERT_FALSE(PathExists(file_name_to));
EXPECT_TRUE(Move(file_name_from, file_name_to));
EXPECT_FALSE(PathExists(file_name_from));
EXPECT_TRUE(PathExists(file_name_to));
}
TEST_F(FileUtilTest, MoveFileExists) {
FilePath file_name_from =
temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Move_Test_File.txt"));
CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
ASSERT_TRUE(PathExists(file_name_from));
FilePath file_name_to = temp_dir_.GetPath().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));
EXPECT_FALSE(PathExists(file_name_from));
EXPECT_TRUE(PathExists(file_name_to));
EXPECT_TRUE(L"Gooooooooooooooooooooogle" == ReadTextFile(file_name_to));
}
TEST_F(FileUtilTest, MoveFileDirExists) {
FilePath file_name_from =
temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Move_Test_File.txt"));
CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
ASSERT_TRUE(PathExists(file_name_from));
FilePath dir_name_to =
temp_dir_.GetPath().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) {
FilePath dir_name_from =
temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Move_From_Subdir"));
CreateDirectory(dir_name_from);
ASSERT_TRUE(PathExists(dir_name_from));
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));
FilePath dir_name_to =
temp_dir_.GetPath().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));
EXPECT_FALSE(PathExists(dir_name_from));
EXPECT_FALSE(PathExists(file_name_from));
EXPECT_TRUE(PathExists(dir_name_to));
EXPECT_TRUE(PathExists(file_name_to));
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) {
FilePath dir_name_from =
temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Move_From_Subdir"));
CreateDirectory(dir_name_from);
ASSERT_TRUE(PathExists(dir_name_from));
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));
FilePath dir_name_exists =
temp_dir_.GetPath().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"));
CreateDirectory(dir_name_exists);
ASSERT_TRUE(PathExists(dir_name_exists));
EXPECT_TRUE(Move(dir_name_from, dir_name_to));
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) {
FilePath dir_name_from =
temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
CreateDirectory(dir_name_from);
ASSERT_TRUE(PathExists(dir_name_from));
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));
FilePath subdir_name_from = dir_name_from.Append(FILE_PATH_LITERAL("Subdir"));
CreateDirectory(subdir_name_from);
ASSERT_TRUE(PathExists(subdir_name_from));
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));
FilePath dir_name_to =
temp_dir_.GetPath().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));
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) {
FilePath dir_name_from =
temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
CreateDirectory(dir_name_from);
ASSERT_TRUE(PathExists(dir_name_from));
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));
FilePath subdir_name_from = dir_name_from.Append(FILE_PATH_LITERAL("Subdir"));
CreateDirectory(subdir_name_from);
ASSERT_TRUE(PathExists(subdir_name_from));
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));
FilePath dir_name_exists =
temp_dir_.GetPath().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"));
CreateDirectory(dir_name_exists);
ASSERT_TRUE(PathExists(dir_name_exists));
EXPECT_TRUE(CopyDirectory(dir_name_from, dir_name_exists, true));
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) {
FilePath dir_name_from =
temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
CreateDirectory(dir_name_from);
ASSERT_TRUE(PathExists(dir_name_from));
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));
FilePath subdir_name_from = dir_name_from.Append(FILE_PATH_LITERAL("Subdir"));
CreateDirectory(subdir_name_from);
ASSERT_TRUE(PathExists(subdir_name_from));
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));
FilePath dir_name_to =
temp_dir_.GetPath().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));
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) {
FilePath dir_name_from =
temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
CreateDirectory(dir_name_from);
ASSERT_TRUE(PathExists(dir_name_from));
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));
FilePath subdir_name_from = dir_name_from.Append(FILE_PATH_LITERAL("Subdir"));
CreateDirectory(subdir_name_from);
ASSERT_TRUE(PathExists(subdir_name_from));
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));
FilePath dir_name_to =
temp_dir_.GetPath().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"));
CreateDirectory(dir_name_to);
ASSERT_TRUE(PathExists(dir_name_to));
EXPECT_TRUE(CopyDirectory(dir_name_from, dir_name_to, false));
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) {
FilePath file_name_from =
temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
ASSERT_TRUE(PathExists(file_name_from));
FilePath file_name_to = temp_dir_.GetPath().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));
EXPECT_TRUE(PathExists(file_name_to));
}
TEST_F(FileUtilTest, CopyFileWithCopyDirectoryRecursiveToExisting) {
FilePath file_name_from =
temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
ASSERT_TRUE(PathExists(file_name_from));
FilePath file_name_to = temp_dir_.GetPath().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));
EXPECT_TRUE(PathExists(file_name_to));
EXPECT_TRUE(L"Gooooooooooooooooooooogle" == ReadTextFile(file_name_to));
}
TEST_F(FileUtilTest, CopyFileWithCopyDirectoryRecursiveToExistingDirectory) {
FilePath file_name_from =
temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
ASSERT_TRUE(PathExists(file_name_from));
FilePath dir_name_to =
temp_dir_.GetPath().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));
EXPECT_TRUE(PathExists(file_name_to));
}
TEST_F(FileUtilTest, CopyFileFailureWithCopyDirectoryExcl) {
FilePath file_name_from =
temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
ASSERT_TRUE(PathExists(file_name_from));
FilePath file_name_to = temp_dir_.GetPath().Append(
FILE_PATH_LITERAL("Copy_Test_File_Destination.txt"));
CreateTextFile(file_name_to, L"Old file content");
ASSERT_TRUE(PathExists(file_name_to));
EXPECT_FALSE(CopyDirectoryExcl(file_name_from, file_name_to, true));
EXPECT_EQ(L"Old file content", ReadTextFile(file_name_to));
}
TEST_F(FileUtilTest, CopyDirectoryWithTrailingSeparators) {
FilePath dir_name_from =
temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
CreateDirectory(dir_name_from);
ASSERT_TRUE(PathExists(dir_name_from));
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));
FilePath dir_name_to =
temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_To_Subdir"));
FilePath file_name_to =
dir_name_to.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
#if BUILDFLAG(IS_WIN)
FilePath from_path =
temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_From_Subdir\\\\\\"));
#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
FilePath from_path =
temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_From_Subdir///"));
#endif
EXPECT_TRUE(CopyDirectory(from_path, dir_name_to, true));
EXPECT_TRUE(PathExists(dir_name_from));
EXPECT_TRUE(PathExists(file_name_from));
EXPECT_TRUE(PathExists(dir_name_to));
EXPECT_TRUE(PathExists(file_name_to));
}
#if BUILDFLAG(IS_POSIX)
TEST_F(FileUtilTest, CopyDirectoryWithNonRegularFiles) {
FilePath dir_name_from =
temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
ASSERT_TRUE(CreateDirectory(dir_name_from));
ASSERT_TRUE(PathExists(dir_name_from));
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));
FilePath symlink_name_from =
dir_name_from.Append(FILE_PATH_LITERAL("Symlink"));
ASSERT_TRUE(CreateSymbolicLink(file_name_from, symlink_name_from));
ASSERT_TRUE(PathExists(symlink_name_from));
FilePath fifo_name_from = dir_name_from.Append(FILE_PATH_LITERAL("Fifo"));
ASSERT_EQ(0, mkfifo(fifo_name_from.value().c_str(), 0644));
ASSERT_TRUE(PathExists(fifo_name_from));
FilePath dir_name_to =
temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_To_Subdir"));
FilePath file_name_to =
dir_name_to.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
FilePath symlink_name_to = dir_name_to.Append(FILE_PATH_LITERAL("Symlink"));
FilePath fifo_name_to = dir_name_to.Append(FILE_PATH_LITERAL("Fifo"));
ASSERT_FALSE(PathExists(dir_name_to));
EXPECT_TRUE(CopyDirectory(dir_name_from, dir_name_to, false));
EXPECT_TRUE(PathExists(dir_name_from));
EXPECT_TRUE(PathExists(file_name_from));
EXPECT_TRUE(PathExists(symlink_name_from));
EXPECT_TRUE(PathExists(fifo_name_from));
EXPECT_TRUE(PathExists(dir_name_to));
EXPECT_TRUE(PathExists(file_name_to));
EXPECT_FALSE(PathExists(symlink_name_to));
EXPECT_FALSE(PathExists(fifo_name_to));
}
TEST_F(FileUtilTest, CopyDirectoryExclFileOverSymlink) {
FilePath dir_name_from =
temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
ASSERT_TRUE(CreateDirectory(dir_name_from));
ASSERT_TRUE(PathExists(dir_name_from));
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));
FilePath dir_name_to =
temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_To_Subdir"));
ASSERT_TRUE(CreateDirectory(dir_name_to));
ASSERT_TRUE(PathExists(dir_name_to));
FilePath symlink_target =
dir_name_to.Append(FILE_PATH_LITERAL("Symlink_Target.txt"));
CreateTextFile(symlink_target, L"asdf");
ASSERT_TRUE(PathExists(symlink_target));
FilePath symlink_name_to =
dir_name_to.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
ASSERT_TRUE(CreateSymbolicLink(symlink_target, symlink_name_to));
ASSERT_TRUE(PathExists(symlink_name_to));
EXPECT_FALSE(CopyDirectoryExcl(dir_name_from, dir_name_to, false));
}
TEST_F(FileUtilTest, CopyDirectoryExclDirectoryOverSymlink) {
FilePath dir_name_from =
temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
ASSERT_TRUE(CreateDirectory(dir_name_from));
ASSERT_TRUE(PathExists(dir_name_from));
FilePath subdir_name_from = dir_name_from.Append(FILE_PATH_LITERAL("Subsub"));
CreateDirectory(subdir_name_from);
ASSERT_TRUE(PathExists(subdir_name_from));
FilePath dir_name_to =
temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_To_Subdir"));
ASSERT_TRUE(CreateDirectory(dir_name_to));
ASSERT_TRUE(PathExists(dir_name_to));
FilePath symlink_target = dir_name_to.Append(FILE_PATH_LITERAL("Subsub"));
CreateTextFile(symlink_target, L"asdf");
ASSERT_TRUE(PathExists(symlink_target));
FilePath symlink_name_to =
dir_name_to.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
ASSERT_TRUE(CreateSymbolicLink(symlink_target, symlink_name_to));
ASSERT_TRUE(PathExists(symlink_name_to));
EXPECT_FALSE(CopyDirectoryExcl(dir_name_from, dir_name_to, false));
}
TEST_F(FileUtilTest, CopyDirectoryExclFileOverDanglingSymlink) {
FilePath dir_name_from =
temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
ASSERT_TRUE(CreateDirectory(dir_name_from));
ASSERT_TRUE(PathExists(dir_name_from));
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));
FilePath dir_name_to =
temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_To_Subdir"));
ASSERT_TRUE(CreateDirectory(dir_name_to));
ASSERT_TRUE(PathExists(dir_name_to));
FilePath symlink_target =
dir_name_to.Append(FILE_PATH_LITERAL("Symlink_Target.txt"));
CreateTextFile(symlink_target, L"asdf");
ASSERT_TRUE(PathExists(symlink_target));
FilePath symlink_name_to =
dir_name_to.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
ASSERT_TRUE(CreateSymbolicLink(symlink_target, symlink_name_to));
ASSERT_TRUE(PathExists(symlink_name_to));
ASSERT_TRUE(DeleteFile(symlink_target));
EXPECT_FALSE(CopyDirectoryExcl(dir_name_from, dir_name_to, false));
EXPECT_FALSE(PathExists(symlink_target));
}
TEST_F(FileUtilTest, CopyDirectoryExclDirectoryOverDanglingSymlink) {
FilePath dir_name_from =
temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
ASSERT_TRUE(CreateDirectory(dir_name_from));
ASSERT_TRUE(PathExists(dir_name_from));
FilePath subdir_name_from = dir_name_from.Append(FILE_PATH_LITERAL("Subsub"));
CreateDirectory(subdir_name_from);
ASSERT_TRUE(PathExists(subdir_name_from));
FilePath dir_name_to =
temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_To_Subdir"));
ASSERT_TRUE(CreateDirectory(dir_name_to));
ASSERT_TRUE(PathExists(dir_name_to));
FilePath symlink_target =
dir_name_to.Append(FILE_PATH_LITERAL("Symlink_Target.txt"));
CreateTextFile(symlink_target, L"asdf");
ASSERT_TRUE(PathExists(symlink_target));
FilePath symlink_name_to =
dir_name_to.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
ASSERT_TRUE(CreateSymbolicLink(symlink_target, symlink_name_to));
ASSERT_TRUE(PathExists(symlink_name_to));
ASSERT_TRUE(DeleteFile(symlink_target));
EXPECT_FALSE(CopyDirectoryExcl(dir_name_from, dir_name_to, false));
EXPECT_FALSE(PathExists(symlink_target));
}
TEST_F(FileUtilTest, CopyDirectoryExclFileOverFifo) {
FilePath dir_name_from =
temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
ASSERT_TRUE(CreateDirectory(dir_name_from));
ASSERT_TRUE(PathExists(dir_name_from));
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));
FilePath dir_name_to =
temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_To_Subdir"));
ASSERT_TRUE(CreateDirectory(dir_name_to));
ASSERT_TRUE(PathExists(dir_name_to));
FilePath fifo_name_to =
dir_name_to.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
ASSERT_EQ(0, mkfifo(fifo_name_to.value().c_str(), 0644));
ASSERT_TRUE(PathExists(fifo_name_to));
EXPECT_FALSE(CopyDirectoryExcl(dir_name_from, dir_name_to, false));
}
#endif
TEST_F(FileUtilTest, CopyFile) {
FilePath dir_name_from =
temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
ASSERT_TRUE(CreateDirectory(dir_name_from));
ASSERT_TRUE(DirectoryExists(dir_name_from));
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));
FilePath dest_file = dir_name_from.Append(FILE_PATH_LITERAL("DestFile.txt"));
ASSERT_TRUE(CopyFile(file_name_from, dest_file));
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));
FilePath dest_file2_test(dir_name_from);
dest_file2_test = dest_file2_test.DirName();
dest_file2_test = dest_file2_test.AppendASCII("DestFile.txt");
EXPECT_TRUE(PathExists(file_name_from));
EXPECT_TRUE(PathExists(dest_file));
EXPECT_EQ(file_contents, ReadTextFile(dest_file));
EXPECT_FALSE(PathExists(dest_file2_test));
EXPECT_FALSE(PathExists(dest_file2));
const std::wstring new_file_contents(L"Moogle");
CreateTextFile(file_name_from, new_file_contents);
ASSERT_TRUE(PathExists(file_name_from));
EXPECT_EQ(new_file_contents, ReadTextFile(file_name_from));
ASSERT_TRUE(CopyFile(file_name_from, dest_file));
EXPECT_TRUE(PathExists(dest_file));
EXPECT_EQ(new_file_contents, ReadTextFile(dest_file));
FilePath dest_dir = temp_dir_.GetPath().Append(FPL("dest_dir"));
ASSERT_TRUE(CreateDirectory(dest_dir));
EXPECT_TRUE(DirectoryExists(dest_dir));
EXPECT_TRUE(IsDirectoryEmpty(dest_dir));
ASSERT_FALSE(CopyFile(file_name_from, dest_dir));
EXPECT_TRUE(DirectoryExists(dest_dir));
EXPECT_TRUE(IsDirectoryEmpty(dest_dir));
}
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));
}
#if BUILDFLAG(IS_WIN)
TEST_F(FileUtilTest, CopyAndDeleteDirectoryTest) {
FilePath dir_name_from = temp_dir_.GetPath().Append(
FILE_PATH_LITERAL("CopyAndDelete_From_Subdir"));
CreateDirectory(dir_name_from);
ASSERT_TRUE(PathExists(dir_name_from));
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));
FilePath dir_name_to =
temp_dir_.GetPath().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));
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) {
const TCHAR* kTmpKey = _T("TMP");
std::array<const TCHAR*, 5> kTmpValues = {_T(""), _T("C:"), _T("C:\\"),
_T("C:\\tmp"), _T("C:\\tmp\\")};
size_t original_tmp_size;
TCHAR* original_tmp;
ASSERT_EQ(0, ::_tdupenv_s(&original_tmp, &original_tmp_size, kTmpKey));
for (const TCHAR* val : kTmpValues) {
FilePath path;
::_tputenv_s(kTmpKey, val);
GetTempDir(&path);
EXPECT_TRUE(path.IsAbsolute())
<< "$TMP=" << val << " result=" << path.value();
}
if (original_tmp) {
::_tputenv_s(kTmpKey, original_tmp);
free(original_tmp);
} else {
::_tputenv_s(kTmpKey, _T(""));
}
}
#endif
TEST_F(FileUtilTest, OpenFileNoInheritance) {
FilePath file_path(temp_dir_.GetPath().Append(FPL("a_file")));
#if defined(ADDRESS_SANITIZER)
static constexpr const char* modes[] = {"wb", "r"};
#else
static constexpr const char* modes[] = {"wb", "r,ccs=UTF-8"};
#endif
for (const char* mode : modes) {
SCOPED_TRACE(mode);
ASSERT_NO_FATAL_FAILURE(CreateTextFile(file_path, L"Geepers"));
FILE* file = OpenFile(file_path, mode);
ASSERT_NE(nullptr, file);
{
absl::Cleanup file_closer = [file] { CloseFile(file); };
bool is_inheritable = true;
ASSERT_NO_FATAL_FAILURE(GetIsInheritable(file, &is_inheritable));
EXPECT_FALSE(is_inheritable);
}
ASSERT_TRUE(DeleteFile(file_path));
}
}
TEST_F(FileUtilTest, CreateAndOpenTemporaryFileInDir) {
FilePath path;
File file = CreateAndOpenTemporaryFileInDir(temp_dir_.GetPath(), &path);
ASSERT_TRUE(file.IsValid());
EXPECT_FALSE(path.empty());
File file2(path,
File::FLAG_OPEN | File::FLAG_READ | File::FLAG_WIN_SHARE_DELETE);
#if BUILDFLAG(IS_WIN)
EXPECT_FALSE(file2.IsValid());
#else
EXPECT_TRUE(file2.IsValid());
#endif
}
TEST_F(FileUtilTest, CreateTemporaryFileTest) {
std::array<FilePath, 3> temp_files;
for (auto& i : temp_files) {
ASSERT_TRUE(CreateTemporaryFile(&i));
EXPECT_TRUE(PathExists(i));
EXPECT_FALSE(DirectoryExists(i));
}
for (size_t i = 0u; i < 3u; i++) {
EXPECT_NE(temp_files[i], temp_files[(i + 1u) % 3u]);
}
for (const auto& i : temp_files) {
EXPECT_TRUE(DeleteFile(i));
}
}
TEST_F(FileUtilTest, CreateAndOpenTemporaryStreamTest) {
std::array<FilePath, 3> names;
std::array<ScopedFILE, 3> fps;
size_t i;
for (i = 0u; i < 3u; ++i) {
fps[i] = CreateAndOpenTemporaryStream(&(names[i]));
ASSERT_TRUE(fps[i]);
EXPECT_TRUE(PathExists(names[i]));
}
for (i = 0u; i < 3u; ++i) {
EXPECT_NE(names[i], names[(i + 1u) % 3u]);
}
for (i = 0u; i < 3u; ++i) {
fps[i].reset();
EXPECT_TRUE(DeleteFile(names[i]));
}
}
TEST_F(FileUtilTest, GetUniquePath) {
FilePath base_name(FPL("Unique_Base_Name.txt"));
FilePath base_path = temp_dir_.GetPath().Append(base_name);
EXPECT_FALSE(PathExists(base_path));
EXPECT_EQ(base_path, GetUniquePath(base_path));
{
File file(base_path,
File::FLAG_CREATE | File::FLAG_READ | File::FLAG_WRITE);
EXPECT_TRUE(PathExists(base_path));
}
static const FilePath::CharType* const kExpectedNames[] = {
FPL("Unique_Base_Name (1).txt"),
FPL("Unique_Base_Name (2).txt"),
FPL("Unique_Base_Name (3).txt"),
};
for (const FilePath::CharType* expected_name : kExpectedNames) {
FilePath expected_path = temp_dir_.GetPath().Append(expected_name);
FilePath path = GetUniquePath(base_path);
EXPECT_EQ(expected_path, path);
EXPECT_FALSE(PathExists(path));
File file(path, File::FLAG_CREATE | File::FLAG_READ | File::FLAG_WRITE);
EXPECT_TRUE(PathExists(path));
}
}
TEST_F(FileUtilTest, GetUniquePathTooManyFiles) {
const FilePath some_file = temp_dir_.GetPath().Append(FPL("SomeFile.txt"));
ASSERT_TRUE(File(some_file, File::FLAG_CREATE | File::FLAG_WRITE).IsValid());
for (int i = 1; i <= kMaxUniqueFiles; ++i) {
FilePath path =
temp_dir_.GetPath().AppendASCII(StringPrintf("SomeFile (%d).txt", i));
ASSERT_EQ(GetUniquePath(some_file), path);
ASSERT_TRUE(File(path, File::FLAG_CREATE | File::FLAG_WRITE).IsValid());
}
EXPECT_EQ(GetUniquePath(some_file), base::FilePath());
}
TEST_F(FileUtilTest, GetUniquePathWithSuffixFormat) {
const char kSuffix[] = "_%d";
FilePath base_name(FPL("Unique_Base_Name.txt"));
FilePath base_path = temp_dir_.GetPath().Append(base_name);
EXPECT_FALSE(PathExists(base_path));
EXPECT_EQ(base_path, GetUniquePathWithSuffixFormat(base_path, kSuffix));
{
File file(base_path,
File::FLAG_CREATE | File::FLAG_READ | File::FLAG_WRITE);
EXPECT_TRUE(PathExists(base_path));
}
static const FilePath::CharType* const kExpectedNames[] = {
FPL("Unique_Base_Name_1.txt"),
FPL("Unique_Base_Name_2.txt"),
FPL("Unique_Base_Name_3.txt"),
};
for (const FilePath::CharType* expected_name : kExpectedNames) {
FilePath expected_path = temp_dir_.GetPath().Append(expected_name);
FilePath path = GetUniquePathWithSuffixFormat(base_path, kSuffix);
EXPECT_EQ(expected_path, path);
EXPECT_FALSE(PathExists(path));
File file(path, File::FLAG_CREATE | File::FLAG_READ | File::FLAG_WRITE);
EXPECT_TRUE(PathExists(path));
}
EXPECT_EQ(temp_dir_.GetPath().Append(FPL("Unique_Base_Name (1).txt")),
GetUniquePathWithSuffixFormat(base_path, " (%d)"));
}
TEST_F(FileUtilTest, FileToFILE) {
File file;
FILE* stream = FileToFILE(std::move(file), "w");
EXPECT_FALSE(stream);
FilePath file_name = temp_dir_.GetPath().Append(FPL("The file.txt"));
file = File(file_name, File::FLAG_CREATE | File::FLAG_WRITE);
EXPECT_TRUE(file.IsValid());
stream = FileToFILE(std::move(file), "w");
EXPECT_TRUE(stream);
EXPECT_FALSE(file.IsValid());
EXPECT_TRUE(CloseFile(stream));
}
TEST_F(FileUtilTest, FILEToFile) {
ScopedFILE stream;
EXPECT_FALSE(FILEToFile(stream.get()).IsValid());
stream.reset(OpenFile(temp_dir_.GetPath().Append(FPL("hello.txt")), "wb+"));
ASSERT_TRUE(stream);
File file = FILEToFile(stream.get());
EXPECT_TRUE(file.IsValid());
ASSERT_EQ(fprintf(stream.get(), "there"), 5);
ASSERT_EQ(fflush(stream.get()), 0);
EXPECT_EQ(file.GetLength(), 5L);
}
TEST_F(FileUtilTest, CreateNewTempDirectoryTest) {
FilePath temp_dir;
ASSERT_TRUE(CreateNewTempDirectory(FPL(""), &temp_dir));
EXPECT_TRUE(PathExists(temp_dir));
EXPECT_TRUE(DeleteFile(temp_dir));
}
TEST_F(FileUtilTest, CreateNewTempDirectoryPrefixTest) {
FilePath temp_dir;
ASSERT_TRUE(
CreateNewTempDirectory(FILE_PATH_LITERAL("test_dir_prefix"), &temp_dir));
EXPECT_TRUE(PathExists(temp_dir));
const FilePath::StringType matcher =
#if BUILDFLAG(IS_WIN)
FILE_PATH_LITERAL("test_dir_prefix*");
#else
FILE_PATH_LITERAL("*.test_dir_prefix.*");
#endif
EXPECT_THAT(temp_dir.value(),
::testing::HasSubstr(FILE_PATH_LITERAL("test_dir_prefix")));
EXPECT_TRUE(DeleteFile(temp_dir));
}
#if BUILDFLAG(IS_WIN)
TEST_F(FileUtilTest, TempDirectoryParentTest) {
if (!::IsUserAnAdmin()) {
GTEST_SKIP() << "This test must be run by an admin user";
}
FilePath temp_dir;
ASSERT_TRUE(CreateNewTempDirectory(FPL(""), &temp_dir));
EXPECT_TRUE(PathExists(temp_dir));
FilePath expected_parent_dir;
if (!::IsUserAnAdmin() ||
!PathService::Get(DIR_SYSTEM_TEMP, &expected_parent_dir)) {
EXPECT_TRUE(PathService::Get(DIR_TEMP, &expected_parent_dir));
}
EXPECT_TRUE(expected_parent_dir.IsParent(temp_dir));
EXPECT_TRUE(DeleteFile(temp_dir));
}
#endif
TEST_F(FileUtilTest, CreateNewTemporaryDirInDirTest) {
FilePath new_dir;
ASSERT_TRUE(CreateTemporaryDirInDir(
temp_dir_.GetPath(), FILE_PATH_LITERAL("CreateNewTemporaryDirInDirTest"),
&new_dir));
EXPECT_TRUE(PathExists(new_dir));
EXPECT_TRUE(temp_dir_.GetPath().IsParent(new_dir));
EXPECT_TRUE(DeleteFile(new_dir));
}
#if BUILDFLAG(IS_WIN)
TEST_F(FileUtilTest, GetSecureTempDirectory) {
FilePath temp_dir;
ASSERT_TRUE(GetSecureTempDirectory(&temp_dir));
FilePath expected_temp_dir;
if (internal::IsUserDefaultAdmin()) {
EXPECT_TRUE(PathService::Get(DIR_SYSTEM_TEMP, &expected_temp_dir));
} else {
EXPECT_TRUE(GetTempDir(&expected_temp_dir));
}
EXPECT_EQ(temp_dir, expected_temp_dir);
}
#endif
#if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
TEST_F(FileUtilTest, GetShmemTempDirTest) {
FilePath dir;
EXPECT_TRUE(GetShmemTempDir(false, &dir));
EXPECT_TRUE(DirectoryExists(dir));
}
TEST_F(FileUtilTest, AllocateFileRegionTest_ZeroOffset) {
std::string_view test_data = "test_data";
FilePath file_path = temp_dir_.GetPath().Append(
FILE_PATH_LITERAL("allocate_file_region_test_zero_offset"));
WriteFile(file_path, test_data);
File file(file_path, base::File::FLAG_OPEN | base::File::FLAG_READ |
base::File::FLAG_WRITE);
ASSERT_TRUE(file.IsValid());
ASSERT_GE(file.GetLength(), 0);
ASSERT_EQ(checked_cast<size_t>(file.GetLength()), test_data.size());
const int kExtendedFileLength = 23;
ASSERT_TRUE(AllocateFileRegion(&file, 0, kExtendedFileLength));
EXPECT_EQ(file.GetLength(), kExtendedFileLength);
char data_read[32] = {};
int bytes_read = UNSAFE_TODO(file.Read(0, data_read, kExtendedFileLength));
EXPECT_EQ(bytes_read, kExtendedFileLength);
auto [front, back] = base::span(data_read).split_at(test_data.size());
EXPECT_EQ(front, test_data);
EXPECT_THAT(back, testing::Each('\0'));
}
TEST_F(FileUtilTest, AllocateFileRegionTest_NonZeroOffset) {
std::string_view test_data = "test_data";
FilePath file_path = temp_dir_.GetPath().Append(
FILE_PATH_LITERAL("allocate_file_region_test_non_zero_offset"));
WriteFile(file_path, test_data);
File file(file_path, base::File::FLAG_OPEN | base::File::FLAG_READ |
base::File::FLAG_WRITE);
ASSERT_TRUE(file.IsValid());
ASSERT_GE(file.GetLength(), 0);
ASSERT_EQ(checked_cast<size_t>(file.GetLength()), test_data.size());
const int kExtensionOffset = 5;
const int kExtensionSize = 10;
ASSERT_TRUE(AllocateFileRegion(&file, kExtensionOffset, kExtensionSize));
const int kExtendedFileLength = kExtensionOffset + kExtensionSize;
EXPECT_EQ(file.GetLength(), kExtendedFileLength);
char data_read[32] = {};
int bytes_read = UNSAFE_TODO(file.Read(0, data_read, kExtendedFileLength));
EXPECT_EQ(bytes_read, kExtendedFileLength);
auto [front, back] = base::span(data_read).split_at(test_data.size());
EXPECT_EQ(front, test_data);
EXPECT_THAT(back, testing::Each('\0'));
}
TEST_F(FileUtilTest, AllocateFileRegionTest_DontTruncate) {
std::string_view test_data = "test_data";
FilePath file_path = temp_dir_.GetPath().Append(
FILE_PATH_LITERAL("allocate_file_region_test_dont_truncate"));
WriteFile(file_path, test_data);
File file(file_path, base::File::FLAG_OPEN | base::File::FLAG_READ |
base::File::FLAG_WRITE);
ASSERT_TRUE(file.IsValid());
ASSERT_GE(file.GetLength(), 0);
ASSERT_EQ(checked_cast<size_t>(file.GetLength()), test_data.size());
const int kTruncatedFileLength = 4;
ASSERT_TRUE(AllocateFileRegion(&file, 0, kTruncatedFileLength));
ASSERT_GE(file.GetLength(), 0);
EXPECT_EQ(checked_cast<size_t>(file.GetLength()), test_data.size());
}
#endif
TEST_F(FileUtilTest, GetHomeDirTest) {
#if !BUILDFLAG(IS_ANDROID)
FilePath home = GetHomeDir();
ASSERT_FALSE(home.empty());
ASSERT_TRUE(home.IsAbsolute());
#endif
}
TEST_F(FileUtilTest, CreateDirectoryTest) {
FilePath test_root =
temp_dir_.GetPath().Append(FILE_PATH_LITERAL("create_directory_test"));
#if BUILDFLAG(IS_WIN)
FilePath test_path =
test_root.Append(FILE_PATH_LITERAL("dir\\tree\\likely\\doesnt\\exist\\"));
#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
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));
EXPECT_TRUE(CreateDirectory(test_path));
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(DeletePathRecursively(test_root));
EXPECT_FALSE(PathExists(test_root));
EXPECT_FALSE(PathExists(test_path));
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));
EXPECT_TRUE(CreateDirectory(FilePath(FilePath::kCurrentDirectory)));
EXPECT_TRUE(CreateDirectory(top_level));
#if BUILDFLAG(IS_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) {
FilePath test_root =
temp_dir_.GetPath().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));
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));
EXPECT_TRUE(DeletePathRecursively(test_root));
}
TEST_F(FileUtilTest, FileEnumeratorTest) {
FileEnumerator f0(temp_dir_.GetPath(), true, FILES_AND_DIRECTORIES);
EXPECT_EQ(FPL(""), f0.Next().value());
EXPECT_EQ(FPL(""), f0.Next().value());
FileEnumerator f0_dotdot(
temp_dir_.GetPath(), false,
FILES_AND_DIRECTORIES | FileEnumerator::INCLUDE_DOT_DOT);
EXPECT_EQ(temp_dir_.GetPath().Append(FPL("..")).value(),
f0_dotdot.Next().value());
EXPECT_EQ(FPL(""), f0_dotdot.Next().value());
FilePath dir1 = temp_dir_.GetPath().Append(FPL("dir1"));
EXPECT_TRUE(CreateDirectory(dir1));
FilePath dir2 = temp_dir_.GetPath().Append(FPL("dir2"));
EXPECT_TRUE(CreateDirectory(dir2));
FilePath dir2inner = dir2.Append(FPL("inner"));
EXPECT_TRUE(CreateDirectory(dir2inner));
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_.GetPath().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_.GetPath().Append(FPL("file2.txt"));
FileEnumerator f1(temp_dir_.GetPath(), 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());
FileEnumerator f2(temp_dir_.GetPath(), 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());
FileEnumerator f2_non_recursive(temp_dir_.GetPath(), 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());
FileEnumerator f2_dotdot(
temp_dir_.GetPath(), 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_.GetPath().Append(FPL(".."))));
EXPECT_EQ(3, c2_dotdot.size());
FileEnumerator f3(temp_dir_.GetPath(), 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());
FileEnumerator f4(temp_dir_.GetPath(), 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());
FileEnumerator f5(temp_dir_.GetPath(), 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 BUILDFLAG(IS_WIN)
{
auto reparse_point = test::FilePathReparsePoint::Create(dir1, dir2);
EXPECT_TRUE(reparse_point.has_value());
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());
FileEnumerator f7(temp_dir_.GetPath(), 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());
FileEnumerator f8(temp_dir_.GetPath(), 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
FileEnumerator f9(temp_dir_.GetPath(), true, FILES_AND_DIRECTORIES);
EXPECT_FALSE(f9.Next().value().empty());
}
TEST_F(FileUtilTest, AppendToFile) {
FilePath data_dir =
temp_dir_.GetPath().Append(FILE_PATH_LITERAL("FilePathTest"));
if (PathExists(data_dir)) {
ASSERT_TRUE(DeletePathRecursively(data_dir));
}
ASSERT_TRUE(CreateDirectory(data_dir));
if (PathExists(data_dir)) {
ASSERT_TRUE(DeletePathRecursively(data_dir));
}
ASSERT_TRUE(CreateDirectory(data_dir));
FilePath foobar(data_dir.Append(FILE_PATH_LITERAL("foobar.txt")));
std::string data("hello");
EXPECT_FALSE(AppendToFile(foobar, data));
EXPECT_TRUE(WriteFile(foobar, data));
EXPECT_TRUE(AppendToFile(foobar, data));
const std::wstring read_content = ReadTextFile(foobar);
EXPECT_EQ(L"hellohello", read_content);
}
TEST_F(FileUtilTest, ReadFile) {
const std::string kTestData("The quick brown fox jumps over the lazy dog.");
FilePath file_path =
temp_dir_.GetPath().Append(FILE_PATH_LITERAL("ReadFileTest"));
ASSERT_TRUE(WriteFile(file_path, kTestData));
std::vector<char> small_buffer(kTestData.size() / 2);
std::vector<char> exact_buffer(kTestData.size());
std::vector<char> large_buffer(kTestData.size() * 2);
EXPECT_EQ(ReadFile(file_path, small_buffer), small_buffer.size());
EXPECT_EQ(kTestData.substr(0, small_buffer.size()),
std::string(small_buffer.begin(), small_buffer.end()));
EXPECT_EQ(ReadFile(file_path, exact_buffer), kTestData.size());
EXPECT_EQ(kTestData, std::string(exact_buffer.begin(), exact_buffer.end()));
EXPECT_EQ(ReadFile(file_path, large_buffer), kTestData.size());
EXPECT_EQ(kTestData, std::string(large_buffer.begin(),
large_buffer.begin() + kTestData.size()));
FilePath file_path_not_exist =
temp_dir_.GetPath().Append(FILE_PATH_LITERAL("ReadFileNotExistTest"));
EXPECT_EQ(ReadFile(file_path_not_exist, exact_buffer), std::nullopt);
}
TEST_F(FileUtilTest, ReadFileToBytes) {
const std::vector<uint8_t> kTestData = {'0', '1', '2', '3'};
FilePath file_path =
temp_dir_.GetPath().Append(FILE_PATH_LITERAL("ReadFileToStringTest"));
FilePath file_path_dangerous =
temp_dir_.GetPath()
.Append(FILE_PATH_LITERAL(".."))
.Append(temp_dir_.GetPath().BaseName())
.Append(FILE_PATH_LITERAL("ReadFileToStringTest"));
ASSERT_TRUE(WriteFile(file_path, kTestData));
std::optional<std::vector<uint8_t>> bytes = ReadFileToBytes(file_path);
ASSERT_TRUE(bytes.has_value());
EXPECT_EQ(kTestData, bytes);
ASSERT_TRUE(WriteFile(file_path, ""));
bytes = ReadFileToBytes(file_path);
ASSERT_TRUE(bytes.has_value());
EXPECT_TRUE(bytes->empty());
ASSERT_FALSE(ReadFileToBytes(file_path_dangerous));
}
TEST_F(FileUtilTest, ReadFileToString) {
const char kTestData[] = "0123";
std::string data;
FilePath file_path =
temp_dir_.GetPath().Append(FILE_PATH_LITERAL("ReadFileToStringTest"));
FilePath file_path_dangerous =
temp_dir_.GetPath()
.Append(FILE_PATH_LITERAL(".."))
.Append(temp_dir_.GetPath().BaseName())
.Append(FILE_PATH_LITERAL("ReadFileToStringTest"));
ASSERT_TRUE(WriteFile(file_path, kTestData));
EXPECT_TRUE(ReadFileToString(file_path, &data));
EXPECT_EQ(kTestData, data);
data = "temp";
EXPECT_FALSE(ReadFileToStringWithMaxSize(file_path, &data, 0));
EXPECT_EQ(0u, data.length());
data = "temp";
EXPECT_FALSE(ReadFileToStringWithMaxSize(file_path, &data, 2));
EXPECT_EQ("01", data);
data = "temp";
EXPECT_FALSE(ReadFileToStringWithMaxSize(file_path, &data, 3));
EXPECT_EQ("012", data);
data = "temp";
EXPECT_TRUE(ReadFileToStringWithMaxSize(file_path, &data, 4));
EXPECT_EQ("0123", data);
data = "temp";
EXPECT_TRUE(ReadFileToStringWithMaxSize(file_path, &data, 6));
EXPECT_EQ("0123", data);
EXPECT_TRUE(ReadFileToStringWithMaxSize(file_path, nullptr, 6));
EXPECT_TRUE(ReadFileToString(file_path, nullptr));
data = "temp";
EXPECT_FALSE(ReadFileToString(file_path_dangerous, &data));
EXPECT_EQ(0u, data.length());
EXPECT_TRUE(DeleteFile(file_path));
data = "temp";
EXPECT_FALSE(ReadFileToString(file_path, &data));
EXPECT_EQ(0u, data.length());
data = "temp";
EXPECT_FALSE(ReadFileToStringWithMaxSize(file_path, &data, 6));
EXPECT_EQ(0u, data.length());
}
#if !BUILDFLAG(IS_WIN)
TEST_F(FileUtilTest, ReadFileToStringWithUnknownFileSize) {
#if BUILDFLAG(IS_FUCHSIA)
test::TaskEnvironment task_environment;
auto dev_zero = ScopedDevZero::Get();
ASSERT_TRUE(dev_zero);
#endif
FilePath file_path("/dev/zero");
std::string data = "temp";
EXPECT_FALSE(ReadFileToStringWithMaxSize(file_path, &data, 0));
EXPECT_EQ(0u, data.length());
data = "temp";
EXPECT_FALSE(ReadFileToStringWithMaxSize(file_path, &data, 2));
EXPECT_EQ(std::string(2, '\0'), data);
EXPECT_FALSE(ReadFileToStringWithMaxSize(file_path, nullptr, 6));
data = "temp";
EXPECT_FALSE(ReadFileToStringWithMaxSize(file_path, &data, kLargeFileSize));
EXPECT_EQ(kLargeFileSize, data.length());
EXPECT_EQ(std::string(kLargeFileSize, '\0'), data);
EXPECT_FALSE(ReadFileToStringWithMaxSize(file_path, nullptr, kLargeFileSize));
}
#endif
#if !BUILDFLAG(IS_WIN) && !BUILDFLAG(IS_FUCHSIA) && !BUILDFLAG(IS_IOS)
#define ChildMain WriteToPipeChildMain
#define ChildMainString "WriteToPipeChildMain"
MULTIPROCESS_TEST_MAIN(ChildMain) {
CommandLine* command_line = CommandLine::ForCurrentProcess();
const FilePath pipe_path = command_line->GetSwitchValuePath("pipe-path");
int fd = open(pipe_path.value().c_str(), O_WRONLY);
CHECK_NE(-1, fd);
base::span<const char> to_write = base::span_from_cstring("0123");
while (!to_write.empty()) {
ssize_t res = write(fd, to_write.data(), to_write.size());
if (res == -1) {
break;
}
to_write = to_write.subspan(checked_cast<size_t>(res));
}
CHECK_EQ(to_write.size(), 0u);
CHECK_EQ(0, close(fd));
return 0;
}
#define MoreThanBufferSizeChildMain WriteToPipeMoreThanBufferSizeChildMain
#define MoreThanBufferSizeChildMainString \
"WriteToPipeMoreThanBufferSizeChildMain"
MULTIPROCESS_TEST_MAIN(MoreThanBufferSizeChildMain) {
std::string data(kLargeFileSize, 'c');
CommandLine* command_line = CommandLine::ForCurrentProcess();
const FilePath pipe_path = command_line->GetSwitchValuePath("pipe-path");
int fd = open(pipe_path.value().c_str(), O_WRONLY);
CHECK_NE(-1, fd);
base::span<const char> to_write = base::span(data);
while (!to_write.empty()) {
ssize_t res = write(fd, to_write.data(), to_write.size());
if (res == -1) {
break;
}
to_write = to_write.subspan(checked_cast<size_t>(res));
}
CHECK_EQ(0, close(fd));
return 0;
}
TEST_F(FileUtilTest, ReadFileToStringWithNamedPipe) {
FilePath pipe_path =
temp_dir_.GetPath().Append(FILE_PATH_LITERAL("test_pipe"));
ASSERT_EQ(0, mkfifo(pipe_path.value().c_str(), 0600));
CommandLine child_command_line(GetMultiProcessTestChildBaseCommandLine());
child_command_line.AppendSwitchPath("pipe-path", pipe_path);
{
Process child_process = SpawnMultiProcessTestChild(
ChildMainString, child_command_line, LaunchOptions());
ASSERT_TRUE(child_process.IsValid());
std::string data = "temp";
EXPECT_FALSE(ReadFileToStringWithMaxSize(pipe_path, &data, 2));
EXPECT_EQ("01", data);
int rv = -1;
ASSERT_TRUE(WaitForMultiprocessTestChildExit(
child_process, TestTimeouts::action_timeout(), &rv));
ASSERT_EQ(0, rv);
}
{
Process child_process = SpawnMultiProcessTestChild(
ChildMainString, child_command_line, LaunchOptions());
ASSERT_TRUE(child_process.IsValid());
std::string data = "temp";
EXPECT_TRUE(ReadFileToStringWithMaxSize(pipe_path, &data, 6));
EXPECT_EQ("0123", data);
int rv = -1;
ASSERT_TRUE(WaitForMultiprocessTestChildExit(
child_process, TestTimeouts::action_timeout(), &rv));
ASSERT_EQ(0, rv);
}
{
Process child_process = SpawnMultiProcessTestChild(
MoreThanBufferSizeChildMainString, child_command_line, LaunchOptions());
ASSERT_TRUE(child_process.IsValid());
std::string data = "temp";
EXPECT_FALSE(ReadFileToStringWithMaxSize(pipe_path, &data, 6));
EXPECT_EQ("cccccc", data);
int rv = -1;
ASSERT_TRUE(WaitForMultiprocessTestChildExit(
child_process, TestTimeouts::action_timeout(), &rv));
ASSERT_EQ(0, rv);
}
{
Process child_process = SpawnMultiProcessTestChild(
MoreThanBufferSizeChildMainString, child_command_line, LaunchOptions());
ASSERT_TRUE(child_process.IsValid());
std::string data = "temp";
EXPECT_FALSE(
ReadFileToStringWithMaxSize(pipe_path, &data, kLargeFileSize - 1));
EXPECT_EQ(std::string(kLargeFileSize - 1, 'c'), data);
int rv = -1;
ASSERT_TRUE(WaitForMultiprocessTestChildExit(
child_process, TestTimeouts::action_timeout(), &rv));
ASSERT_EQ(0, rv);
}
{
Process child_process = SpawnMultiProcessTestChild(
MoreThanBufferSizeChildMainString, child_command_line, LaunchOptions());
ASSERT_TRUE(child_process.IsValid());
std::string data = "temp";
EXPECT_TRUE(ReadFileToStringWithMaxSize(pipe_path, &data, kLargeFileSize));
EXPECT_EQ(std::string(kLargeFileSize, 'c'), data);
int rv = -1;
ASSERT_TRUE(WaitForMultiprocessTestChildExit(
child_process, TestTimeouts::action_timeout(), &rv));
ASSERT_EQ(0, rv);
}
{
Process child_process = SpawnMultiProcessTestChild(
MoreThanBufferSizeChildMainString, child_command_line, LaunchOptions());
ASSERT_TRUE(child_process.IsValid());
std::string data = "temp";
EXPECT_TRUE(
ReadFileToStringWithMaxSize(pipe_path, &data, kLargeFileSize * 5));
EXPECT_EQ(std::string(kLargeFileSize, 'c'), data);
int rv = -1;
ASSERT_TRUE(WaitForMultiprocessTestChildExit(
child_process, TestTimeouts::action_timeout(), &rv));
ASSERT_EQ(0, rv);
}
ASSERT_EQ(0, unlink(pipe_path.value().c_str()));
}
#endif
#if BUILDFLAG(IS_WIN)
#define ChildMain WriteToPipeChildMain
#define ChildMainString "WriteToPipeChildMain"
MULTIPROCESS_TEST_MAIN(ChildMain) {
const char kTestData[] = "0123";
CommandLine* command_line = CommandLine::ForCurrentProcess();
const FilePath pipe_path = command_line->GetSwitchValuePath("pipe-path");
std::string switch_string = command_line->GetSwitchValueASCII("sync_event");
EXPECT_FALSE(switch_string.empty());
unsigned int switch_uint = 0;
EXPECT_TRUE(StringToUint(switch_string, &switch_uint));
win::ScopedHandle sync_event(win::Uint32ToHandle(switch_uint));
HANDLE ph = CreateNamedPipe(pipe_path.value().c_str(), PIPE_ACCESS_OUTBOUND,
PIPE_WAIT, 1, 0, 0, 0, NULL);
EXPECT_NE(ph, INVALID_HANDLE_VALUE);
EXPECT_TRUE(SetEvent(sync_event.get()));
if (!::ConnectNamedPipe(ph, nullptr)) {
auto error = ::GetLastError();
EXPECT_EQ(error, DWORD{ERROR_PIPE_CONNECTED});
}
DWORD written;
EXPECT_TRUE(::WriteFile(ph, kTestData, strlen(kTestData), &written, NULL));
EXPECT_EQ(strlen(kTestData), written);
CloseHandle(ph);
return 0;
}
#define MoreThanBufferSizeChildMain WriteToPipeMoreThanBufferSizeChildMain
#define MoreThanBufferSizeChildMainString \
"WriteToPipeMoreThanBufferSizeChildMain"
MULTIPROCESS_TEST_MAIN(MoreThanBufferSizeChildMain) {
std::string data(kLargeFileSize, 'c');
CommandLine* command_line = CommandLine::ForCurrentProcess();
const FilePath pipe_path = command_line->GetSwitchValuePath("pipe-path");
std::string switch_string = command_line->GetSwitchValueASCII("sync_event");
EXPECT_FALSE(switch_string.empty());
unsigned int switch_uint = 0;
EXPECT_TRUE(StringToUint(switch_string, &switch_uint));
win::ScopedHandle sync_event(win::Uint32ToHandle(switch_uint));
HANDLE ph = CreateNamedPipe(pipe_path.value().c_str(), PIPE_ACCESS_OUTBOUND,
PIPE_WAIT, 1, data.size(), data.size(), 0, NULL);
EXPECT_NE(ph, INVALID_HANDLE_VALUE);
EXPECT_TRUE(SetEvent(sync_event.get()));
if (!::ConnectNamedPipe(ph, nullptr)) {
auto error = ::GetLastError();
EXPECT_EQ(error, DWORD{ERROR_PIPE_CONNECTED});
}
DWORD written;
EXPECT_TRUE(::WriteFile(ph, data.c_str(), data.size(), &written, NULL));
EXPECT_EQ(data.size(), written);
CloseHandle(ph);
return 0;
}
TEST_F(FileUtilTest, ReadFileToStringWithNamedPipe) {
FilePath pipe_path(FILE_PATH_LITERAL("\\\\.\\pipe\\test_pipe"));
win::ScopedHandle sync_event(CreateEvent(0, false, false, nullptr));
CommandLine child_command_line(GetMultiProcessTestChildBaseCommandLine());
child_command_line.AppendSwitchPath("pipe-path", pipe_path);
child_command_line.AppendSwitchASCII(
"sync_event", NumberToString(win::HandleToUint32(sync_event.get())));
LaunchOptions options;
options.handles_to_inherit.push_back(sync_event.get());
{
Process child_process = SpawnMultiProcessTestChild(
ChildMainString, child_command_line, options);
ASSERT_TRUE(child_process.IsValid());
EXPECT_EQ(WAIT_OBJECT_0, WaitForSingleObject(sync_event.get(), INFINITE));
std::string data = "temp";
EXPECT_FALSE(ReadFileToStringWithMaxSize(pipe_path, &data, 2));
EXPECT_EQ("01", data);
int rv = -1;
ASSERT_TRUE(WaitForMultiprocessTestChildExit(
child_process, TestTimeouts::action_timeout(), &rv));
ASSERT_EQ(0, rv);
}
{
Process child_process = SpawnMultiProcessTestChild(
ChildMainString, child_command_line, options);
ASSERT_TRUE(child_process.IsValid());
EXPECT_EQ(WAIT_OBJECT_0, WaitForSingleObject(sync_event.get(), INFINITE));
std::string data = "temp";
EXPECT_TRUE(ReadFileToStringWithMaxSize(pipe_path, &data, 6));
EXPECT_EQ("0123", data);
int rv = -1;
ASSERT_TRUE(WaitForMultiprocessTestChildExit(
child_process, TestTimeouts::action_timeout(), &rv));
ASSERT_EQ(0, rv);
}
{
Process child_process = SpawnMultiProcessTestChild(
MoreThanBufferSizeChildMainString, child_command_line, options);
ASSERT_TRUE(child_process.IsValid());
EXPECT_EQ(WAIT_OBJECT_0, WaitForSingleObject(sync_event.get(), INFINITE));
std::string data = "temp";
EXPECT_FALSE(ReadFileToStringWithMaxSize(pipe_path, &data, 6));
EXPECT_EQ("cccccc", data);
int rv = -1;
ASSERT_TRUE(WaitForMultiprocessTestChildExit(
child_process, TestTimeouts::action_timeout(), &rv));
ASSERT_EQ(0, rv);
}
{
Process child_process = SpawnMultiProcessTestChild(
MoreThanBufferSizeChildMainString, child_command_line, options);
ASSERT_TRUE(child_process.IsValid());
EXPECT_EQ(WAIT_OBJECT_0, WaitForSingleObject(sync_event.get(), INFINITE));
std::string data = "temp";
EXPECT_FALSE(
ReadFileToStringWithMaxSize(pipe_path, &data, kLargeFileSize - 1));
EXPECT_EQ(std::string(kLargeFileSize - 1, 'c'), data);
int rv = -1;
ASSERT_TRUE(WaitForMultiprocessTestChildExit(
child_process, TestTimeouts::action_timeout(), &rv));
ASSERT_EQ(0, rv);
}
{
Process child_process = SpawnMultiProcessTestChild(
MoreThanBufferSizeChildMainString, child_command_line, options);
ASSERT_TRUE(child_process.IsValid());
EXPECT_EQ(WAIT_OBJECT_0, WaitForSingleObject(sync_event.get(), INFINITE));
std::string data = "temp";
EXPECT_TRUE(ReadFileToStringWithMaxSize(pipe_path, &data, kLargeFileSize));
EXPECT_EQ(std::string(kLargeFileSize, 'c'), data);
int rv = -1;
ASSERT_TRUE(WaitForMultiprocessTestChildExit(
child_process, TestTimeouts::action_timeout(), &rv));
ASSERT_EQ(0, rv);
}
{
Process child_process = SpawnMultiProcessTestChild(
MoreThanBufferSizeChildMainString, child_command_line, options);
ASSERT_TRUE(child_process.IsValid());
EXPECT_EQ(WAIT_OBJECT_0, WaitForSingleObject(sync_event.get(), INFINITE));
std::string data = "temp";
EXPECT_TRUE(
ReadFileToStringWithMaxSize(pipe_path, &data, kLargeFileSize * 5));
EXPECT_EQ(std::string(kLargeFileSize, 'c'), data);
int rv = -1;
ASSERT_TRUE(WaitForMultiprocessTestChildExit(
child_process, TestTimeouts::action_timeout(), &rv));
ASSERT_EQ(0, rv);
}
}
#endif
#if BUILDFLAG(IS_POSIX) && !BUILDFLAG(IS_APPLE)
TEST_F(FileUtilTest, ReadFileToStringWithProcFileSystem) {
FilePath file_path("/proc/cpuinfo");
std::string data = "temp";
EXPECT_FALSE(ReadFileToStringWithMaxSize(file_path, &data, 0));
EXPECT_EQ(0u, data.length());
data = "temp";
EXPECT_FALSE(ReadFileToStringWithMaxSize(file_path, &data, 2));
EXPECT_TRUE(EqualsCaseInsensitiveASCII("pr", data));
data = "temp";
EXPECT_FALSE(ReadFileToStringWithMaxSize(file_path, &data, 4));
EXPECT_TRUE(EqualsCaseInsensitiveASCII("proc", data));
EXPECT_FALSE(ReadFileToStringWithMaxSize(file_path, nullptr, 4));
}
#endif
TEST_F(FileUtilTest, ReadFileToStringWithLargeFile) {
std::string data(kLargeFileSize, 'c');
FilePath file_path =
temp_dir_.GetPath().Append(FILE_PATH_LITERAL("ReadFileToStringTest"));
ASSERT_TRUE(WriteFile(file_path, data));
std::string actual_data = "temp";
EXPECT_TRUE(ReadFileToString(file_path, &actual_data));
EXPECT_EQ(data, actual_data);
actual_data = "temp";
EXPECT_FALSE(ReadFileToStringWithMaxSize(file_path, &actual_data, 0));
EXPECT_EQ(0u, actual_data.length());
actual_data = "temp";
EXPECT_FALSE(
ReadFileToStringWithMaxSize(file_path, &actual_data, kLargeFileSize - 1));
EXPECT_EQ(std::string(kLargeFileSize - 1, 'c'), actual_data);
}
TEST_F(FileUtilTest, ReadStreamToString) {
ScopedFILE stream(
OpenFile(temp_dir_.GetPath().Append(FPL("hello.txt")), "wb+"));
ASSERT_TRUE(stream);
File file = FILEToFile(stream.get());
ASSERT_TRUE(file.IsValid());
ASSERT_EQ(fprintf(stream.get(), "there"), 5);
ASSERT_EQ(fflush(stream.get()), 0);
std::string contents;
EXPECT_TRUE(ReadStreamToString(stream.get(), &contents));
EXPECT_EQ(contents, std::string("there"));
}
#if BUILDFLAG(IS_POSIX)
TEST_F(FileUtilTest, ReadStreamToString_ZeroLengthFile) {
Thread write_thread("write thread");
ASSERT_TRUE(write_thread.Start());
const size_t kSizes[] = {0, 1, 4095, 4096, 4097, 65535, 65536, 65537};
for (size_t size : kSizes) {
ScopedFD read_fd, write_fd;
ASSERT_TRUE(CreatePipe(&read_fd, &write_fd, false ));
std::string random_data;
if (size > 0) {
random_data = RandBytesAsString(size);
}
EXPECT_EQ(size, random_data.size());
write_thread.task_runner()->PostTask(
FROM_HERE,
BindLambdaForTesting([random_data, write_fd = std::move(write_fd)]() {
ASSERT_TRUE(WriteFileDescriptor(write_fd.get(), random_data));
}));
ScopedFILE read_file(fdopen(read_fd.release(), "r"));
ASSERT_TRUE(read_file);
std::string contents;
EXPECT_TRUE(ReadStreamToString(read_file.get(), &contents));
EXPECT_EQ(contents, random_data);
}
}
#endif
TEST_F(FileUtilTest, ReadStreamToStringWithMaxSize) {
ScopedFILE stream(
OpenFile(temp_dir_.GetPath().Append(FPL("hello.txt")), "wb+"));
ASSERT_TRUE(stream);
File file = FILEToFile(stream.get());
ASSERT_TRUE(file.IsValid());
ASSERT_EQ(fprintf(stream.get(), "there"), 5);
ASSERT_EQ(fflush(stream.get()), 0);
std::string contents;
EXPECT_FALSE(ReadStreamToStringWithMaxSize(stream.get(), 2, &contents));
}
TEST_F(FileUtilTest, ReadStreamToStringNullStream) {
std::string contents;
EXPECT_FALSE(ReadStreamToString(nullptr, &contents));
}
TEST_F(FileUtilTest, TouchFile) {
FilePath data_dir =
temp_dir_.GetPath().Append(FILE_PATH_LITERAL("FilePathTest"));
if (PathExists(data_dir)) {
ASSERT_TRUE(DeletePathRecursively(data_dir));
}
ASSERT_TRUE(CreateDirectory(data_dir));
FilePath foobar(data_dir.Append(FILE_PATH_LITERAL("foobar.txt")));
std::string data("hello");
ASSERT_TRUE(WriteFile(foobar, data));
Time access_time;
ASSERT_TRUE(Time::FromString("Wed, 16 Nov 1994, 00:00:00", &access_time));
Time modification_time;
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));
#if !BUILDFLAG(IS_FUCHSIA)
EXPECT_EQ(access_time.ToInternalValue(),
file_info.last_accessed.ToInternalValue());
#endif
EXPECT_EQ(modification_time.ToInternalValue(),
file_info.last_modified.ToInternalValue());
}
TEST_F(FileUtilTest, WriteFileSpanVariant) {
FilePath empty_file =
temp_dir_.GetPath().Append(FILE_PATH_LITERAL("empty_file"));
ASSERT_FALSE(PathExists(empty_file));
EXPECT_TRUE(WriteFile(empty_file, base::span<const uint8_t>()));
EXPECT_TRUE(PathExists(empty_file));
std::string data = "not empty";
EXPECT_TRUE(ReadFileToString(empty_file, &data));
EXPECT_TRUE(data.empty());
FilePath write_span_file =
temp_dir_.GetPath().Append(FILE_PATH_LITERAL("write_span_file"));
ASSERT_FALSE(PathExists(write_span_file));
static constexpr uint8_t kInput[] = {'h', 'e', 'l', 'l', 'o'};
EXPECT_TRUE(WriteFile(write_span_file, kInput));
EXPECT_TRUE(PathExists(write_span_file));
data.clear();
EXPECT_TRUE(ReadFileToString(write_span_file, &data));
EXPECT_EQ("hello", data);
}
TEST_F(FileUtilTest, WriteFileStringVariant) {
FilePath empty_file =
temp_dir_.GetPath().Append(FILE_PATH_LITERAL("empty_file"));
ASSERT_FALSE(PathExists(empty_file));
EXPECT_TRUE(WriteFile(empty_file, ""));
EXPECT_TRUE(PathExists(empty_file));
std::string data = "not empty";
EXPECT_TRUE(ReadFileToString(empty_file, &data));
EXPECT_TRUE(data.empty());
FilePath write_span_file =
temp_dir_.GetPath().Append(FILE_PATH_LITERAL("write_string_file"));
ASSERT_FALSE(PathExists(write_span_file));
EXPECT_TRUE(WriteFile(write_span_file, "world"));
EXPECT_TRUE(PathExists(write_span_file));
data.clear();
EXPECT_TRUE(ReadFileToString(write_span_file, &data));
EXPECT_EQ("world", data);
}
TEST_F(FileUtilTest, IsDirectoryEmpty) {
FilePath empty_dir =
temp_dir_.GetPath().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));
EXPECT_FALSE(IsDirectoryEmpty(empty_dir));
}
#if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
TEST_F(FileUtilTest, SetNonBlocking) {
const int kBogusFd = 99999;
EXPECT_FALSE(SetNonBlocking(kBogusFd));
FilePath path;
ASSERT_TRUE(PathService::Get(DIR_TEST_DATA, &path));
path = path.Append(FPL("file_util")).Append(FPL("original.txt"));
ScopedFD fd(open(path.value().c_str(), O_RDONLY));
ASSERT_GE(fd.get(), 0);
EXPECT_TRUE(SetNonBlocking(fd.get()));
}
TEST_F(FileUtilTest, SetCloseOnExec) {
const int kBogusFd = 99999;
EXPECT_FALSE(SetCloseOnExec(kBogusFd));
FilePath path;
ASSERT_TRUE(PathService::Get(DIR_TEST_DATA, &path));
path = path.Append(FPL("file_util")).Append(FPL("original.txt"));
ScopedFD fd(open(path.value().c_str(), O_RDONLY));
ASSERT_GE(fd.get(), 0);
EXPECT_TRUE(SetCloseOnExec(fd.get()));
}
#endif
#if BUILDFLAG(IS_MAC)
class VerifyPathControlledByUserTest : public FileUtilTest {
protected:
void SetUp() override {
FileUtilTest::SetUp();
base_dir_ = temp_dir_.GetPath().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.");
stat_wrapper_t stat_buf;
ASSERT_EQ(0, File::Stat(base_dir_, &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());
int enabled_permissions =
FILE_PERMISSION_USER_MASK | FILE_PERMISSION_GROUP_MASK;
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) {
FilePath does_not_exist =
base_dir_.AppendASCII("does").AppendASCII("not").AppendASCII("exist");
EXPECT_FALSE(
VerifyPathControlledByUser(base_dir_, does_not_exist, uid_, ok_gids_));
EXPECT_FALSE(VerifyPathControlledByUser(sub_dir_, base_dir_, uid_, ok_gids_));
FilePath empty;
EXPECT_FALSE(VerifyPathControlledByUser(empty, base_dir_, uid_, ok_gids_));
EXPECT_TRUE(VerifyPathControlledByUser(base_dir_, sub_dir_, uid_, ok_gids_));
}
TEST_F(VerifyPathControlledByUserTest, Symlinks) {
FilePath file_link = base_dir_.AppendASCII("file_link");
ASSERT_TRUE(CreateSymbolicLink(text_file_, file_link))
<< "Failed to create symlink.";
EXPECT_FALSE(
VerifyPathControlledByUser(base_dir_, file_link, uid_, ok_gids_));
EXPECT_FALSE(
VerifyPathControlledByUser(file_link, file_link, uid_, ok_gids_));
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(VerifyPathControlledByUser(base_dir_, file_path_with_link, uid_,
ok_gids_));
EXPECT_FALSE(VerifyPathControlledByUser(link_to_sub_dir, file_path_with_link,
uid_, ok_gids_));
EXPECT_TRUE(VerifyPathControlledByUser(file_path_with_link,
file_path_with_link, uid_, ok_gids_));
}
TEST_F(VerifyPathControlledByUserTest, OwnershipChecks) {
uid_t bad_uid = uid_ + 1;
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));
EXPECT_TRUE(VerifyPathControlledByUser(base_dir_, sub_dir_, uid_, ok_gids_));
EXPECT_TRUE(
VerifyPathControlledByUser(base_dir_, text_file_, uid_, ok_gids_));
EXPECT_TRUE(VerifyPathControlledByUser(sub_dir_, text_file_, uid_, ok_gids_));
EXPECT_FALSE(
VerifyPathControlledByUser(base_dir_, sub_dir_, bad_uid, ok_gids_));
EXPECT_FALSE(
VerifyPathControlledByUser(base_dir_, text_file_, bad_uid, ok_gids_));
EXPECT_FALSE(
VerifyPathControlledByUser(sub_dir_, text_file_, bad_uid, ok_gids_));
EXPECT_FALSE(
VerifyPathControlledByUser(base_dir_, sub_dir_, uid_, bad_gids_));
EXPECT_FALSE(
VerifyPathControlledByUser(base_dir_, text_file_, uid_, bad_gids_));
EXPECT_FALSE(
VerifyPathControlledByUser(sub_dir_, text_file_, uid_, bad_gids_));
}
TEST_F(VerifyPathControlledByUserTest, GroupWriteTest) {
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));
EXPECT_TRUE(VerifyPathControlledByUser(base_dir_, sub_dir_, uid_, ok_gids_));
EXPECT_TRUE(
VerifyPathControlledByUser(base_dir_, text_file_, uid_, ok_gids_));
EXPECT_TRUE(VerifyPathControlledByUser(sub_dir_, text_file_, uid_, ok_gids_));
EXPECT_TRUE(VerifyPathControlledByUser(base_dir_, sub_dir_, uid_, bad_gids_));
EXPECT_TRUE(
VerifyPathControlledByUser(base_dir_, text_file_, uid_, bad_gids_));
EXPECT_TRUE(
VerifyPathControlledByUser(sub_dir_, text_file_, uid_, bad_gids_));
std::set<gid_t> no_gids;
EXPECT_TRUE(VerifyPathControlledByUser(base_dir_, sub_dir_, uid_, no_gids));
EXPECT_TRUE(VerifyPathControlledByUser(base_dir_, text_file_, uid_, no_gids));
EXPECT_TRUE(VerifyPathControlledByUser(sub_dir_, text_file_, uid_, no_gids));
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));
EXPECT_TRUE(VerifyPathControlledByUser(base_dir_, sub_dir_, uid_, ok_gids_));
EXPECT_TRUE(
VerifyPathControlledByUser(base_dir_, text_file_, uid_, ok_gids_));
EXPECT_TRUE(VerifyPathControlledByUser(sub_dir_, text_file_, uid_, ok_gids_));
EXPECT_FALSE(
VerifyPathControlledByUser(base_dir_, sub_dir_, uid_, bad_gids_));
EXPECT_FALSE(
VerifyPathControlledByUser(base_dir_, text_file_, uid_, bad_gids_));
EXPECT_FALSE(
VerifyPathControlledByUser(sub_dir_, text_file_, uid_, bad_gids_));
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(
VerifyPathControlledByUser(base_dir_, sub_dir_, uid_, multiple_gids));
EXPECT_TRUE(
VerifyPathControlledByUser(base_dir_, text_file_, uid_, multiple_gids));
EXPECT_TRUE(
VerifyPathControlledByUser(sub_dir_, text_file_, uid_, multiple_gids));
}
TEST_F(VerifyPathControlledByUserTest, WriteBitChecks) {
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));
EXPECT_TRUE(VerifyPathControlledByUser(base_dir_, sub_dir_, uid_, ok_gids_));
EXPECT_TRUE(
VerifyPathControlledByUser(base_dir_, text_file_, uid_, ok_gids_));
EXPECT_TRUE(VerifyPathControlledByUser(sub_dir_, text_file_, uid_, ok_gids_));
ASSERT_NO_FATAL_FAILURE(ChangePosixFilePermissions(base_dir_, S_IWOTH, 0u));
EXPECT_FALSE(VerifyPathControlledByUser(base_dir_, sub_dir_, uid_, ok_gids_));
EXPECT_FALSE(
VerifyPathControlledByUser(base_dir_, text_file_, uid_, ok_gids_));
EXPECT_TRUE(VerifyPathControlledByUser(sub_dir_, text_file_, uid_, ok_gids_));
ASSERT_NO_FATAL_FAILURE(ChangePosixFilePermissions(sub_dir_, S_IWOTH, 0u));
EXPECT_FALSE(VerifyPathControlledByUser(base_dir_, sub_dir_, uid_, ok_gids_));
EXPECT_FALSE(
VerifyPathControlledByUser(base_dir_, text_file_, uid_, ok_gids_));
EXPECT_FALSE(
VerifyPathControlledByUser(sub_dir_, text_file_, uid_, ok_gids_));
ASSERT_NO_FATAL_FAILURE(ChangePosixFilePermissions(text_file_, S_IWOTH, 0u));
EXPECT_FALSE(VerifyPathControlledByUser(base_dir_, sub_dir_, uid_, ok_gids_));
EXPECT_FALSE(
VerifyPathControlledByUser(base_dir_, text_file_, uid_, ok_gids_));
EXPECT_FALSE(
VerifyPathControlledByUser(sub_dir_, text_file_, uid_, ok_gids_));
ASSERT_NO_FATAL_FAILURE(ChangePosixFilePermissions(sub_dir_, 0u, S_IWOTH));
EXPECT_FALSE(VerifyPathControlledByUser(base_dir_, sub_dir_, uid_, ok_gids_));
EXPECT_FALSE(
VerifyPathControlledByUser(base_dir_, text_file_, uid_, ok_gids_));
EXPECT_FALSE(
VerifyPathControlledByUser(sub_dir_, text_file_, uid_, ok_gids_));
ASSERT_NO_FATAL_FAILURE(ChangePosixFilePermissions(base_dir_, 0u, S_IWOTH));
EXPECT_TRUE(VerifyPathControlledByUser(base_dir_, sub_dir_, uid_, ok_gids_));
EXPECT_FALSE(
VerifyPathControlledByUser(base_dir_, text_file_, uid_, ok_gids_));
EXPECT_FALSE(
VerifyPathControlledByUser(sub_dir_, text_file_, uid_, ok_gids_));
ASSERT_NO_FATAL_FAILURE(ChangePosixFilePermissions(text_file_, 0u, S_IWOTH));
EXPECT_TRUE(VerifyPathControlledByUser(base_dir_, sub_dir_, uid_, ok_gids_));
EXPECT_TRUE(
VerifyPathControlledByUser(base_dir_, text_file_, uid_, ok_gids_));
EXPECT_TRUE(VerifyPathControlledByUser(sub_dir_, text_file_, uid_, ok_gids_));
}
#endif
#if BUILDFLAG(IS_ANDROID)
TEST_F(FileUtilTest, ValidContentUriTest) {
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"));
std::optional<int64_t> image_size = GetFileSize(image_file);
ASSERT_TRUE(image_size.has_value());
ASSERT_GT(image_size.value(), 0);
FilePath path = InsertImageIntoMediaStore(image_file);
EXPECT_TRUE(path.IsContentUri());
EXPECT_TRUE(PathExists(path));
std::optional<int64_t> content_uri_size = GetFileSize(path);
ASSERT_TRUE(content_uri_size.has_value());
EXPECT_EQ(image_size.value(), content_uri_size.value());
File file(path, File::FLAG_OPEN | File::FLAG_READ);
EXPECT_TRUE(file.IsValid());
auto buffer = std::make_unique<char[]>(image_size.value());
EXPECT_TRUE(
UNSAFE_BUFFERS(file.ReadAtCurrentPos(buffer.get(), image_size.value())));
}
TEST_F(FileUtilTest, WriteContentUri) {
FilePath path = temp_dir_.GetPath().Append("file.txt");
ASSERT_TRUE(WriteFile(path, "file-content"));
FilePath content_uri =
*test::android::GetContentUriFromCacheDirFilePath(path);
File file = File(content_uri, File::FLAG_CREATE_ALWAYS | File::FLAG_WRITE);
EXPECT_TRUE(file.IsValid());
std::optional<int64_t> size = GetFileSize(path);
ASSERT_TRUE(size.has_value());
EXPECT_EQ(size.value(), 0);
EXPECT_EQ(*file.WriteAtCurrentPos(byte_span_from_cstring("123")), 3u);
EXPECT_TRUE(file.Flush());
size = GetFileSize(path);
ASSERT_TRUE(size.has_value());
EXPECT_EQ(size.value(), 3);
}
TEST_F(FileUtilTest, NonExistentContentUriTest) {
FilePath path("content://foo.bar");
EXPECT_TRUE(path.IsContentUri());
EXPECT_FALSE(PathExists(path));
EXPECT_FALSE(GetFileSize(path).has_value());
File file(path, File::FLAG_OPEN | File::FLAG_READ);
EXPECT_FALSE(file.IsValid());
}
TEST_F(FileUtilTest, CreateDirectoryOnlyCheckMissingSubpaths) {
FilePath dir = PathService::CheckedGet(DIR_ANDROID_APP_DATA);
EXPECT_TRUE(CreateDirectory(dir));
}
#endif
#if BUILDFLAG(IS_WIN) && BUILDFLAG(GOOGLE_CHROME_BRANDING) && \
defined(ARCH_CPU_32_BITS)
#define FLAKY_327582285 1
#endif
#if defined(FLAKY_327582285)
#define MAYBE_PreReadFileExistingFileNoSize \
DISABLED_PreReadFileExistingFileNoSize
#else
#define MAYBE_PreReadFileExistingFileNoSize PreReadFileExistingFileNoSize
#endif
TEST_F(FileUtilTest, MAYBE_PreReadFileExistingFileNoSize) {
FilePath text_file = temp_dir_.GetPath().Append(FPL("text_file"));
CreateTextFile(text_file, bogus_content);
EXPECT_TRUE(
PreReadFile(text_file, false, false));
}
#if defined(FLAKY_327582285)
#define MAYBE_PreReadFileExistingFileExactSize \
DISABLED_PreReadFileExistingFileExactSize
#else
#define MAYBE_PreReadFileExistingFileExactSize PreReadFileExistingFileExactSize
#endif
TEST_F(FileUtilTest, MAYBE_PreReadFileExistingFileExactSize) {
FilePath text_file = temp_dir_.GetPath().Append(FPL("text_file"));
CreateTextFile(text_file, bogus_content);
EXPECT_TRUE(PreReadFile(text_file, false,
false, std::size(bogus_content)));
}
#if defined(FLAKY_327582285)
#define MAYBE_PreReadFileExistingFileOverSized \
DISABLED_PreReadFileExistingFileOverSized
#else
#define MAYBE_PreReadFileExistingFileOverSized PreReadFileExistingFileOverSized
#endif
TEST_F(FileUtilTest, MAYBE_PreReadFileExistingFileOverSized) {
FilePath text_file = temp_dir_.GetPath().Append(FPL("text_file"));
CreateTextFile(text_file, bogus_content);
EXPECT_TRUE(PreReadFile(text_file, false,
false, std::size(bogus_content) * 2));
}
#if defined(FLAKY_327582285)
#define MAYBE_PreReadFileExistingFileUnderSized \
DISABLED_PreReadFileExistingFileUnderSized
#else
#define MAYBE_PreReadFileExistingFileUnderSized \
PreReadFileExistingFileUnderSized
#endif
TEST_F(FileUtilTest, MAYBE_PreReadFileExistingFileUnderSized) {
FilePath text_file = temp_dir_.GetPath().Append(FPL("text_file"));
CreateTextFile(text_file, bogus_content);
EXPECT_TRUE(PreReadFile(text_file, false,
false, std::size(bogus_content) / 2));
}
TEST_F(FileUtilTest, PreReadFileExistingFileZeroSize) {
FilePath text_file = temp_dir_.GetPath().Append(FPL("text_file"));
CreateTextFile(text_file, bogus_content);
EXPECT_TRUE(PreReadFile(text_file, false,
false, 0));
}
TEST_F(FileUtilTest, PreReadFileExistingEmptyFileNoSize) {
FilePath text_file = temp_dir_.GetPath().Append(FPL("text_file"));
CreateTextFile(text_file, L"");
PreReadFile(text_file, false, false);
}
TEST_F(FileUtilTest, PreReadFileExistingEmptyFileZeroSize) {
FilePath text_file = temp_dir_.GetPath().Append(FPL("text_file"));
CreateTextFile(text_file, L"");
EXPECT_TRUE(PreReadFile(text_file, false,
false, 0));
}
TEST_F(FileUtilTest, PreReadFileInexistentFile) {
FilePath inexistent_file = temp_dir_.GetPath().Append(FPL("inexistent_file"));
EXPECT_FALSE(PreReadFile(inexistent_file, false,
false));
}
#if defined(FLAKY_327582285)
#define MAYBE_PreReadFileExecutable DISABLED_PreReadFileExecutable
#else
#define MAYBE_PreReadFileExecutable PreReadFileExecutable
#endif
TEST_F(FileUtilTest, MAYBE_PreReadFileExecutable) {
FilePath exe_data_dir;
ASSERT_TRUE(PathService::Get(DIR_TEST_DATA, &exe_data_dir));
exe_data_dir = exe_data_dir.Append(FPL("pe_image_reader"));
ASSERT_TRUE(PathExists(exe_data_dir));
const FilePath test_exe = exe_data_dir.Append(FPL("signed.exe"));
EXPECT_TRUE(
PreReadFile(test_exe, true, false));
}
#if defined(FLAKY_327582285)
#define MAYBE_PreReadFileWithSequentialAccess \
DISABLED_PreReadFileWithSequentialAccess
#else
#define MAYBE_PreReadFileWithSequentialAccess PreReadFileWithSequentialAccess
#endif
TEST_F(FileUtilTest, MAYBE_PreReadFileWithSequentialAccess) {
FilePath text_file = temp_dir_.GetPath().Append(FPL("text_file"));
CreateTextFile(text_file, bogus_content);
EXPECT_TRUE(
PreReadFile(text_file, false, true));
}
#undef FLAKY_327582285
TEST(FileUtilMultiThreadedTest, MultiThreadedTempFiles) {
#if BUILDFLAG(IS_FUCHSIA)
constexpr int kNumThreads = 8;
#else
constexpr int kNumThreads = 64;
#endif
constexpr int kNumWritesPerThread = 32;
std::unique_ptr<Thread> threads[kNumThreads];
for (auto& thread : threads) {
thread = std::make_unique<Thread>("test worker");
thread->Start();
}
for (auto& thread : threads) {
thread->WaitUntilThreadStarted();
}
const RepeatingClosure open_write_close_read = BindRepeating([] {
FilePath output_filename;
ScopedFILE output_file(CreateAndOpenTemporaryStream(&output_filename));
EXPECT_TRUE(output_file);
const std::string content = Uuid::GenerateRandomV4().AsLowercaseString();
#if BUILDFLAG(IS_WIN)
HANDLE handle =
reinterpret_cast<HANDLE>(_get_osfhandle(_fileno(output_file.get())));
DWORD bytes_written = 0;
::WriteFile(handle, content.c_str(), content.length(), &bytes_written,
NULL);
#else
size_t bytes_written =
::write(::fileno(output_file.get()), content.c_str(), content.length());
#endif
EXPECT_EQ(content.length(), bytes_written);
::fflush(output_file.get());
output_file.reset();
std::string output_file_contents;
EXPECT_TRUE(ReadFileToString(output_filename, &output_file_contents))
<< output_filename;
EXPECT_EQ(content, output_file_contents);
DeleteFile(output_filename);
});
for (int i = 0; i < kNumWritesPerThread; ++i) {
for (auto& thread : threads) {
thread->task_runner()->PostTask(FROM_HERE, open_write_close_read);
}
}
for (auto& thread : threads) {
thread->Stop();
}
}
#if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
TEST(ScopedFD, ScopedFDDoesClose) {
int fds[2];
char c = 0;
ASSERT_EQ(0, pipe(fds));
const int write_end = fds[1];
ScopedFD read_end_closer(fds[0]);
{ ScopedFD write_end_closer(fds[1]); }
int ret = close(write_end);
EXPECT_EQ(-1, ret);
EXPECT_EQ(EBADF, errno);
ASSERT_EQ(0, fcntl(fds[0], F_SETFL, O_NONBLOCK));
EXPECT_EQ(0, read(fds[0], &c, 1));
}
#if defined(GTEST_HAS_DEATH_TEST)
void CloseWithScopedFD(int fd) {
ScopedFD fd_closer(fd);
}
#endif
TEST(ScopedFD, ScopedFDCrashesOnCloseFailure) {
int fds[2];
ASSERT_EQ(0, pipe(fds));
ScopedFD read_end_closer(fds[0]);
EXPECT_EQ(0, IGNORE_EINTR(close(fds[1])));
#if defined(GTEST_HAS_DEATH_TEST)
EXPECT_DEATH(CloseWithScopedFD(fds[1]), "");
#endif
}
#endif
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID)
TEST_F(FileUtilTest, CopyFileContentsWithSendfile) {
FilePath file_name_from = temp_dir_.GetPath().Append(
FILE_PATH_LITERAL("copy_contents_file_in.txt"));
FilePath file_name_to = temp_dir_.GetPath().Append(
FILE_PATH_LITERAL("copy_contents_file_out.txt"));
const std::wstring from_contents(L"0123456789ABCDEF");
CreateTextFile(file_name_from, from_contents);
ASSERT_TRUE(PathExists(file_name_from));
const std::wstring to_contents(L"GHIJKL");
CreateTextFile(file_name_to, to_contents);
ASSERT_TRUE(PathExists(file_name_to));
File from(file_name_from, File::FLAG_OPEN | File::FLAG_READ);
ASSERT_TRUE(from.IsValid());
File to(file_name_to, File::FLAG_OPEN | File::FLAG_WRITE);
ASSERT_TRUE(to.IsValid());
ASSERT_EQ(from.Seek(File::Whence::FROM_BEGIN, 1), 1);
ASSERT_EQ(to.Seek(File::Whence::FROM_BEGIN, 1), 1);
bool retry_slow = false;
ASSERT_TRUE(internal::CopyFileContentsWithSendfile(from, to, retry_slow));
from.Close();
to.Close();
EXPECT_EQ(L"G123456789ABCDEF", ReadTextFile(file_name_to));
}
TEST_F(FileUtilTest, CopyFileContentsWithSendfileEmpty) {
FilePath file_name_from = temp_dir_.GetPath().Append(
FILE_PATH_LITERAL("copy_contents_file_in.txt"));
FilePath file_name_to = temp_dir_.GetPath().Append(
FILE_PATH_LITERAL("copy_contents_file_out.txt"));
const std::wstring from_contents(L"");
CreateTextFile(file_name_from, from_contents);
ASSERT_TRUE(PathExists(file_name_from));
const std::wstring to_contents(L"");
CreateTextFile(file_name_to, to_contents);
ASSERT_TRUE(PathExists(file_name_to));
File from(file_name_from, File::FLAG_OPEN | File::FLAG_READ);
ASSERT_TRUE(from.IsValid());
File to(file_name_to, File::FLAG_OPEN | File::FLAG_WRITE);
ASSERT_TRUE(to.IsValid());
bool retry_slow = false;
ASSERT_FALSE(internal::CopyFileContentsWithSendfile(from, to, retry_slow));
ASSERT_TRUE(retry_slow);
from.Close();
to.Close();
EXPECT_EQ(L"", ReadTextFile(file_name_to));
}
TEST_F(FileUtilTest, CopyFileContentsWithSendfilePipe) {
FilePath file_name_to = temp_dir_.GetPath().Append(
FILE_PATH_LITERAL("copy_contents_file_out.txt"));
File to(file_name_to,
File::FLAG_OPEN | File::FLAG_WRITE | File::FLAG_CREATE_ALWAYS);
ASSERT_TRUE(to.IsValid());
int fd[2];
ASSERT_EQ(pipe2(fd, O_CLOEXEC), 0);
const char* buf = "hello world";
ASSERT_EQ(write(fd[1], buf, sizeof(buf)), static_cast<int>(sizeof(buf)));
bool retry_slow = false;
base::PlatformFile pipe_read_end(fd[0]);
base::File pipe_read(pipe_read_end);
ASSERT_FALSE(
internal::CopyFileContentsWithSendfile(pipe_read, to, retry_slow));
ASSERT_TRUE(retry_slow);
}
TEST_F(FileUtilTest, CopyFileContentsWithSendfileSocket) {
int sock[2];
ASSERT_EQ(socketpair(AF_UNIX, SOCK_STREAM, 0, sock), 0);
FilePath file_name_from = temp_dir_.GetPath().Append(
FILE_PATH_LITERAL("copy_contents_file_in.txt"));
FilePath file_name_to = temp_dir_.GetPath().Append(
FILE_PATH_LITERAL("copy_contents_file_out.txt"));
const std::wstring from_contents(L"0123456789ABCDEF");
CreateTextFile(file_name_from, from_contents);
ASSERT_TRUE(PathExists(file_name_from));
File from(file_name_from, File::FLAG_OPEN | File::FLAG_READ);
ASSERT_TRUE(from.IsValid());
base::PlatformFile to_file(sock[0]);
base::File to_sock(to_file);
bool retry_slow = false;
ASSERT_TRUE(
internal::CopyFileContentsWithSendfile(from, to_sock, retry_slow));
base::PlatformFile from_sock_file(sock[1]);
base::File from_sock(from_sock_file);
File to(file_name_to,
File::FLAG_OPEN | File::FLAG_WRITE | File::FLAG_CREATE_ALWAYS);
ASSERT_TRUE(to.IsValid());
ASSERT_FALSE(
internal::CopyFileContentsWithSendfile(from_sock, to, retry_slow));
ASSERT_TRUE(retry_slow);
}
TEST_F(FileUtilTest, CopyFileContentsWithSendfileSeqFile) {
for (auto* const file : {"/proc/meminfo", "/proc/self/cmdline"}) {
FilePath proc_file_from(file);
File from(proc_file_from, File::FLAG_OPEN | File::FLAG_READ);
ASSERT_TRUE(from.IsValid()) << "could not open " << file;
FilePath file_name_to = temp_dir_.GetPath().Append(
FILE_PATH_LITERAL("copy_contents_file_out.txt"));
File to(file_name_to,
File::FLAG_OPEN | File::FLAG_WRITE | File::FLAG_CREATE_ALWAYS);
ASSERT_TRUE(to.IsValid());
bool retry_slow = false;
ASSERT_FALSE(internal::CopyFileContentsWithSendfile(from, to, retry_slow))
<< proc_file_from << " should have failed";
ASSERT_TRUE(retry_slow)
<< "retry slow for " << proc_file_from << " should be set";
ASSERT_TRUE(base::CopyFileContents(from, to));
ASSERT_GT(to.GetLength(), 0);
ASSERT_TRUE(base::DeleteFile(file_name_to));
}
}
#endif
TEST_F(FileUtilTest, CreatingFileWithSameNameAfterDelete) {
static constexpr FilePath::CharType kFileBaseName[] =
FILE_PATH_LITERAL("file");
const FilePath file_path = temp_dir_.GetPath().Append(kFileBaseName);
const auto byte_span = byte_span_from_cstring("CONTENT");
const auto file_flags =
File::FLAG_OPEN_ALWAYS | File::FLAG_WRITE | File::FLAG_WIN_SHARE_DELETE;
File first_file(file_path, file_flags);
ASSERT_TRUE(first_file.IsValid());
ASSERT_THAT(first_file.Write(0, byte_span),
testing::Optional(byte_span.size()));
ASSERT_TRUE(DeleteFile(file_path));
File second_file(file_path, file_flags);
ASSERT_TRUE(second_file.IsValid());
ASSERT_EQ(second_file.GetLength(), 0);
}
}
}