• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2012 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "base/files/file_util.h"
6 
7 #include <stddef.h>
8 #include <stdint.h>
9 #include <stdio.h>
10 
11 #include <algorithm>
12 #include <fstream>
13 #include <initializer_list>
14 #include <memory>
15 #include <set>
16 #include <utility>
17 #include <vector>
18 
19 #include "base/base_paths.h"
20 #include "base/command_line.h"
21 #include "base/environment.h"
22 #include "base/features.h"
23 #include "base/files/file.h"
24 #include "base/files/file_enumerator.h"
25 #include "base/files/file_path.h"
26 #include "base/files/platform_file.h"
27 #include "base/files/scoped_file.h"
28 #include "base/files/scoped_temp_dir.h"
29 #include "base/functional/bind.h"
30 #include "base/functional/callback_helpers.h"
31 #include "base/logging.h"
32 #include "base/path_service.h"
33 #include "base/rand_util.h"
34 #include "base/scoped_environment_variable_override.h"
35 #include "base/strings/string_util.h"
36 #include "base/strings/stringprintf.h"
37 #include "base/strings/utf_string_conversions.h"
38 #include "base/test/bind.h"
39 #include "base/test/multiprocess_test.h"
40 #include "base/test/scoped_feature_list.h"
41 #include "base/test/task_environment.h"
42 #include "base/test/test_file_util.h"
43 #include "base/test/test_timeouts.h"
44 #include "base/threading/platform_thread.h"
45 #include "base/threading/thread.h"
46 #include "base/time/time.h"
47 #include "base/uuid.h"
48 #include "build/build_config.h"
49 #include "testing/gtest/include/gtest/gtest.h"
50 #include "testing/multiprocess_func_list.h"
51 #include "testing/platform_test.h"
52 
53 #if BUILDFLAG(IS_WIN)
54 #include <shellapi.h>
55 #include <shlobj.h>
56 #include <tchar.h>
57 #include <windows.h>
58 #include <winioctl.h>
59 #include "base/scoped_native_library.h"
60 #include "base/strings/string_number_conversions.h"
61 #include "base/test/gtest_util.h"
62 #include "base/win/scoped_handle.h"
63 #include "base/win/win_util.h"
64 #endif
65 
66 #if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
67 #include <errno.h>
68 #include <fcntl.h>
69 #include <sys/ioctl.h>
70 #include <sys/types.h>
71 #include <unistd.h>
72 #endif
73 
74 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID)
75 #include <sys/socket.h>
76 #endif
77 
78 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
79 #include <linux/fs.h>
80 #endif
81 
82 #if BUILDFLAG(IS_ANDROID)
83 #include "base/android/content_uri_utils.h"
84 #endif
85 
86 #if BUILDFLAG(IS_FUCHSIA)
87 #include "base/test/scoped_dev_zero_fuchsia.h"
88 #endif
89 
90 // This macro helps avoid wrapped lines in the test structs.
91 #define FPL(x) FILE_PATH_LITERAL(x)
92 
93 namespace base {
94 
95 namespace {
96 
97 const size_t kLargeFileSize = (1 << 16) + 3;
98 
99 // To test that NormalizeFilePath() deals with NTFS reparse points correctly,
100 // we need functions to create and delete reparse points.
101 #if BUILDFLAG(IS_WIN)
102 typedef struct _REPARSE_DATA_BUFFER {
103   ULONG  ReparseTag;
104   USHORT  ReparseDataLength;
105   USHORT  Reserved;
106   union {
107     struct {
108       USHORT SubstituteNameOffset;
109       USHORT SubstituteNameLength;
110       USHORT PrintNameOffset;
111       USHORT PrintNameLength;
112       ULONG Flags;
113       WCHAR PathBuffer[1];
114     } SymbolicLinkReparseBuffer;
115     struct {
116       USHORT SubstituteNameOffset;
117       USHORT SubstituteNameLength;
118       USHORT PrintNameOffset;
119       USHORT PrintNameLength;
120       WCHAR PathBuffer[1];
121     } MountPointReparseBuffer;
122     struct {
123       UCHAR DataBuffer[1];
124     } GenericReparseBuffer;
125   };
126 } REPARSE_DATA_BUFFER, *PREPARSE_DATA_BUFFER;
127 
128 // Sets a reparse point. |source| will now point to |target|. Returns true if
129 // the call succeeds, false otherwise.
SetReparsePoint(HANDLE source,const FilePath & target_path)130 bool SetReparsePoint(HANDLE source, const FilePath& target_path) {
131   std::wstring kPathPrefix = FILE_PATH_LITERAL("\\??\\");
132   std::wstring target_str;
133   // The juction will not work if the target path does not start with \??\ .
134   if (kPathPrefix != target_path.value().substr(0, kPathPrefix.size()))
135     target_str += kPathPrefix;
136   target_str += target_path.value();
137   const wchar_t* target = target_str.c_str();
138   USHORT size_target = static_cast<USHORT>(wcslen(target)) * sizeof(target[0]);
139   char buffer[2000] = {0};
140   DWORD returned;
141 
142   REPARSE_DATA_BUFFER* data = reinterpret_cast<REPARSE_DATA_BUFFER*>(buffer);
143 
144   data->ReparseTag = 0xa0000003;
145   memcpy(data->MountPointReparseBuffer.PathBuffer, target, size_target + 2);
146 
147   data->MountPointReparseBuffer.SubstituteNameLength = size_target;
148   data->MountPointReparseBuffer.PrintNameOffset = size_target + 2;
149   data->ReparseDataLength = size_target + 4 + 8;
150 
151   int data_size = data->ReparseDataLength + 8;
152 
153   if (!DeviceIoControl(source, FSCTL_SET_REPARSE_POINT, &buffer, data_size,
154                        NULL, 0, &returned, NULL)) {
155     return false;
156   }
157   return true;
158 }
159 
160 // Delete the reparse point referenced by |source|. Returns true if the call
161 // succeeds, false otherwise.
DeleteReparsePoint(HANDLE source)162 bool DeleteReparsePoint(HANDLE source) {
163   DWORD returned;
164   REPARSE_DATA_BUFFER data = {0};
165   data.ReparseTag = 0xa0000003;
166   if (!DeviceIoControl(source, FSCTL_DELETE_REPARSE_POINT, &data, 8, NULL, 0,
167                        &returned, NULL)) {
168     return false;
169   }
170   return true;
171 }
172 
173 // Method that wraps the win32 GetShortPathName API. Returns an empty path on
174 // error.
MakeShortFilePath(const FilePath & input)175 FilePath MakeShortFilePath(const FilePath& input) {
176   DWORD path_short_len = ::GetShortPathName(input.value().c_str(), nullptr, 0);
177   if (path_short_len == 0UL)
178     return FilePath();
179 
180   std::wstring path_short_str;
181   path_short_len = ::GetShortPathName(
182       input.value().c_str(), WriteInto(&path_short_str, path_short_len),
183       path_short_len);
184   if (path_short_len == 0UL)
185     return FilePath();
186 
187   return FilePath(path_short_str);
188 }
189 
190 // Manages a reparse point for a test.
191 class ReparsePoint {
192  public:
193   // Creates a reparse point from |source| (an empty directory) to |target|.
ReparsePoint(const FilePath & source,const FilePath & target)194   ReparsePoint(const FilePath& source, const FilePath& target) {
195     dir_.Set(
196         ::CreateFile(source.value().c_str(), GENERIC_READ | GENERIC_WRITE,
197                      FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
198                      NULL, OPEN_EXISTING,
199                      FILE_FLAG_BACKUP_SEMANTICS,  // Needed to open a directory.
200                      NULL));
201     created_ = dir_.is_valid() && SetReparsePoint(dir_.get(), target);
202   }
203   ReparsePoint(const ReparsePoint&) = delete;
204   ReparsePoint& operator=(const ReparsePoint&) = delete;
205 
~ReparsePoint()206   ~ReparsePoint() {
207     if (created_)
208       DeleteReparsePoint(dir_.get());
209   }
210 
IsValid()211   bool IsValid() { return created_; }
212 
213  private:
214   win::ScopedHandle dir_;
215   bool created_;
216 };
217 
218 #endif
219 
220 #if BUILDFLAG(IS_MAC)
221 // Provide a simple way to change the permissions bits on |path| in tests.
222 // ASSERT failures will return, but not stop the test.  Caller should wrap
223 // calls to this function in ASSERT_NO_FATAL_FAILURE().
ChangePosixFilePermissions(const FilePath & path,int mode_bits_to_set,int mode_bits_to_clear)224 void ChangePosixFilePermissions(const FilePath& path,
225                                 int mode_bits_to_set,
226                                 int mode_bits_to_clear) {
227   ASSERT_FALSE(mode_bits_to_set & mode_bits_to_clear)
228       << "Can't set and clear the same bits.";
229 
230   int mode = 0;
231   ASSERT_TRUE(GetPosixFilePermissions(path, &mode));
232   mode |= mode_bits_to_set;
233   mode &= ~mode_bits_to_clear;
234   ASSERT_TRUE(SetPosixFilePermissions(path, mode));
235 }
236 #endif  // BUILDFLAG(IS_MAC)
237 
238 // Fuchsia doesn't support file permissions.
239 #if !BUILDFLAG(IS_FUCHSIA)
240 // Sets the source file to read-only.
SetReadOnly(const FilePath & path,bool read_only)241 void SetReadOnly(const FilePath& path, bool read_only) {
242 #if BUILDFLAG(IS_WIN)
243   // On Windows, it involves setting/removing the 'readonly' bit.
244   DWORD attrs = GetFileAttributes(path.value().c_str());
245   ASSERT_NE(INVALID_FILE_ATTRIBUTES, attrs);
246   ASSERT_TRUE(SetFileAttributes(
247       path.value().c_str(), read_only ? (attrs | FILE_ATTRIBUTE_READONLY)
248                                       : (attrs & ~FILE_ATTRIBUTE_READONLY)));
249 
250   DWORD expected =
251       read_only
252           ? ((attrs & (FILE_ATTRIBUTE_ARCHIVE | FILE_ATTRIBUTE_DIRECTORY)) |
253              FILE_ATTRIBUTE_READONLY)
254           : (attrs & (FILE_ATTRIBUTE_ARCHIVE | FILE_ATTRIBUTE_DIRECTORY));
255 
256   // Ignore FILE_ATTRIBUTE_NOT_CONTENT_INDEXED and FILE_ATTRIBUTE_COMPRESSED
257   // if present. These flags are set by the operating system, depending on
258   // local configurations, such as compressing the file system. Not filtering
259   // out these flags could cause tests to fail even though they should pass.
260   attrs = GetFileAttributes(path.value().c_str()) &
261           ~(FILE_ATTRIBUTE_NOT_CONTENT_INDEXED | FILE_ATTRIBUTE_COMPRESSED);
262   ASSERT_EQ(expected, attrs);
263 #else
264   // On all other platforms, it involves removing/setting the write bit.
265   mode_t mode = read_only ? S_IRUSR : (S_IRUSR | S_IWUSR);
266   EXPECT_TRUE(SetPosixFilePermissions(
267       path, DirectoryExists(path) ? (mode | S_IXUSR) : mode));
268 #endif  // BUILDFLAG(IS_WIN)
269 }
270 
IsReadOnly(const FilePath & path)271 bool IsReadOnly(const FilePath& path) {
272 #if BUILDFLAG(IS_WIN)
273   DWORD attrs = GetFileAttributes(path.value().c_str());
274   EXPECT_NE(INVALID_FILE_ATTRIBUTES, attrs);
275   return attrs & FILE_ATTRIBUTE_READONLY;
276 #else
277   int mode = 0;
278   EXPECT_TRUE(GetPosixFilePermissions(path, &mode));
279   return !(mode & S_IWUSR);
280 #endif  // BUILDFLAG(IS_WIN)
281 }
282 
283 #endif  // BUILDFLAG(IS_FUCHSIA)
284 
285 const wchar_t bogus_content[] = L"I'm cannon fodder.";
286 
287 const int FILES_AND_DIRECTORIES =
288     FileEnumerator::FILES | FileEnumerator::DIRECTORIES;
289 
290 // file_util winds up using autoreleased objects on the Mac, so this needs
291 // to be a PlatformTest
292 class FileUtilTest : public PlatformTest {
293  protected:
SetUp()294   void SetUp() override {
295     PlatformTest::SetUp();
296     ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
297   }
298 
299   ScopedTempDir temp_dir_;
300 };
301 
302 // Collects all the results from the given file enumerator, and provides an
303 // interface to query whether a given file is present.
304 class FindResultCollector {
305  public:
FindResultCollector(FileEnumerator * enumerator)306   explicit FindResultCollector(FileEnumerator* enumerator) {
307     FilePath cur_file;
308     while (!(cur_file = enumerator->Next()).value().empty()) {
309       FilePath::StringType path = cur_file.value();
310       // The file should not be returned twice.
311       EXPECT_TRUE(files_.end() == files_.find(path))
312           << "Same file returned twice";
313 
314       // Save for later.
315       files_.insert(path);
316     }
317   }
318 
319   // Returns true if the enumerator found the file.
HasFile(const FilePath & file) const320   bool HasFile(const FilePath& file) const {
321     return files_.find(file.value()) != files_.end();
322   }
323 
size()324   int size() {
325     return static_cast<int>(files_.size());
326   }
327 
328  private:
329   std::set<FilePath::StringType> files_;
330 };
331 
332 // Simple function to dump some text into a new file.
CreateTextFile(const FilePath & filename,const std::wstring & contents)333 void CreateTextFile(const FilePath& filename,
334                     const std::wstring& contents) {
335   std::wofstream file;
336 #if BUILDFLAG(IS_WIN)
337   file.open(filename.value().c_str());
338 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
339   file.open(filename.value());
340 #endif  // BUILDFLAG(IS_WIN)
341   ASSERT_TRUE(file.is_open());
342   file << contents;
343   file.close();
344 }
345 
346 // Simple function to take out some text from a file.
ReadTextFile(const FilePath & filename)347 std::wstring ReadTextFile(const FilePath& filename) {
348   wchar_t contents[64];
349   std::wifstream file;
350 #if BUILDFLAG(IS_WIN)
351   file.open(filename.value().c_str());
352 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
353   file.open(filename.value());
354 #endif  // BUILDFLAG(IS_WIN)
355   EXPECT_TRUE(file.is_open());
356   file.getline(contents, std::size(contents));
357   file.close();
358   return std::wstring(contents);
359 }
360 
361 // Sets |is_inheritable| to indicate whether or not |stream| is set up to be
362 // inerhited into child processes (i.e., HANDLE_FLAG_INHERIT is set on the
363 // underlying handle on Windows, or FD_CLOEXEC is not set on the underlying file
364 // descriptor on POSIX). Calls to this function must be wrapped with
365 // ASSERT_NO_FATAL_FAILURE to properly abort tests in case of fatal failure.
GetIsInheritable(FILE * stream,bool * is_inheritable)366 void GetIsInheritable(FILE* stream, bool* is_inheritable) {
367 #if BUILDFLAG(IS_WIN)
368   HANDLE handle = reinterpret_cast<HANDLE>(_get_osfhandle(_fileno(stream)));
369   ASSERT_NE(INVALID_HANDLE_VALUE, handle);
370 
371   DWORD info = 0;
372   ASSERT_EQ(TRUE, ::GetHandleInformation(handle, &info));
373   *is_inheritable = ((info & HANDLE_FLAG_INHERIT) != 0);
374 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
375   int fd = fileno(stream);
376   ASSERT_NE(-1, fd);
377   int flags = fcntl(fd, F_GETFD, 0);
378   ASSERT_NE(-1, flags);
379   *is_inheritable = ((flags & FD_CLOEXEC) == 0);
380 #else
381 #error Not implemented
382 #endif
383 }
384 
385 #if BUILDFLAG(IS_POSIX)
386 class ScopedWorkingDirectory {
387  public:
ScopedWorkingDirectory(const FilePath & new_working_dir)388   explicit ScopedWorkingDirectory(const FilePath& new_working_dir) {
389     CHECK(base::GetCurrentDirectory(&original_working_directory_));
390     CHECK(base::SetCurrentDirectory(new_working_dir));
391   }
392 
~ScopedWorkingDirectory()393   ~ScopedWorkingDirectory() {
394     CHECK(base::SetCurrentDirectory(original_working_directory_));
395   }
396 
397  private:
398   base::FilePath original_working_directory_;
399 };
400 
TEST_F(FileUtilTest,MakeAbsoluteFilePathNoResolveSymbolicLinks)401 TEST_F(FileUtilTest, MakeAbsoluteFilePathNoResolveSymbolicLinks) {
402   FilePath cwd;
403   ASSERT_TRUE(GetCurrentDirectory(&cwd));
404   const std::pair<FilePath, absl::optional<FilePath>> kExpectedResults[]{
405       {FilePath(), absl::nullopt},
406       {FilePath("."), cwd},
407       {FilePath(".."), cwd.DirName()},
408       {FilePath("a/.."), cwd},
409       {FilePath("a/b/.."), cwd.Append(FPL("a"))},
410       {FilePath("/tmp/../.."), FilePath("/")},
411       {FilePath("/tmp/../"), FilePath("/")},
412       {FilePath("/tmp/a/b/../c/../.."), FilePath("/tmp")},
413       {FilePath("/././tmp/./a/./b/../c/./../.."), FilePath("/tmp")},
414       {FilePath("/.././../tmp"), FilePath("/tmp")},
415       {FilePath("/..///.////..////tmp"), FilePath("/tmp")},
416       {FilePath("//..///.////..////tmp"), FilePath("//tmp")},
417       {FilePath("///..///.////..////tmp"), FilePath("/tmp")},
418   };
419 
420   for (auto& expected_result : kExpectedResults) {
421     EXPECT_EQ(MakeAbsoluteFilePathNoResolveSymbolicLinks(expected_result.first),
422               expected_result.second);
423   }
424 
425   // Test that MakeAbsoluteFilePathNoResolveSymbolicLinks() returns an empty
426   // path if GetCurrentDirectory() fails.
427   const FilePath temp_dir_path = temp_dir_.GetPath();
428   ScopedWorkingDirectory scoped_cwd(temp_dir_path);
429   // Delete the cwd so that GetCurrentDirectory() fails.
430   ASSERT_TRUE(temp_dir_.Delete());
431   ASSERT_FALSE(
432       MakeAbsoluteFilePathNoResolveSymbolicLinks(FilePath("relative_file_path"))
433           .has_value());
434 }
435 #endif  // BUILDFLAG(IS_POSIX)
436 
TEST_F(FileUtilTest,FileAndDirectorySize)437 TEST_F(FileUtilTest, FileAndDirectorySize) {
438   // Create three files of 20, 30 and 3 chars (utf8). ComputeDirectorySize
439   // should return 53 bytes.
440   FilePath file_01 = temp_dir_.GetPath().Append(FPL("The file 01.txt"));
441   CreateTextFile(file_01, L"12345678901234567890");
442   int64_t size_f1 = 0;
443   ASSERT_TRUE(GetFileSize(file_01, &size_f1));
444   EXPECT_EQ(20ll, size_f1);
445 
446   FilePath subdir_path = temp_dir_.GetPath().Append(FPL("Level2"));
447   CreateDirectory(subdir_path);
448 
449   FilePath file_02 = subdir_path.Append(FPL("The file 02.txt"));
450   CreateTextFile(file_02, L"123456789012345678901234567890");
451   int64_t size_f2 = 0;
452   ASSERT_TRUE(GetFileSize(file_02, &size_f2));
453   EXPECT_EQ(30ll, size_f2);
454 
455   FilePath subsubdir_path = subdir_path.Append(FPL("Level3"));
456   CreateDirectory(subsubdir_path);
457 
458   FilePath file_03 = subsubdir_path.Append(FPL("The file 03.txt"));
459   CreateTextFile(file_03, L"123");
460 
461   int64_t computed_size = ComputeDirectorySize(temp_dir_.GetPath());
462   EXPECT_EQ(size_f1 + size_f2 + 3, computed_size);
463 }
464 
TEST_F(FileUtilTest,NormalizeFilePathBasic)465 TEST_F(FileUtilTest, NormalizeFilePathBasic) {
466   // Create a directory under the test dir.  Because we create it,
467   // we know it is not a link.
468   FilePath file_a_path = temp_dir_.GetPath().Append(FPL("file_a"));
469   FilePath dir_path = temp_dir_.GetPath().Append(FPL("dir"));
470   FilePath file_b_path = dir_path.Append(FPL("file_b"));
471   CreateDirectory(dir_path);
472 
473   FilePath normalized_file_a_path, normalized_file_b_path;
474   ASSERT_FALSE(PathExists(file_a_path));
475   ASSERT_FALSE(NormalizeFilePath(file_a_path, &normalized_file_a_path))
476     << "NormalizeFilePath() should fail on nonexistent paths.";
477 
478   CreateTextFile(file_a_path, bogus_content);
479   ASSERT_TRUE(PathExists(file_a_path));
480   ASSERT_TRUE(NormalizeFilePath(file_a_path, &normalized_file_a_path));
481 
482   CreateTextFile(file_b_path, bogus_content);
483   ASSERT_TRUE(PathExists(file_b_path));
484   ASSERT_TRUE(NormalizeFilePath(file_b_path, &normalized_file_b_path));
485 
486   // Because this test created |dir_path|, we know it is not a link
487   // or junction.  So, the real path of the directory holding file a
488   // must be the parent of the path holding file b.
489   ASSERT_TRUE(normalized_file_a_path.DirName()
490       .IsParent(normalized_file_b_path.DirName()));
491 }
492 
493 #if BUILDFLAG(IS_WIN)
494 
TEST_F(FileUtilTest,NormalizeFileEmptyFile)495 TEST_F(FileUtilTest, NormalizeFileEmptyFile) {
496   // Create a directory under the test dir.  Because we create it,
497   // we know it is not a link.
498   const wchar_t empty_content[] = L"";
499 
500   FilePath file_a_path = temp_dir_.GetPath().Append(FPL("file_empty_a"));
501   FilePath dir_path = temp_dir_.GetPath().Append(FPL("dir"));
502   FilePath file_b_path = dir_path.Append(FPL("file_empty_b"));
503   ASSERT_TRUE(CreateDirectory(dir_path));
504 
505   FilePath normalized_file_a_path, normalized_file_b_path;
506   ASSERT_FALSE(PathExists(file_a_path));
507   EXPECT_FALSE(NormalizeFilePath(file_a_path, &normalized_file_a_path))
508       << "NormalizeFilePath() should fail on nonexistent paths.";
509 
510   CreateTextFile(file_a_path, empty_content);
511   ASSERT_TRUE(PathExists(file_a_path));
512   EXPECT_TRUE(NormalizeFilePath(file_a_path, &normalized_file_a_path));
513 
514   CreateTextFile(file_b_path, empty_content);
515   ASSERT_TRUE(PathExists(file_b_path));
516   EXPECT_TRUE(NormalizeFilePath(file_b_path, &normalized_file_b_path));
517 
518   // Because this test created |dir_path|, we know it is not a link
519   // or junction.  So, the real path of the directory holding file a
520   // must be the parent of the path holding file b.
521   EXPECT_TRUE(normalized_file_a_path.DirName().IsParent(
522       normalized_file_b_path.DirName()));
523 }
524 
TEST_F(FileUtilTest,NormalizeFilePathReparsePoints)525 TEST_F(FileUtilTest, NormalizeFilePathReparsePoints) {
526   // Build the following directory structure:
527   //
528   // temp_dir
529   // |-> base_a
530   // |   |-> sub_a
531   // |       |-> file.txt
532   // |       |-> long_name___... (Very long name.)
533   // |           |-> sub_long
534   // |              |-> deep.txt
535   // |-> base_b
536   //     |-> to_sub_a (reparse point to temp_dir\base_a\sub_a)
537   //     |-> to_base_b (reparse point to temp_dir\base_b)
538   //     |-> to_sub_long (reparse point to temp_dir\sub_a\long_name_\sub_long)
539 
540   FilePath base_a = temp_dir_.GetPath().Append(FPL("base_a"));
541 #if BUILDFLAG(IS_WIN)
542   // TEMP can have a lower case drive letter.
543   std::wstring temp_base_a = base_a.value();
544   ASSERT_FALSE(temp_base_a.empty());
545   temp_base_a[0] = ToUpperASCII(char16_t{temp_base_a[0]});
546   base_a = FilePath(temp_base_a);
547 #endif
548   ASSERT_TRUE(CreateDirectory(base_a));
549 #if BUILDFLAG(IS_WIN)
550   // TEMP might be a short name which is not normalized.
551   base_a = MakeLongFilePath(base_a);
552 #endif
553 
554   FilePath sub_a = base_a.Append(FPL("sub_a"));
555   ASSERT_TRUE(CreateDirectory(sub_a));
556 
557   FilePath file_txt = sub_a.Append(FPL("file.txt"));
558   CreateTextFile(file_txt, bogus_content);
559 
560   // Want a directory whose name is long enough to make the path to the file
561   // inside just under MAX_PATH chars.  This will be used to test that when
562   // a junction expands to a path over MAX_PATH chars in length,
563   // NormalizeFilePath() fails without crashing.
564   FilePath sub_long_rel(FPL("sub_long"));
565   FilePath deep_txt(FPL("deep.txt"));
566 
567   int target_length = MAX_PATH;
568   target_length -= (sub_a.value().length() + 1);  // +1 for the sepperator '\'.
569   target_length -= (sub_long_rel.Append(deep_txt).value().length() + 1);
570   // Without making the path a bit shorter, CreateDirectory() fails.
571   // the resulting path is still long enough to hit the failing case in
572   // NormalizePath().
573   const int kCreateDirLimit = 4;
574   target_length -= kCreateDirLimit;
575   FilePath::StringType long_name_str = FPL("long_name_");
576   long_name_str.resize(target_length, '_');
577 
578   FilePath long_name = sub_a.Append(FilePath(long_name_str));
579   FilePath deep_file = long_name.Append(sub_long_rel).Append(deep_txt);
580   ASSERT_EQ(static_cast<size_t>(MAX_PATH - kCreateDirLimit),
581             deep_file.value().length());
582 
583   FilePath sub_long = deep_file.DirName();
584   ASSERT_TRUE(CreateDirectory(sub_long));
585   CreateTextFile(deep_file, bogus_content);
586 
587   FilePath base_b = temp_dir_.GetPath().Append(FPL("base_b"));
588   ASSERT_TRUE(CreateDirectory(base_b));
589 #if BUILDFLAG(IS_WIN)
590   // TEMP might be a short name which is not normalized.
591   base_b = MakeLongFilePath(base_b);
592 #endif
593 
594   FilePath to_sub_a = base_b.Append(FPL("to_sub_a"));
595   ASSERT_TRUE(CreateDirectory(to_sub_a));
596   FilePath normalized_path;
597   {
598     ReparsePoint reparse_to_sub_a(to_sub_a, sub_a);
599     ASSERT_TRUE(reparse_to_sub_a.IsValid());
600 
601     FilePath to_base_b = base_b.Append(FPL("to_base_b"));
602     ASSERT_TRUE(CreateDirectory(to_base_b));
603     ReparsePoint reparse_to_base_b(to_base_b, base_b);
604     ASSERT_TRUE(reparse_to_base_b.IsValid());
605 
606     FilePath to_sub_long = base_b.Append(FPL("to_sub_long"));
607     ASSERT_TRUE(CreateDirectory(to_sub_long));
608     ReparsePoint reparse_to_sub_long(to_sub_long, sub_long);
609     ASSERT_TRUE(reparse_to_sub_long.IsValid());
610 
611     // Normalize a junction free path: base_a\sub_a\file.txt .
612     ASSERT_TRUE(NormalizeFilePath(file_txt, &normalized_path));
613     ASSERT_EQ(file_txt.value(), normalized_path.value());
614 
615     // Check that the path base_b\to_sub_a\file.txt can be normalized to exclude
616     // the junction to_sub_a.
617     ASSERT_TRUE(NormalizeFilePath(to_sub_a.Append(FPL("file.txt")),
618                                              &normalized_path));
619     ASSERT_EQ(file_txt.value(), normalized_path.value());
620 
621     // Check that the path base_b\to_base_b\to_base_b\to_sub_a\file.txt can be
622     // normalized to exclude junctions to_base_b and to_sub_a .
623     ASSERT_TRUE(NormalizeFilePath(base_b.Append(FPL("to_base_b"))
624                                                    .Append(FPL("to_base_b"))
625                                                    .Append(FPL("to_sub_a"))
626                                                    .Append(FPL("file.txt")),
627                                              &normalized_path));
628     ASSERT_EQ(file_txt.value(), normalized_path.value());
629 
630     // A long enough path will cause NormalizeFilePath() to fail.  Make a long
631     // path using to_base_b many times, and check that paths long enough to fail
632     // do not cause a crash.
633     FilePath long_path = base_b;
634     const int kLengthLimit = MAX_PATH + 200;
635     while (long_path.value().length() <= kLengthLimit) {
636       long_path = long_path.Append(FPL("to_base_b"));
637     }
638     long_path = long_path.Append(FPL("to_sub_a"))
639                          .Append(FPL("file.txt"));
640 
641     ASSERT_FALSE(NormalizeFilePath(long_path, &normalized_path));
642 
643     // Normalizing the junction to deep.txt should fail, because the expanded
644     // path to deep.txt is longer than MAX_PATH.
645     ASSERT_FALSE(NormalizeFilePath(to_sub_long.Append(deep_txt),
646                                               &normalized_path));
647 
648     // Delete the reparse points, and see that NormalizeFilePath() fails
649     // to traverse them.
650   }
651 
652   ASSERT_FALSE(NormalizeFilePath(to_sub_a.Append(FPL("file.txt")),
653                                             &normalized_path));
654 }
655 
TEST_F(FileUtilTest,DevicePathToDriveLetter)656 TEST_F(FileUtilTest, DevicePathToDriveLetter) {
657   // Get a drive letter.
658   std::wstring real_drive_letter = AsWString(
659       ToUpperASCII(AsStringPiece16(temp_dir_.GetPath().value().substr(0, 2))));
660   if (!IsAsciiAlpha(real_drive_letter[0]) || ':' != real_drive_letter[1]) {
661     LOG(ERROR) << "Can't get a drive letter to test with.";
662     return;
663   }
664 
665   // Get the NT style path to that drive.
666   wchar_t device_path[MAX_PATH] = {'\0'};
667   ASSERT_TRUE(
668       ::QueryDosDevice(real_drive_letter.c_str(), device_path, MAX_PATH));
669   FilePath actual_device_path(device_path);
670   FilePath win32_path;
671 
672   // Run DevicePathToDriveLetterPath() on the NT style path we got from
673   // QueryDosDevice().  Expect the drive letter we started with.
674   ASSERT_TRUE(DevicePathToDriveLetterPath(actual_device_path, &win32_path));
675   ASSERT_EQ(real_drive_letter, win32_path.value());
676 
677   // Add some directories to the path.  Expect those extra path componenets
678   // to be preserved.
679   FilePath kRelativePath(FPL("dir1\\dir2\\file.txt"));
680   ASSERT_TRUE(DevicePathToDriveLetterPath(
681       actual_device_path.Append(kRelativePath),
682       &win32_path));
683   EXPECT_EQ(FilePath(real_drive_letter + FILE_PATH_LITERAL("\\"))
684                 .Append(kRelativePath)
685                 .value(),
686             win32_path.value());
687 
688   // Deform the real path so that it is invalid by removing the last four
689   // characters.  The way windows names devices that are hard disks
690   // (\Device\HardDiskVolume${NUMBER}) guarantees that the string is longer
691   // than three characters.  The only way the truncated string could be a
692   // real drive is if more than 10^3 disks are mounted:
693   // \Device\HardDiskVolume10000 would be truncated to \Device\HardDiskVolume1
694   // Check that DevicePathToDriveLetterPath fails.
695   size_t path_length = actual_device_path.value().length();
696   size_t new_length = path_length - 4;
697   ASSERT_GT(new_length, 0u);
698   FilePath prefix_of_real_device_path(
699       actual_device_path.value().substr(0, new_length));
700   ASSERT_FALSE(DevicePathToDriveLetterPath(prefix_of_real_device_path,
701                                            &win32_path));
702 
703   ASSERT_FALSE(DevicePathToDriveLetterPath(
704       prefix_of_real_device_path.Append(kRelativePath),
705       &win32_path));
706 
707   // Deform the real path so that it is invalid by adding some characters. For
708   // example, if C: maps to \Device\HardDiskVolume8, then we simulate a
709   // request for the drive letter whose native path is
710   // \Device\HardDiskVolume812345 .  We assume such a device does not exist,
711   // because drives are numbered in order and mounting 112345 hard disks will
712   // never happen.
713   const FilePath::StringType kExtraChars = FPL("12345");
714 
715   FilePath real_device_path_plus_numbers(
716       actual_device_path.value() + kExtraChars);
717 
718   ASSERT_FALSE(DevicePathToDriveLetterPath(
719       real_device_path_plus_numbers,
720       &win32_path));
721 
722   ASSERT_FALSE(DevicePathToDriveLetterPath(
723       real_device_path_plus_numbers.Append(kRelativePath),
724       &win32_path));
725 }
726 
TEST_F(FileUtilTest,CreateTemporaryFileInDirLongPathTest)727 TEST_F(FileUtilTest, CreateTemporaryFileInDirLongPathTest) {
728   // Test that CreateTemporaryFileInDir() creates a path and returns a long path
729   // if it is available. This test requires that:
730   // - the filesystem at |temp_dir_| supports long filenames.
731   // - the account has FILE_LIST_DIRECTORY permission for all ancestor
732   //   directories of |temp_dir_|.
733   constexpr FilePath::CharType kLongDirName[] = FPL("A long path");
734   constexpr FilePath::CharType kTestSubDirName[] = FPL("test");
735   FilePath long_test_dir = temp_dir_.GetPath().Append(kLongDirName);
736   ASSERT_TRUE(CreateDirectory(long_test_dir));
737 
738   // kLongDirName is not a 8.3 component. So ::GetShortPathName() should give us
739   // a different short name.
740   FilePath short_test_dir = MakeShortFilePath(long_test_dir);
741   ASSERT_FALSE(short_test_dir.empty());
742   ASSERT_NE(kLongDirName, short_test_dir.BaseName().value());
743 
744   FilePath temp_file;
745   ASSERT_TRUE(CreateTemporaryFileInDir(short_test_dir, &temp_file));
746   EXPECT_EQ(kLongDirName, temp_file.DirName().BaseName().value());
747   EXPECT_TRUE(PathExists(temp_file));
748 
749   // Create a subdirectory of |long_test_dir| and make |long_test_dir|
750   // unreadable. We should still be able to create a temp file in the
751   // subdirectory, but we won't be able to determine the long path for it. This
752   // mimics the environment that some users run where their user profiles reside
753   // in a location where the don't have full access to the higher level
754   // directories. (Note that this assumption is true for NTFS, but not for some
755   // network file systems. E.g. AFS).
756   FilePath access_test_dir = long_test_dir.Append(kTestSubDirName);
757   ASSERT_TRUE(CreateDirectory(access_test_dir));
758   FilePermissionRestorer long_test_dir_restorer(long_test_dir);
759   ASSERT_TRUE(MakeFileUnreadable(long_test_dir));
760 
761   // Use the short form of the directory to create a temporary filename.
762   ASSERT_TRUE(CreateTemporaryFileInDir(
763       short_test_dir.Append(kTestSubDirName), &temp_file));
764   EXPECT_TRUE(PathExists(temp_file));
765   EXPECT_TRUE(short_test_dir.IsParent(temp_file.DirName()));
766 
767   // Check that the long path can't be determined for |temp_file|.
768   // Helper method base::MakeLongFilePath returns an empty path on error.
769   FilePath temp_file_long = MakeLongFilePath(temp_file);
770   ASSERT_TRUE(temp_file_long.empty());
771 }
772 
TEST_F(FileUtilTest,MakeLongFilePathTest)773 TEST_F(FileUtilTest, MakeLongFilePathTest) {
774   // Tests helper function base::MakeLongFilePath
775 
776   // If a username isn't a valid 8.3 short file name (even just a
777   // lengthy name like "user with long name"), Windows will set the TMP and TEMP
778   // environment variables to be 8.3 paths. ::GetTempPath (called in
779   // base::GetTempDir) just uses the value specified by TMP or TEMP, and so can
780   // return a short path. So from the start need to use MakeLongFilePath
781   // to normalize the path for such test environments.
782   FilePath temp_dir_long = MakeLongFilePath(temp_dir_.GetPath());
783   ASSERT_FALSE(temp_dir_long.empty());
784 
785   FilePath long_test_dir = temp_dir_long.Append(FPL("A long directory name"));
786   ASSERT_TRUE(CreateDirectory(long_test_dir));
787 
788   // Directory name is not a 8.3 component. So ::GetShortPathName() should give
789   // us a different short name.
790   FilePath short_test_dir = MakeShortFilePath(long_test_dir);
791   ASSERT_FALSE(short_test_dir.empty());
792 
793   EXPECT_NE(long_test_dir, short_test_dir);
794   EXPECT_EQ(long_test_dir, MakeLongFilePath(short_test_dir));
795 
796   FilePath long_test_file = long_test_dir.Append(FPL("A long file name.1234"));
797   CreateTextFile(long_test_file, bogus_content);
798   ASSERT_TRUE(PathExists(long_test_file));
799 
800   // File name is not a 8.3 component. So ::GetShortPathName() should give us
801   // a different short name.
802   FilePath short_test_file = MakeShortFilePath(long_test_file);
803   ASSERT_FALSE(short_test_file.empty());
804 
805   EXPECT_NE(long_test_file, short_test_file);
806   EXPECT_EQ(long_test_file, MakeLongFilePath(short_test_file));
807 
808   // MakeLongFilePath should return empty path if file does not exist.
809   EXPECT_TRUE(DeleteFile(short_test_file));
810   EXPECT_TRUE(MakeLongFilePath(short_test_file).empty());
811 
812   // MakeLongFilePath should return empty path if directory does not exist.
813   EXPECT_TRUE(DeleteFile(short_test_dir));
814   EXPECT_TRUE(MakeLongFilePath(short_test_dir).empty());
815 }
816 
TEST_F(FileUtilTest,CreateWinHardlinkTest)817 TEST_F(FileUtilTest, CreateWinHardlinkTest) {
818   // Link to a different file name in a sub-directory of |temp_dir_|.
819   FilePath test_dir = temp_dir_.GetPath().Append(FPL("test"));
820   ASSERT_TRUE(CreateDirectory(test_dir));
821   FilePath temp_file;
822   ASSERT_TRUE(CreateTemporaryFileInDir(temp_dir_.GetPath(), &temp_file));
823   FilePath link_to_file = test_dir.Append(FPL("linked_name"));
824   EXPECT_TRUE(CreateWinHardLink(link_to_file, temp_file));
825   EXPECT_TRUE(PathExists(link_to_file));
826 
827   // Link two directories. This should fail. Verify that failure is returned
828   // by CreateWinHardLink.
829   EXPECT_FALSE(CreateWinHardLink(temp_dir_.GetPath(), test_dir));
830 }
831 
TEST_F(FileUtilTest,PreventExecuteMappingNewFile)832 TEST_F(FileUtilTest, PreventExecuteMappingNewFile) {
833   base::test::ScopedFeatureList enforcement_feature;
834   enforcement_feature.InitAndEnableFeature(
835       features::kEnforceNoExecutableFileHandles);
836   FilePath file = temp_dir_.GetPath().Append(FPL("afile.txt"));
837 
838   ASSERT_FALSE(PathExists(file));
839   {
840     File new_file(file, File::FLAG_WRITE | File::FLAG_WIN_NO_EXECUTE |
841                             File::FLAG_CREATE_ALWAYS);
842     ASSERT_TRUE(new_file.IsValid());
843   }
844 
845   {
846     File open_file(file, File::FLAG_READ | File::FLAG_WIN_EXECUTE |
847                              File::FLAG_OPEN_ALWAYS);
848     EXPECT_FALSE(open_file.IsValid());
849   }
850   // Verify the deny ACL did not prevent deleting the file.
851   EXPECT_TRUE(DeleteFile(file));
852 }
853 
TEST_F(FileUtilTest,PreventExecuteMappingExisting)854 TEST_F(FileUtilTest, PreventExecuteMappingExisting) {
855   base::test::ScopedFeatureList enforcement_feature;
856   enforcement_feature.InitAndEnableFeature(
857       features::kEnforceNoExecutableFileHandles);
858   FilePath file = temp_dir_.GetPath().Append(FPL("afile.txt"));
859   CreateTextFile(file, bogus_content);
860   ASSERT_TRUE(PathExists(file));
861   {
862     File open_file(file, File::FLAG_READ | File::FLAG_WIN_EXECUTE |
863                              File::FLAG_OPEN_ALWAYS);
864     EXPECT_TRUE(open_file.IsValid());
865   }
866   EXPECT_TRUE(PreventExecuteMapping(file));
867   {
868     File open_file(file, File::FLAG_READ | File::FLAG_WIN_EXECUTE |
869                              File::FLAG_OPEN_ALWAYS);
870     EXPECT_FALSE(open_file.IsValid());
871   }
872   // Verify the deny ACL did not prevent deleting the file.
873   EXPECT_TRUE(DeleteFile(file));
874 }
875 
TEST_F(FileUtilTest,PreventExecuteMappingOpenFile)876 TEST_F(FileUtilTest, PreventExecuteMappingOpenFile) {
877   base::test::ScopedFeatureList enforcement_feature;
878   enforcement_feature.InitAndEnableFeature(
879       features::kEnforceNoExecutableFileHandles);
880   FilePath file = temp_dir_.GetPath().Append(FPL("afile.txt"));
881   CreateTextFile(file, bogus_content);
882   ASSERT_TRUE(PathExists(file));
883   File open_file(file, File::FLAG_READ | File::FLAG_WRITE |
884                            File::FLAG_WIN_EXECUTE | File::FLAG_OPEN_ALWAYS);
885   EXPECT_TRUE(open_file.IsValid());
886   // Verify ACE can be set even on an open file.
887   EXPECT_TRUE(PreventExecuteMapping(file));
888   {
889     File second_open_file(
890         file, File::FLAG_READ | File::FLAG_WRITE | File::FLAG_OPEN_ALWAYS);
891     EXPECT_TRUE(second_open_file.IsValid());
892   }
893   {
894     File third_open_file(file, File::FLAG_READ | File::FLAG_WIN_EXECUTE |
895                                    File::FLAG_OPEN_ALWAYS);
896     EXPECT_FALSE(third_open_file.IsValid());
897   }
898 
899   open_file.Close();
900   // Verify the deny ACL did not prevent deleting the file.
901   EXPECT_TRUE(DeleteFile(file));
902 }
903 
TEST(FileUtilDeathTest,DisallowNoExecuteOnUnsafeFile)904 TEST(FileUtilDeathTest, DisallowNoExecuteOnUnsafeFile) {
905   base::test::ScopedFeatureList enforcement_feature;
906   enforcement_feature.InitAndEnableFeature(
907       features::kEnforceNoExecutableFileHandles);
908   base::FilePath local_app_data;
909   // This test places a file in %LOCALAPPDATA% to verify that the checks in
910   // IsPathSafeToSetAclOn work correctly.
911   ASSERT_TRUE(
912       base::PathService::Get(base::DIR_LOCAL_APP_DATA, &local_app_data));
913 
914   base::FilePath file_path;
915   EXPECT_DCHECK_DEATH_WITH(
916       {
917         {
918           base::File temp_file =
919               base::CreateAndOpenTemporaryFileInDir(local_app_data, &file_path);
920         }
921         File reopen_file(file_path, File::FLAG_READ | File::FLAG_WRITE |
922                                         File::FLAG_WIN_NO_EXECUTE |
923                                         File::FLAG_OPEN_ALWAYS |
924                                         File::FLAG_DELETE_ON_CLOSE);
925       },
926       "Unsafe to deny execute access to path");
927 }
928 
MULTIPROCESS_TEST_MAIN(NoExecuteOnSafeFileMain)929 MULTIPROCESS_TEST_MAIN(NoExecuteOnSafeFileMain) {
930   base::FilePath temp_file;
931   CHECK(base::CreateTemporaryFile(&temp_file));
932 
933   // A file with FLAG_WIN_NO_EXECUTE created in temp dir should always be
934   // permitted.
935   File reopen_file(temp_file, File::FLAG_READ | File::FLAG_WRITE |
936                                   File::FLAG_WIN_NO_EXECUTE |
937                                   File::FLAG_OPEN_ALWAYS |
938                                   File::FLAG_DELETE_ON_CLOSE);
939   return 0;
940 }
941 
TEST_F(FileUtilTest,NoExecuteOnSafeFile)942 TEST_F(FileUtilTest, NoExecuteOnSafeFile) {
943   FilePath new_dir;
944   ASSERT_TRUE(CreateTemporaryDirInDir(
945       temp_dir_.GetPath(), FILE_PATH_LITERAL("NoExecuteOnSafeFileLongPath"),
946       &new_dir));
947 
948   FilePath short_dir = base::MakeShortFilePath(new_dir);
949 
950   // Verify that the path really is 8.3 now.
951   ASSERT_NE(new_dir.value(), short_dir.value());
952 
953   LaunchOptions options;
954   options.environment[L"TMP"] = short_dir.value();
955 
956   CommandLine child_command_line(GetMultiProcessTestChildBaseCommandLine());
957 
958   Process child_process = SpawnMultiProcessTestChild(
959       "NoExecuteOnSafeFileMain", child_command_line, options);
960   ASSERT_TRUE(child_process.IsValid());
961   int rv = -1;
962   ASSERT_TRUE(WaitForMultiprocessTestChildExit(
963       child_process, TestTimeouts::action_timeout(), &rv));
964   ASSERT_EQ(0, rv);
965 }
966 
967 class FileUtilExecuteEnforcementTest
968     : public FileUtilTest,
969       public ::testing::WithParamInterface<bool> {
970  public:
FileUtilExecuteEnforcementTest()971   FileUtilExecuteEnforcementTest() {
972     if (IsEnforcementEnabled()) {
973       enforcement_feature_.InitAndEnableFeature(
974           features::kEnforceNoExecutableFileHandles);
975     } else {
976       enforcement_feature_.InitAndDisableFeature(
977           features::kEnforceNoExecutableFileHandles);
978     }
979   }
980 
981  protected:
IsEnforcementEnabled()982   bool IsEnforcementEnabled() { return GetParam(); }
983 
984  private:
985   base::test::ScopedFeatureList enforcement_feature_;
986 };
987 
988 // This test verifies that if a file has been passed to `PreventExecuteMapping`
989 // and enforcement is enabled, then it cannot be mapped as executable into
990 // memory.
TEST_P(FileUtilExecuteEnforcementTest,Functional)991 TEST_P(FileUtilExecuteEnforcementTest, Functional) {
992   FilePath dir_exe;
993   EXPECT_TRUE(PathService::Get(DIR_EXE, &dir_exe));
994   // This DLL is built as part of base_unittests so is guaranteed to be present.
995   FilePath test_dll(dir_exe.Append(FPL("scoped_handle_test_dll.dll")));
996 
997   EXPECT_TRUE(base::PathExists(test_dll));
998 
999   FilePath dll_copy_path = temp_dir_.GetPath().Append(FPL("test.dll"));
1000 
1001   ASSERT_TRUE(CopyFile(test_dll, dll_copy_path));
1002   ASSERT_TRUE(PreventExecuteMapping(dll_copy_path));
1003   ScopedNativeLibrary module(dll_copy_path);
1004 
1005   // If enforcement is enabled, then `PreventExecuteMapping` will have prevented
1006   // the load, and the module will be invalid.
1007   EXPECT_EQ(IsEnforcementEnabled(), !module.is_valid());
1008 }
1009 
1010 INSTANTIATE_TEST_SUITE_P(EnforcementEnabled,
1011                          FileUtilExecuteEnforcementTest,
1012                          ::testing::Values(true));
1013 INSTANTIATE_TEST_SUITE_P(EnforcementDisabled,
1014                          FileUtilExecuteEnforcementTest,
1015                          ::testing::Values(false));
1016 
1017 #endif  // BUILDFLAG(IS_WIN)
1018 
1019 #if BUILDFLAG(IS_POSIX)
1020 
TEST_F(FileUtilTest,CreateAndReadSymlinks)1021 TEST_F(FileUtilTest, CreateAndReadSymlinks) {
1022   FilePath link_from = temp_dir_.GetPath().Append(FPL("from_file"));
1023   FilePath link_to = temp_dir_.GetPath().Append(FPL("to_file"));
1024   CreateTextFile(link_to, bogus_content);
1025 
1026   ASSERT_TRUE(CreateSymbolicLink(link_to, link_from))
1027     << "Failed to create file symlink.";
1028 
1029   // If we created the link properly, we should be able to read the contents
1030   // through it.
1031   EXPECT_EQ(bogus_content, ReadTextFile(link_from));
1032 
1033   FilePath result;
1034   ASSERT_TRUE(ReadSymbolicLink(link_from, &result));
1035   EXPECT_EQ(link_to.value(), result.value());
1036 
1037   // Link to a directory.
1038   link_from = temp_dir_.GetPath().Append(FPL("from_dir"));
1039   link_to = temp_dir_.GetPath().Append(FPL("to_dir"));
1040   ASSERT_TRUE(CreateDirectory(link_to));
1041   ASSERT_TRUE(CreateSymbolicLink(link_to, link_from))
1042     << "Failed to create directory symlink.";
1043 
1044   // Test failures.
1045   EXPECT_FALSE(CreateSymbolicLink(link_to, link_to));
1046   EXPECT_FALSE(ReadSymbolicLink(link_to, &result));
1047   FilePath missing = temp_dir_.GetPath().Append(FPL("missing"));
1048   EXPECT_FALSE(ReadSymbolicLink(missing, &result));
1049 }
1050 
TEST_F(FileUtilTest,CreateAndReadRelativeSymlinks)1051 TEST_F(FileUtilTest, CreateAndReadRelativeSymlinks) {
1052   FilePath link_from = temp_dir_.GetPath().Append(FPL("from_file"));
1053   FilePath filename_link_to("to_file");
1054   FilePath link_to = temp_dir_.GetPath().Append(filename_link_to);
1055   FilePath link_from_in_subdir =
1056       temp_dir_.GetPath().Append(FPL("subdir")).Append(FPL("from_file"));
1057   FilePath link_to_in_subdir = FilePath(FPL("..")).Append(filename_link_to);
1058   CreateTextFile(link_to, bogus_content);
1059 
1060   ASSERT_TRUE(CreateDirectory(link_from_in_subdir.DirName()));
1061   ASSERT_TRUE(CreateSymbolicLink(link_to_in_subdir, link_from_in_subdir));
1062 
1063   ASSERT_TRUE(CreateSymbolicLink(filename_link_to, link_from))
1064       << "Failed to create file symlink.";
1065 
1066   // If we created the link properly, we should be able to read the contents
1067   // through it.
1068   EXPECT_EQ(bogus_content, ReadTextFile(link_from));
1069   EXPECT_EQ(bogus_content, ReadTextFile(link_from_in_subdir));
1070 
1071   FilePath result;
1072   ASSERT_TRUE(ReadSymbolicLink(link_from, &result));
1073   EXPECT_EQ(filename_link_to.value(), result.value());
1074 
1075   absl::optional<FilePath> absolute_link = ReadSymbolicLinkAbsolute(link_from);
1076   ASSERT_TRUE(absolute_link);
1077   EXPECT_EQ(link_to.value(), absolute_link->value());
1078 
1079   absolute_link = ReadSymbolicLinkAbsolute(link_from_in_subdir);
1080   ASSERT_TRUE(absolute_link);
1081   EXPECT_EQ(link_to.value(), absolute_link->value());
1082 
1083   // Link to a directory.
1084   link_from = temp_dir_.GetPath().Append(FPL("from_dir"));
1085   filename_link_to = FilePath("to_dir");
1086   link_to = temp_dir_.GetPath().Append(filename_link_to);
1087   ASSERT_TRUE(CreateDirectory(link_to));
1088   ASSERT_TRUE(CreateSymbolicLink(filename_link_to, link_from))
1089       << "Failed to create relative directory symlink.";
1090 
1091   ASSERT_TRUE(ReadSymbolicLink(link_from, &result));
1092   EXPECT_EQ(filename_link_to.value(), result.value());
1093 
1094   absolute_link = ReadSymbolicLinkAbsolute(link_from);
1095   ASSERT_TRUE(absolute_link);
1096   EXPECT_EQ(link_to.value(), absolute_link->value());
1097 
1098   // Test failures.
1099   EXPECT_FALSE(CreateSymbolicLink(link_to, link_to));
1100   EXPECT_FALSE(ReadSymbolicLink(link_to, &result));
1101 }
1102 
1103 // The following test of NormalizeFilePath() require that we create a symlink.
1104 // This can not be done on Windows before Vista.  On Vista, creating a symlink
1105 // requires privilege "SeCreateSymbolicLinkPrivilege".
1106 // TODO(skerner): Investigate the possibility of giving base_unittests the
1107 // privileges required to create a symlink.
TEST_F(FileUtilTest,NormalizeFilePathSymlinks)1108 TEST_F(FileUtilTest, NormalizeFilePathSymlinks) {
1109   // Link one file to another.
1110   FilePath link_from = temp_dir_.GetPath().Append(FPL("from_file"));
1111   FilePath link_to = temp_dir_.GetPath().Append(FPL("to_file"));
1112   CreateTextFile(link_to, bogus_content);
1113 
1114   ASSERT_TRUE(CreateSymbolicLink(link_to, link_from))
1115     << "Failed to create file symlink.";
1116 
1117   // Check that NormalizeFilePath sees the link.
1118   FilePath normalized_path;
1119   ASSERT_TRUE(NormalizeFilePath(link_from, &normalized_path));
1120   EXPECT_NE(link_from, link_to);
1121   EXPECT_EQ(link_to.BaseName().value(), normalized_path.BaseName().value());
1122   EXPECT_EQ(link_to.BaseName().value(), normalized_path.BaseName().value());
1123 
1124   // Link to a directory.
1125   link_from = temp_dir_.GetPath().Append(FPL("from_dir"));
1126   link_to = temp_dir_.GetPath().Append(FPL("to_dir"));
1127   ASSERT_TRUE(CreateDirectory(link_to));
1128   ASSERT_TRUE(CreateSymbolicLink(link_to, link_from))
1129     << "Failed to create directory symlink.";
1130 
1131   EXPECT_FALSE(NormalizeFilePath(link_from, &normalized_path))
1132     << "Links to directories should return false.";
1133 
1134   // Test that a loop in the links causes NormalizeFilePath() to return false.
1135   link_from = temp_dir_.GetPath().Append(FPL("link_a"));
1136   link_to = temp_dir_.GetPath().Append(FPL("link_b"));
1137   ASSERT_TRUE(CreateSymbolicLink(link_to, link_from))
1138     << "Failed to create loop symlink a.";
1139   ASSERT_TRUE(CreateSymbolicLink(link_from, link_to))
1140     << "Failed to create loop symlink b.";
1141 
1142   // Infinite loop!
1143   EXPECT_FALSE(NormalizeFilePath(link_from, &normalized_path));
1144 }
1145 
TEST_F(FileUtilTest,DeleteSymlinkToExistentFile)1146 TEST_F(FileUtilTest, DeleteSymlinkToExistentFile) {
1147   // Create a file.
1148   FilePath file_name = temp_dir_.GetPath().Append(FPL("Test DeleteFile 2.txt"));
1149   CreateTextFile(file_name, bogus_content);
1150   ASSERT_TRUE(PathExists(file_name));
1151 
1152   // Create a symlink to the file.
1153   FilePath file_link = temp_dir_.GetPath().Append("file_link_2");
1154   ASSERT_TRUE(CreateSymbolicLink(file_name, file_link))
1155       << "Failed to create symlink.";
1156 
1157   // Delete the symbolic link.
1158   EXPECT_TRUE(DeleteFile(file_link));
1159 
1160   // Make sure original file is not deleted.
1161   EXPECT_FALSE(PathExists(file_link));
1162   EXPECT_TRUE(PathExists(file_name));
1163 }
1164 
TEST_F(FileUtilTest,DeleteSymlinkToNonExistentFile)1165 TEST_F(FileUtilTest, DeleteSymlinkToNonExistentFile) {
1166   // Create a non-existent file path.
1167   FilePath non_existent =
1168       temp_dir_.GetPath().Append(FPL("Test DeleteFile 3.txt"));
1169   EXPECT_FALSE(PathExists(non_existent));
1170 
1171   // Create a symlink to the non-existent file.
1172   FilePath file_link = temp_dir_.GetPath().Append("file_link_3");
1173   ASSERT_TRUE(CreateSymbolicLink(non_existent, file_link))
1174       << "Failed to create symlink.";
1175 
1176   // Make sure the symbolic link is exist.
1177   EXPECT_TRUE(IsLink(file_link));
1178   EXPECT_FALSE(PathExists(file_link));
1179 
1180   // Delete the symbolic link.
1181   EXPECT_TRUE(DeleteFile(file_link));
1182 
1183   // Make sure the symbolic link is deleted.
1184   EXPECT_FALSE(IsLink(file_link));
1185 }
1186 
TEST_F(FileUtilTest,CopyFileFollowsSymlinks)1187 TEST_F(FileUtilTest, CopyFileFollowsSymlinks) {
1188   FilePath link_from = temp_dir_.GetPath().Append(FPL("from_file"));
1189   FilePath link_to = temp_dir_.GetPath().Append(FPL("to_file"));
1190   CreateTextFile(link_to, bogus_content);
1191 
1192   ASSERT_TRUE(CreateSymbolicLink(link_to, link_from));
1193 
1194   // If we created the link properly, we should be able to read the contents
1195   // through it.
1196   EXPECT_EQ(bogus_content, ReadTextFile(link_from));
1197 
1198   FilePath result;
1199   ASSERT_TRUE(ReadSymbolicLink(link_from, &result));
1200   EXPECT_EQ(link_to.value(), result.value());
1201 
1202   // Create another file and copy it to |link_from|.
1203   FilePath src_file = temp_dir_.GetPath().Append(FPL("src.txt"));
1204   const std::wstring file_contents(L"Gooooooooooooooooooooogle");
1205   CreateTextFile(src_file, file_contents);
1206   ASSERT_TRUE(CopyFile(src_file, link_from));
1207 
1208   // Make sure |link_from| is still a symlink, and |link_to| has been written to
1209   // by CopyFile().
1210   EXPECT_TRUE(IsLink(link_from));
1211   EXPECT_EQ(file_contents, ReadTextFile(link_from));
1212   EXPECT_EQ(file_contents, ReadTextFile(link_to));
1213 }
1214 
TEST_F(FileUtilTest,ChangeFilePermissionsAndRead)1215 TEST_F(FileUtilTest, ChangeFilePermissionsAndRead) {
1216   // Create a file path.
1217   FilePath file_name =
1218       temp_dir_.GetPath().Append(FPL("Test Readable File.txt"));
1219   EXPECT_FALSE(PathExists(file_name));
1220   EXPECT_FALSE(PathIsReadable(file_name));
1221 
1222   static constexpr char kData[] = "hello";
1223   static constexpr int kDataSize = sizeof(kData) - 1;
1224   char buffer[kDataSize];
1225 
1226   // Write file.
1227   EXPECT_TRUE(WriteFile(file_name, kData));
1228   EXPECT_TRUE(PathExists(file_name));
1229 
1230   // Make sure the file is readable.
1231   int32_t mode = 0;
1232   EXPECT_TRUE(GetPosixFilePermissions(file_name, &mode));
1233   EXPECT_TRUE(mode & FILE_PERMISSION_READ_BY_USER);
1234   EXPECT_TRUE(PathIsReadable(file_name));
1235 
1236   // Get rid of the read permission.
1237   EXPECT_TRUE(SetPosixFilePermissions(file_name, 0u));
1238   EXPECT_TRUE(GetPosixFilePermissions(file_name, &mode));
1239   EXPECT_FALSE(mode & FILE_PERMISSION_READ_BY_USER);
1240   EXPECT_FALSE(PathIsReadable(file_name));
1241   // Make sure the file can't be read.
1242   EXPECT_EQ(-1, ReadFile(file_name, buffer, kDataSize));
1243 
1244   // Give the read permission.
1245   EXPECT_TRUE(SetPosixFilePermissions(file_name, FILE_PERMISSION_READ_BY_USER));
1246   EXPECT_TRUE(GetPosixFilePermissions(file_name, &mode));
1247   EXPECT_TRUE(mode & FILE_PERMISSION_READ_BY_USER);
1248   EXPECT_TRUE(PathIsReadable(file_name));
1249   // Make sure the file can be read.
1250   EXPECT_EQ(kDataSize, ReadFile(file_name, buffer, kDataSize));
1251 
1252   // Delete the file.
1253   EXPECT_TRUE(DeleteFile(file_name));
1254   EXPECT_FALSE(PathExists(file_name));
1255 }
1256 
TEST_F(FileUtilTest,ChangeFilePermissionsAndWrite)1257 TEST_F(FileUtilTest, ChangeFilePermissionsAndWrite) {
1258   // Create a file path.
1259   FilePath file_name =
1260       temp_dir_.GetPath().Append(FPL("Test Readable File.txt"));
1261   EXPECT_FALSE(PathExists(file_name));
1262 
1263   const std::string kData("hello");
1264 
1265   // Write file.
1266   EXPECT_TRUE(WriteFile(file_name, kData));
1267   EXPECT_TRUE(PathExists(file_name));
1268 
1269   // Make sure the file is writable.
1270   int mode = 0;
1271   EXPECT_TRUE(GetPosixFilePermissions(file_name, &mode));
1272   EXPECT_TRUE(mode & FILE_PERMISSION_WRITE_BY_USER);
1273   EXPECT_TRUE(PathIsWritable(file_name));
1274 
1275   // Get rid of the write permission.
1276   EXPECT_TRUE(SetPosixFilePermissions(file_name, 0u));
1277   EXPECT_TRUE(GetPosixFilePermissions(file_name, &mode));
1278   EXPECT_FALSE(mode & FILE_PERMISSION_WRITE_BY_USER);
1279   // Make sure the file can't be write.
1280   EXPECT_FALSE(WriteFile(file_name, kData));
1281   EXPECT_FALSE(PathIsWritable(file_name));
1282 
1283   // Give read permission.
1284   EXPECT_TRUE(SetPosixFilePermissions(file_name,
1285                                       FILE_PERMISSION_WRITE_BY_USER));
1286   EXPECT_TRUE(GetPosixFilePermissions(file_name, &mode));
1287   EXPECT_TRUE(mode & FILE_PERMISSION_WRITE_BY_USER);
1288   // Make sure the file can be write.
1289   EXPECT_TRUE(WriteFile(file_name, kData));
1290   EXPECT_TRUE(PathIsWritable(file_name));
1291 
1292   // Delete the file.
1293   EXPECT_TRUE(DeleteFile(file_name));
1294   EXPECT_FALSE(PathExists(file_name));
1295 }
1296 
TEST_F(FileUtilTest,ChangeDirectoryPermissionsAndEnumerate)1297 TEST_F(FileUtilTest, ChangeDirectoryPermissionsAndEnumerate) {
1298   // Create a directory path.
1299   FilePath subdir_path = temp_dir_.GetPath().Append(FPL("PermissionTest1"));
1300   CreateDirectory(subdir_path);
1301   ASSERT_TRUE(PathExists(subdir_path));
1302 
1303   // Create a dummy file to enumerate.
1304   FilePath file_name = subdir_path.Append(FPL("Test Readable File.txt"));
1305   EXPECT_FALSE(PathExists(file_name));
1306   const std::string kData("hello");
1307   EXPECT_TRUE(WriteFile(file_name, kData));
1308   EXPECT_TRUE(PathExists(file_name));
1309 
1310   // Make sure the directory has the all permissions.
1311   int mode = 0;
1312   EXPECT_TRUE(GetPosixFilePermissions(subdir_path, &mode));
1313   EXPECT_EQ(FILE_PERMISSION_USER_MASK, mode & FILE_PERMISSION_USER_MASK);
1314 
1315   // Get rid of the permissions from the directory.
1316   EXPECT_TRUE(SetPosixFilePermissions(subdir_path, 0u));
1317   EXPECT_TRUE(GetPosixFilePermissions(subdir_path, &mode));
1318   EXPECT_FALSE(mode & FILE_PERMISSION_USER_MASK);
1319 
1320   // Make sure the file in the directory can't be enumerated.
1321   FileEnumerator f1(subdir_path, true, FileEnumerator::FILES);
1322   EXPECT_TRUE(PathExists(subdir_path));
1323   FindResultCollector c1(&f1);
1324   EXPECT_EQ(0, c1.size());
1325   EXPECT_FALSE(GetPosixFilePermissions(file_name, &mode));
1326 
1327   // Give the permissions to the directory.
1328   EXPECT_TRUE(SetPosixFilePermissions(subdir_path, FILE_PERMISSION_USER_MASK));
1329   EXPECT_TRUE(GetPosixFilePermissions(subdir_path, &mode));
1330   EXPECT_EQ(FILE_PERMISSION_USER_MASK, mode & FILE_PERMISSION_USER_MASK);
1331 
1332   // Make sure the file in the directory can be enumerated.
1333   FileEnumerator f2(subdir_path, true, FileEnumerator::FILES);
1334   FindResultCollector c2(&f2);
1335   EXPECT_TRUE(c2.HasFile(file_name));
1336   EXPECT_EQ(1, c2.size());
1337 
1338   // Delete the file.
1339   EXPECT_TRUE(DeletePathRecursively(subdir_path));
1340   EXPECT_FALSE(PathExists(subdir_path));
1341 }
1342 
TEST_F(FileUtilTest,ExecutableExistsInPath)1343 TEST_F(FileUtilTest, ExecutableExistsInPath) {
1344   // Create two directories that we will put in our PATH
1345   const FilePath::CharType kDir1[] = FPL("dir1");
1346   const FilePath::CharType kDir2[] = FPL("dir2");
1347 
1348   FilePath dir1 = temp_dir_.GetPath().Append(kDir1);
1349   FilePath dir2 = temp_dir_.GetPath().Append(kDir2);
1350   ASSERT_TRUE(CreateDirectory(dir1));
1351   ASSERT_TRUE(CreateDirectory(dir2));
1352 
1353   ScopedEnvironmentVariableOverride scoped_env(
1354       "PATH", dir1.value() + ":" + dir2.value());
1355   ASSERT_TRUE(scoped_env.IsOverridden());
1356 
1357   const FilePath::CharType kRegularFileName[] = FPL("regular_file");
1358   const FilePath::CharType kExeFileName[] = FPL("exe");
1359   const FilePath::CharType kDneFileName[] = FPL("does_not_exist");
1360 
1361   const FilePath kExePath = dir1.Append(kExeFileName);
1362   const FilePath kRegularFilePath = dir2.Append(kRegularFileName);
1363 
1364   // Write file.
1365   const std::string kData("hello");
1366   ASSERT_TRUE(WriteFile(kExePath, kData));
1367   ASSERT_TRUE(PathExists(kExePath));
1368   ASSERT_TRUE(WriteFile(kRegularFilePath, kData));
1369   ASSERT_TRUE(PathExists(kRegularFilePath));
1370 
1371   ASSERT_TRUE(SetPosixFilePermissions(dir1.Append(kExeFileName),
1372                                       FILE_PERMISSION_EXECUTE_BY_USER));
1373 
1374   EXPECT_TRUE(ExecutableExistsInPath(scoped_env.GetEnv(), kExeFileName));
1375   EXPECT_FALSE(ExecutableExistsInPath(scoped_env.GetEnv(), kRegularFileName));
1376   EXPECT_FALSE(ExecutableExistsInPath(scoped_env.GetEnv(), kDneFileName));
1377 }
1378 
TEST_F(FileUtilTest,CopyDirectoryPermissions)1379 TEST_F(FileUtilTest, CopyDirectoryPermissions) {
1380   // Create a directory.
1381   FilePath dir_name_from =
1382       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
1383   CreateDirectory(dir_name_from);
1384   ASSERT_TRUE(PathExists(dir_name_from));
1385 
1386   // Create some regular files under the directory with various permissions.
1387   FilePath file_name_from =
1388       dir_name_from.Append(FILE_PATH_LITERAL("Reggy-1.txt"));
1389   CreateTextFile(file_name_from, L"Mordecai");
1390   ASSERT_TRUE(PathExists(file_name_from));
1391   ASSERT_TRUE(SetPosixFilePermissions(file_name_from, 0755));
1392 
1393   FilePath file2_name_from =
1394       dir_name_from.Append(FILE_PATH_LITERAL("Reggy-2.txt"));
1395   CreateTextFile(file2_name_from, L"Rigby");
1396   ASSERT_TRUE(PathExists(file2_name_from));
1397   ASSERT_TRUE(SetPosixFilePermissions(file2_name_from, 0777));
1398 
1399   FilePath file3_name_from =
1400       dir_name_from.Append(FILE_PATH_LITERAL("Reggy-3.txt"));
1401   CreateTextFile(file3_name_from, L"Benson");
1402   ASSERT_TRUE(PathExists(file3_name_from));
1403   ASSERT_TRUE(SetPosixFilePermissions(file3_name_from, 0400));
1404 
1405   // Copy the directory recursively.
1406   FilePath dir_name_to =
1407       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_To_Subdir"));
1408   FilePath file_name_to =
1409       dir_name_to.Append(FILE_PATH_LITERAL("Reggy-1.txt"));
1410   FilePath file2_name_to =
1411       dir_name_to.Append(FILE_PATH_LITERAL("Reggy-2.txt"));
1412   FilePath file3_name_to =
1413       dir_name_to.Append(FILE_PATH_LITERAL("Reggy-3.txt"));
1414 
1415   ASSERT_FALSE(PathExists(dir_name_to));
1416 
1417   EXPECT_TRUE(CopyDirectory(dir_name_from, dir_name_to, true));
1418   ASSERT_TRUE(PathExists(file_name_to));
1419   ASSERT_TRUE(PathExists(file2_name_to));
1420   ASSERT_TRUE(PathExists(file3_name_to));
1421 
1422   int mode = 0;
1423   int expected_mode;
1424   ASSERT_TRUE(GetPosixFilePermissions(file_name_to, &mode));
1425 #if BUILDFLAG(IS_APPLE)
1426   expected_mode = 0755;
1427 #elif BUILDFLAG(IS_CHROMEOS)
1428   expected_mode = 0644;
1429 #else
1430   expected_mode = 0600;
1431 #endif
1432   EXPECT_EQ(expected_mode, mode);
1433 
1434   ASSERT_TRUE(GetPosixFilePermissions(file2_name_to, &mode));
1435 #if BUILDFLAG(IS_APPLE)
1436   expected_mode = 0755;
1437 #elif BUILDFLAG(IS_CHROMEOS)
1438   expected_mode = 0644;
1439 #else
1440   expected_mode = 0600;
1441 #endif
1442   EXPECT_EQ(expected_mode, mode);
1443 
1444   ASSERT_TRUE(GetPosixFilePermissions(file3_name_to, &mode));
1445 #if BUILDFLAG(IS_APPLE)
1446   expected_mode = 0600;
1447 #elif BUILDFLAG(IS_CHROMEOS)
1448   expected_mode = 0644;
1449 #else
1450   expected_mode = 0600;
1451 #endif
1452   EXPECT_EQ(expected_mode, mode);
1453 }
1454 
TEST_F(FileUtilTest,CopyDirectoryPermissionsOverExistingFile)1455 TEST_F(FileUtilTest, CopyDirectoryPermissionsOverExistingFile) {
1456   // Create a directory.
1457   FilePath dir_name_from =
1458       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
1459   CreateDirectory(dir_name_from);
1460   ASSERT_TRUE(PathExists(dir_name_from));
1461 
1462   // Create a file under the directory.
1463   FilePath file_name_from =
1464       dir_name_from.Append(FILE_PATH_LITERAL("Reggy-1.txt"));
1465   CreateTextFile(file_name_from, L"Mordecai");
1466   ASSERT_TRUE(PathExists(file_name_from));
1467   ASSERT_TRUE(SetPosixFilePermissions(file_name_from, 0644));
1468 
1469   // Create a directory.
1470   FilePath dir_name_to =
1471       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_To_Subdir"));
1472   CreateDirectory(dir_name_to);
1473   ASSERT_TRUE(PathExists(dir_name_to));
1474 
1475   // Create a file under the directory with wider permissions.
1476   FilePath file_name_to =
1477       dir_name_to.Append(FILE_PATH_LITERAL("Reggy-1.txt"));
1478   CreateTextFile(file_name_to, L"Rigby");
1479   ASSERT_TRUE(PathExists(file_name_to));
1480   ASSERT_TRUE(SetPosixFilePermissions(file_name_to, 0777));
1481 
1482   // Ensure that when we copy the directory, the file contents are copied
1483   // but the permissions on the destination are left alone.
1484   EXPECT_TRUE(CopyDirectory(dir_name_from, dir_name_to, false));
1485   ASSERT_TRUE(PathExists(file_name_to));
1486   ASSERT_EQ(L"Mordecai", ReadTextFile(file_name_to));
1487 
1488   int mode = 0;
1489   ASSERT_TRUE(GetPosixFilePermissions(file_name_to, &mode));
1490   EXPECT_EQ(0777, mode);
1491 }
1492 
TEST_F(FileUtilTest,CopyDirectoryExclDoesNotOverwrite)1493 TEST_F(FileUtilTest, CopyDirectoryExclDoesNotOverwrite) {
1494   // Create source directory.
1495   FilePath dir_name_from =
1496       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
1497   CreateDirectory(dir_name_from);
1498   ASSERT_TRUE(PathExists(dir_name_from));
1499 
1500   // Create a file under the directory.
1501   FilePath file_name_from =
1502       dir_name_from.Append(FILE_PATH_LITERAL("Reggy-1.txt"));
1503   CreateTextFile(file_name_from, L"Mordecai");
1504   ASSERT_TRUE(PathExists(file_name_from));
1505 
1506   // Create destination directory.
1507   FilePath dir_name_to =
1508       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_To_Subdir"));
1509   CreateDirectory(dir_name_to);
1510   ASSERT_TRUE(PathExists(dir_name_to));
1511 
1512   // Create a file under the directory with the same name.
1513   FilePath file_name_to = dir_name_to.Append(FILE_PATH_LITERAL("Reggy-1.txt"));
1514   CreateTextFile(file_name_to, L"Rigby");
1515   ASSERT_TRUE(PathExists(file_name_to));
1516 
1517   // Ensure that copying failed and the file was not overwritten.
1518   EXPECT_FALSE(CopyDirectoryExcl(dir_name_from, dir_name_to, false));
1519   ASSERT_TRUE(PathExists(file_name_to));
1520   ASSERT_EQ(L"Rigby", ReadTextFile(file_name_to));
1521 }
1522 
TEST_F(FileUtilTest,CopyDirectoryExclDirectoryOverExistingFile)1523 TEST_F(FileUtilTest, CopyDirectoryExclDirectoryOverExistingFile) {
1524   // Create source directory.
1525   FilePath dir_name_from =
1526       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
1527   CreateDirectory(dir_name_from);
1528   ASSERT_TRUE(PathExists(dir_name_from));
1529 
1530   // Create a subdirectory.
1531   FilePath subdir_name_from = dir_name_from.Append(FILE_PATH_LITERAL("Subsub"));
1532   CreateDirectory(subdir_name_from);
1533   ASSERT_TRUE(PathExists(subdir_name_from));
1534 
1535   // Create destination directory.
1536   FilePath dir_name_to =
1537       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_To_Subdir"));
1538   CreateDirectory(dir_name_to);
1539   ASSERT_TRUE(PathExists(dir_name_to));
1540 
1541   // Create a regular file under the directory with the same name.
1542   FilePath file_name_to = dir_name_to.Append(FILE_PATH_LITERAL("Subsub"));
1543   CreateTextFile(file_name_to, L"Rigby");
1544   ASSERT_TRUE(PathExists(file_name_to));
1545 
1546   // Ensure that copying failed and the file was not overwritten.
1547   EXPECT_FALSE(CopyDirectoryExcl(dir_name_from, dir_name_to, false));
1548   ASSERT_TRUE(PathExists(file_name_to));
1549   ASSERT_EQ(L"Rigby", ReadTextFile(file_name_to));
1550 }
1551 
TEST_F(FileUtilTest,CopyDirectoryExclDirectoryOverExistingDirectory)1552 TEST_F(FileUtilTest, CopyDirectoryExclDirectoryOverExistingDirectory) {
1553   // Create source directory.
1554   FilePath dir_name_from =
1555       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
1556   CreateDirectory(dir_name_from);
1557   ASSERT_TRUE(PathExists(dir_name_from));
1558 
1559   // Create a subdirectory.
1560   FilePath subdir_name_from = dir_name_from.Append(FILE_PATH_LITERAL("Subsub"));
1561   CreateDirectory(subdir_name_from);
1562   ASSERT_TRUE(PathExists(subdir_name_from));
1563 
1564   // Create destination directory.
1565   FilePath dir_name_to =
1566       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_To_Subdir"));
1567   CreateDirectory(dir_name_to);
1568   ASSERT_TRUE(PathExists(dir_name_to));
1569 
1570   // Create a subdirectory under the directory with the same name.
1571   FilePath subdir_name_to = dir_name_to.Append(FILE_PATH_LITERAL("Subsub"));
1572   CreateDirectory(subdir_name_to);
1573   ASSERT_TRUE(PathExists(subdir_name_to));
1574 
1575   // Ensure that copying failed and the file was not overwritten.
1576   EXPECT_FALSE(CopyDirectoryExcl(dir_name_from, dir_name_to, false));
1577 }
1578 
TEST_F(FileUtilTest,CopyFileExecutablePermission)1579 TEST_F(FileUtilTest, CopyFileExecutablePermission) {
1580   FilePath src = temp_dir_.GetPath().Append(FPL("src.txt"));
1581   const std::wstring file_contents(L"Gooooooooooooooooooooogle");
1582   CreateTextFile(src, file_contents);
1583 
1584   ASSERT_TRUE(SetPosixFilePermissions(src, 0755));
1585   int mode = 0;
1586   ASSERT_TRUE(GetPosixFilePermissions(src, &mode));
1587   EXPECT_EQ(0755, mode);
1588 
1589   FilePath dst = temp_dir_.GetPath().Append(FPL("dst.txt"));
1590   ASSERT_TRUE(CopyFile(src, dst));
1591   EXPECT_EQ(file_contents, ReadTextFile(dst));
1592 
1593   ASSERT_TRUE(GetPosixFilePermissions(dst, &mode));
1594   int expected_mode;
1595 #if BUILDFLAG(IS_APPLE)
1596   expected_mode = 0755;
1597 #elif BUILDFLAG(IS_CHROMEOS)
1598   expected_mode = 0644;
1599 #else
1600   expected_mode = 0600;
1601 #endif
1602   EXPECT_EQ(expected_mode, mode);
1603   ASSERT_TRUE(DeleteFile(dst));
1604 
1605   ASSERT_TRUE(SetPosixFilePermissions(src, 0777));
1606   ASSERT_TRUE(GetPosixFilePermissions(src, &mode));
1607   EXPECT_EQ(0777, mode);
1608 
1609   ASSERT_TRUE(CopyFile(src, dst));
1610   EXPECT_EQ(file_contents, ReadTextFile(dst));
1611 
1612   ASSERT_TRUE(GetPosixFilePermissions(dst, &mode));
1613 #if BUILDFLAG(IS_APPLE)
1614   expected_mode = 0755;
1615 #elif BUILDFLAG(IS_CHROMEOS)
1616   expected_mode = 0644;
1617 #else
1618   expected_mode = 0600;
1619 #endif
1620   EXPECT_EQ(expected_mode, mode);
1621   ASSERT_TRUE(DeleteFile(dst));
1622 
1623   ASSERT_TRUE(SetPosixFilePermissions(src, 0400));
1624   ASSERT_TRUE(GetPosixFilePermissions(src, &mode));
1625   EXPECT_EQ(0400, mode);
1626 
1627   ASSERT_TRUE(CopyFile(src, dst));
1628   EXPECT_EQ(file_contents, ReadTextFile(dst));
1629 
1630   ASSERT_TRUE(GetPosixFilePermissions(dst, &mode));
1631 #if BUILDFLAG(IS_APPLE)
1632   expected_mode = 0600;
1633 #elif BUILDFLAG(IS_CHROMEOS)
1634   expected_mode = 0644;
1635 #else
1636   expected_mode = 0600;
1637 #endif
1638   EXPECT_EQ(expected_mode, mode);
1639 
1640   // This time, do not delete |dst|. Instead set its permissions to 0777.
1641   ASSERT_TRUE(SetPosixFilePermissions(dst, 0777));
1642   ASSERT_TRUE(GetPosixFilePermissions(dst, &mode));
1643   EXPECT_EQ(0777, mode);
1644 
1645   // Overwrite it and check the permissions again.
1646   ASSERT_TRUE(CopyFile(src, dst));
1647   EXPECT_EQ(file_contents, ReadTextFile(dst));
1648   ASSERT_TRUE(GetPosixFilePermissions(dst, &mode));
1649   EXPECT_EQ(0777, mode);
1650 }
1651 
1652 #endif  // BUILDFLAG(IS_POSIX)
1653 
1654 #if !BUILDFLAG(IS_FUCHSIA)
1655 
TEST_F(FileUtilTest,CopyFileACL)1656 TEST_F(FileUtilTest, CopyFileACL) {
1657   // While FileUtilTest.CopyFile asserts the content is correctly copied over,
1658   // this test case asserts the access control bits are meeting expectations in
1659   // CopyFile().
1660   FilePath src = temp_dir_.GetPath().Append(FILE_PATH_LITERAL("src.txt"));
1661   const std::wstring file_contents(L"Gooooooooooooooooooooogle");
1662   CreateTextFile(src, file_contents);
1663 
1664   // Set the source file to read-only.
1665   ASSERT_FALSE(IsReadOnly(src));
1666   SetReadOnly(src, true);
1667   ASSERT_TRUE(IsReadOnly(src));
1668 
1669   // Copy the file.
1670   FilePath dst = temp_dir_.GetPath().Append(FILE_PATH_LITERAL("dst.txt"));
1671   ASSERT_TRUE(CopyFile(src, dst));
1672   EXPECT_EQ(file_contents, ReadTextFile(dst));
1673 
1674   ASSERT_FALSE(IsReadOnly(dst));
1675 }
1676 
TEST_F(FileUtilTest,CopyDirectoryACL)1677 TEST_F(FileUtilTest, CopyDirectoryACL) {
1678   // Create source directories.
1679   FilePath src = temp_dir_.GetPath().Append(FILE_PATH_LITERAL("src"));
1680   FilePath src_subdir = src.Append(FILE_PATH_LITERAL("subdir"));
1681   CreateDirectory(src_subdir);
1682   ASSERT_TRUE(PathExists(src_subdir));
1683 
1684   // Create a file under the directory.
1685   FilePath src_file = src.Append(FILE_PATH_LITERAL("src.txt"));
1686   CreateTextFile(src_file, L"Gooooooooooooooooooooogle");
1687   SetReadOnly(src_file, true);
1688   ASSERT_TRUE(IsReadOnly(src_file));
1689 
1690   // Make directory read-only.
1691   SetReadOnly(src_subdir, true);
1692   ASSERT_TRUE(IsReadOnly(src_subdir));
1693 
1694   // Copy the directory recursively.
1695   FilePath dst = temp_dir_.GetPath().Append(FILE_PATH_LITERAL("dst"));
1696   FilePath dst_file = dst.Append(FILE_PATH_LITERAL("src.txt"));
1697   EXPECT_TRUE(CopyDirectory(src, dst, true));
1698 
1699   FilePath dst_subdir = dst.Append(FILE_PATH_LITERAL("subdir"));
1700   ASSERT_FALSE(IsReadOnly(dst_subdir));
1701   ASSERT_FALSE(IsReadOnly(dst_file));
1702 
1703   // Give write permissions to allow deletion.
1704   SetReadOnly(src_subdir, false);
1705   ASSERT_FALSE(IsReadOnly(src_subdir));
1706 }
1707 
1708 #endif  // !BUILDFLAG(IS_FUCHSIA)
1709 
TEST_F(FileUtilTest,DeleteNonExistent)1710 TEST_F(FileUtilTest, DeleteNonExistent) {
1711   FilePath non_existent =
1712       temp_dir_.GetPath().AppendASCII("bogus_file_dne.foobar");
1713   ASSERT_FALSE(PathExists(non_existent));
1714 
1715   EXPECT_TRUE(DeleteFile(non_existent));
1716   ASSERT_FALSE(PathExists(non_existent));
1717   EXPECT_TRUE(DeletePathRecursively(non_existent));
1718   ASSERT_FALSE(PathExists(non_existent));
1719 }
1720 
TEST_F(FileUtilTest,DeleteNonExistentWithNonExistentParent)1721 TEST_F(FileUtilTest, DeleteNonExistentWithNonExistentParent) {
1722   FilePath non_existent = temp_dir_.GetPath().AppendASCII("bogus_topdir");
1723   non_existent = non_existent.AppendASCII("bogus_subdir");
1724   ASSERT_FALSE(PathExists(non_existent));
1725 
1726   EXPECT_TRUE(DeleteFile(non_existent));
1727   ASSERT_FALSE(PathExists(non_existent));
1728   EXPECT_TRUE(DeletePathRecursively(non_existent));
1729   ASSERT_FALSE(PathExists(non_existent));
1730 }
1731 
TEST_F(FileUtilTest,DeleteFile)1732 TEST_F(FileUtilTest, DeleteFile) {
1733   // Create a file
1734   FilePath file_name = temp_dir_.GetPath().Append(FPL("Test DeleteFile 1.txt"));
1735   CreateTextFile(file_name, bogus_content);
1736   ASSERT_TRUE(PathExists(file_name));
1737 
1738   // Make sure it's deleted
1739   EXPECT_TRUE(DeleteFile(file_name));
1740   EXPECT_FALSE(PathExists(file_name));
1741 
1742   // Test recursive case, create a new file
1743   file_name = temp_dir_.GetPath().Append(FPL("Test DeleteFile 2.txt"));
1744   CreateTextFile(file_name, bogus_content);
1745   ASSERT_TRUE(PathExists(file_name));
1746 
1747   // Make sure it's deleted
1748   EXPECT_TRUE(DeletePathRecursively(file_name));
1749   EXPECT_FALSE(PathExists(file_name));
1750 }
1751 
1752 #if BUILDFLAG(IS_ANDROID)
TEST_F(FileUtilTest,DeleteContentUri)1753 TEST_F(FileUtilTest, DeleteContentUri) {
1754   // Get the path to the test file.
1755   FilePath data_dir;
1756   ASSERT_TRUE(PathService::Get(DIR_TEST_DATA, &data_dir));
1757   data_dir = data_dir.Append(FPL("file_util"));
1758   ASSERT_TRUE(PathExists(data_dir));
1759   FilePath image_file = data_dir.Append(FPL("red.png"));
1760   ASSERT_TRUE(PathExists(image_file));
1761 
1762   // Make a copy (we don't want to delete the original red.png when deleting the
1763   // content URI).
1764   FilePath image_copy = data_dir.Append(FPL("redcopy.png"));
1765   ASSERT_TRUE(CopyFile(image_file, image_copy));
1766 
1767   // Insert the image into MediaStore and get a content URI.
1768   FilePath uri_path = InsertImageIntoMediaStore(image_copy);
1769   ASSERT_TRUE(uri_path.IsContentUri());
1770   ASSERT_TRUE(PathExists(uri_path));
1771 
1772   // Try deleting the content URI.
1773   EXPECT_TRUE(DeleteFile(uri_path));
1774   EXPECT_FALSE(PathExists(image_copy));
1775   EXPECT_FALSE(PathExists(uri_path));
1776 }
1777 #endif  // BUILDFLAG(IS_ANDROID)
1778 
1779 #if BUILDFLAG(IS_WIN)
1780 // Tests that the Delete function works for wild cards, especially
1781 // with the recursion flag.  Also coincidentally tests PathExists.
1782 // TODO(erikkay): see if anyone's actually using this feature of the API
TEST_F(FileUtilTest,DeleteWildCard)1783 TEST_F(FileUtilTest, DeleteWildCard) {
1784   // Create a file and a directory
1785   FilePath file_name =
1786       temp_dir_.GetPath().Append(FPL("Test DeleteWildCard.txt"));
1787   CreateTextFile(file_name, bogus_content);
1788   ASSERT_TRUE(PathExists(file_name));
1789 
1790   FilePath subdir_path = temp_dir_.GetPath().Append(FPL("DeleteWildCardDir"));
1791   CreateDirectory(subdir_path);
1792   ASSERT_TRUE(PathExists(subdir_path));
1793 
1794   // Create the wildcard path
1795   FilePath directory_contents = temp_dir_.GetPath();
1796   directory_contents = directory_contents.Append(FPL("*"));
1797 
1798   // Delete non-recursively and check that only the file is deleted
1799   EXPECT_TRUE(DeleteFile(directory_contents));
1800   EXPECT_FALSE(PathExists(file_name));
1801   EXPECT_TRUE(PathExists(subdir_path));
1802 
1803   // Delete recursively and make sure all contents are deleted
1804   EXPECT_TRUE(DeletePathRecursively(directory_contents));
1805   EXPECT_FALSE(PathExists(file_name));
1806   EXPECT_FALSE(PathExists(subdir_path));
1807 }
1808 
1809 // TODO(erikkay): see if anyone's actually using this feature of the API
TEST_F(FileUtilTest,DeleteNonExistantWildCard)1810 TEST_F(FileUtilTest, DeleteNonExistantWildCard) {
1811   // Create a file and a directory
1812   FilePath subdir_path =
1813       temp_dir_.GetPath().Append(FPL("DeleteNonExistantWildCard"));
1814   CreateDirectory(subdir_path);
1815   ASSERT_TRUE(PathExists(subdir_path));
1816 
1817   // Create the wildcard path
1818   FilePath directory_contents = subdir_path;
1819   directory_contents = directory_contents.Append(FPL("*"));
1820 
1821   // Delete non-recursively and check nothing got deleted
1822   EXPECT_TRUE(DeleteFile(directory_contents));
1823   EXPECT_TRUE(PathExists(subdir_path));
1824 
1825   // Delete recursively and check nothing got deleted
1826   EXPECT_TRUE(DeletePathRecursively(directory_contents));
1827   EXPECT_TRUE(PathExists(subdir_path));
1828 }
1829 #endif
1830 
1831 // Tests non-recursive Delete() for a directory.
TEST_F(FileUtilTest,DeleteDirNonRecursive)1832 TEST_F(FileUtilTest, DeleteDirNonRecursive) {
1833   // Create a subdirectory and put a file and two directories inside.
1834   FilePath test_subdir =
1835       temp_dir_.GetPath().Append(FPL("DeleteDirNonRecursive"));
1836   CreateDirectory(test_subdir);
1837   ASSERT_TRUE(PathExists(test_subdir));
1838 
1839   FilePath file_name = test_subdir.Append(FPL("Test DeleteDir.txt"));
1840   CreateTextFile(file_name, bogus_content);
1841   ASSERT_TRUE(PathExists(file_name));
1842 
1843   FilePath subdir_path1 = test_subdir.Append(FPL("TestSubDir1"));
1844   CreateDirectory(subdir_path1);
1845   ASSERT_TRUE(PathExists(subdir_path1));
1846 
1847   FilePath subdir_path2 = test_subdir.Append(FPL("TestSubDir2"));
1848   CreateDirectory(subdir_path2);
1849   ASSERT_TRUE(PathExists(subdir_path2));
1850 
1851   // Delete non-recursively and check that the empty dir got deleted
1852   EXPECT_TRUE(DeleteFile(subdir_path2));
1853   EXPECT_FALSE(PathExists(subdir_path2));
1854 
1855   // Delete non-recursively and check that nothing got deleted
1856   EXPECT_FALSE(DeleteFile(test_subdir));
1857   EXPECT_TRUE(PathExists(test_subdir));
1858   EXPECT_TRUE(PathExists(file_name));
1859   EXPECT_TRUE(PathExists(subdir_path1));
1860 }
1861 
1862 // Tests recursive Delete() for a directory.
TEST_F(FileUtilTest,DeleteDirRecursive)1863 TEST_F(FileUtilTest, DeleteDirRecursive) {
1864   // Create a subdirectory and put a file and two directories inside.
1865   FilePath test_subdir = temp_dir_.GetPath().Append(FPL("DeleteDirRecursive"));
1866   CreateDirectory(test_subdir);
1867   ASSERT_TRUE(PathExists(test_subdir));
1868 
1869   FilePath file_name = test_subdir.Append(FPL("Test DeleteDirRecursive.txt"));
1870   CreateTextFile(file_name, bogus_content);
1871   ASSERT_TRUE(PathExists(file_name));
1872 
1873   FilePath subdir_path1 = test_subdir.Append(FPL("TestSubDir1"));
1874   CreateDirectory(subdir_path1);
1875   ASSERT_TRUE(PathExists(subdir_path1));
1876 
1877   FilePath subdir_path2 = test_subdir.Append(FPL("TestSubDir2"));
1878   CreateDirectory(subdir_path2);
1879   ASSERT_TRUE(PathExists(subdir_path2));
1880 
1881   // Delete recursively and check that the empty dir got deleted
1882   EXPECT_TRUE(DeletePathRecursively(subdir_path2));
1883   EXPECT_FALSE(PathExists(subdir_path2));
1884 
1885   // Delete recursively and check that everything got deleted
1886   EXPECT_TRUE(DeletePathRecursively(test_subdir));
1887   EXPECT_FALSE(PathExists(file_name));
1888   EXPECT_FALSE(PathExists(subdir_path1));
1889   EXPECT_FALSE(PathExists(test_subdir));
1890 }
1891 
1892 // Tests recursive Delete() for a directory.
TEST_F(FileUtilTest,DeleteDirRecursiveWithOpenFile)1893 TEST_F(FileUtilTest, DeleteDirRecursiveWithOpenFile) {
1894   // Create a subdirectory and put a file and two directories inside.
1895   FilePath test_subdir = temp_dir_.GetPath().Append(FPL("DeleteWithOpenFile"));
1896   CreateDirectory(test_subdir);
1897   ASSERT_TRUE(PathExists(test_subdir));
1898 
1899   FilePath file_name1 = test_subdir.Append(FPL("Undeletebable File1.txt"));
1900   File file1(file_name1,
1901              File::FLAG_CREATE | File::FLAG_READ | File::FLAG_WRITE);
1902   ASSERT_TRUE(PathExists(file_name1));
1903 
1904   FilePath file_name2 = test_subdir.Append(FPL("Deleteable File2.txt"));
1905   CreateTextFile(file_name2, bogus_content);
1906   ASSERT_TRUE(PathExists(file_name2));
1907 
1908   FilePath file_name3 = test_subdir.Append(FPL("Undeletebable File3.txt"));
1909   File file3(file_name3,
1910              File::FLAG_CREATE | File::FLAG_READ | File::FLAG_WRITE);
1911   ASSERT_TRUE(PathExists(file_name3));
1912 
1913 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
1914   // On Windows, holding the file open in sufficient to make it un-deletable.
1915   // The POSIX code is verifiable on Linux by creating an "immutable" file but
1916   // this is best-effort because it's not supported by all file systems. Both
1917   // files will have the same flags so no need to get them individually.
1918   int flags;
1919   bool file_attrs_supported =
1920       ioctl(file1.GetPlatformFile(), FS_IOC_GETFLAGS, &flags) == 0;
1921   // Some filesystems (e.g. tmpfs) don't support file attributes.
1922   if (file_attrs_supported) {
1923     flags |= FS_IMMUTABLE_FL;
1924     ioctl(file1.GetPlatformFile(), FS_IOC_SETFLAGS, &flags);
1925     ioctl(file3.GetPlatformFile(), FS_IOC_SETFLAGS, &flags);
1926   }
1927 #endif
1928 
1929   // Delete recursively and check that at least the second file got deleted.
1930   // This ensures that un-deletable files don't impact those that can be.
1931   DeletePathRecursively(test_subdir);
1932   EXPECT_FALSE(PathExists(file_name2));
1933 
1934 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
1935   // Make sure that the test can clean up after itself.
1936   if (file_attrs_supported) {
1937     flags &= ~FS_IMMUTABLE_FL;
1938     ioctl(file1.GetPlatformFile(), FS_IOC_SETFLAGS, &flags);
1939     ioctl(file3.GetPlatformFile(), FS_IOC_SETFLAGS, &flags);
1940   }
1941 #endif
1942 }
1943 
1944 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
1945 // This test will validate that files which would block when read result in a
1946 // failure on a call to ReadFileToStringNonBlocking. To accomplish this we will
1947 // use a named pipe because it appears as a file on disk and we can control how
1948 // much data is available to read. This allows us to simulate a file which would
1949 // block.
TEST_F(FileUtilTest,TestNonBlockingFileReadLinux)1950 TEST_F(FileUtilTest, TestNonBlockingFileReadLinux) {
1951   FilePath fifo_path = temp_dir_.GetPath().Append(FPL("fifo"));
1952   int res = mkfifo(fifo_path.MaybeAsASCII().c_str(),
1953                    S_IWUSR | S_IRUSR | S_IWGRP | S_IWGRP);
1954   ASSERT_NE(res, -1);
1955 
1956   base::ScopedFD fd(open(fifo_path.MaybeAsASCII().c_str(), O_RDWR));
1957   ASSERT_TRUE(fd.is_valid());
1958 
1959   std::string result;
1960   // We will try to read when nothing is available on the fifo, the output
1961   // string will be unmodified and it will fail with EWOULDBLOCK.
1962   ASSERT_FALSE(ReadFileToStringNonBlocking(fifo_path, &result));
1963   EXPECT_EQ(errno, EWOULDBLOCK);
1964   EXPECT_TRUE(result.empty());
1965 
1966   // Make a single byte available to read on the FIFO.
1967   ASSERT_EQ(write(fd.get(), "a", 1), 1);
1968 
1969   // Now the key part of the test we will call ReadFromFileNonBlocking which
1970   // should fail, errno will be EWOULDBLOCK and the output string will contain
1971   // the single 'a' byte.
1972   ASSERT_FALSE(ReadFileToStringNonBlocking(fifo_path, &result));
1973   EXPECT_EQ(errno, EWOULDBLOCK);
1974   ASSERT_EQ(result.size(), 1u);
1975   EXPECT_EQ(result[0], 'a');
1976 }
1977 #endif  // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
1978 
TEST_F(FileUtilTest,MoveFileNew)1979 TEST_F(FileUtilTest, MoveFileNew) {
1980   // Create a file
1981   FilePath file_name_from =
1982       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Move_Test_File.txt"));
1983   CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
1984   ASSERT_TRUE(PathExists(file_name_from));
1985 
1986   // The destination.
1987   FilePath file_name_to = temp_dir_.GetPath().Append(
1988       FILE_PATH_LITERAL("Move_Test_File_Destination.txt"));
1989   ASSERT_FALSE(PathExists(file_name_to));
1990 
1991   EXPECT_TRUE(Move(file_name_from, file_name_to));
1992 
1993   // Check everything has been moved.
1994   EXPECT_FALSE(PathExists(file_name_from));
1995   EXPECT_TRUE(PathExists(file_name_to));
1996 }
1997 
TEST_F(FileUtilTest,MoveFileExists)1998 TEST_F(FileUtilTest, MoveFileExists) {
1999   // Create a file
2000   FilePath file_name_from =
2001       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Move_Test_File.txt"));
2002   CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
2003   ASSERT_TRUE(PathExists(file_name_from));
2004 
2005   // The destination name.
2006   FilePath file_name_to = temp_dir_.GetPath().Append(
2007       FILE_PATH_LITERAL("Move_Test_File_Destination.txt"));
2008   CreateTextFile(file_name_to, L"Old file content");
2009   ASSERT_TRUE(PathExists(file_name_to));
2010 
2011   EXPECT_TRUE(Move(file_name_from, file_name_to));
2012 
2013   // Check everything has been moved.
2014   EXPECT_FALSE(PathExists(file_name_from));
2015   EXPECT_TRUE(PathExists(file_name_to));
2016   EXPECT_TRUE(L"Gooooooooooooooooooooogle" == ReadTextFile(file_name_to));
2017 }
2018 
TEST_F(FileUtilTest,MoveFileDirExists)2019 TEST_F(FileUtilTest, MoveFileDirExists) {
2020   // Create a file
2021   FilePath file_name_from =
2022       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Move_Test_File.txt"));
2023   CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
2024   ASSERT_TRUE(PathExists(file_name_from));
2025 
2026   // The destination directory
2027   FilePath dir_name_to =
2028       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Destination"));
2029   CreateDirectory(dir_name_to);
2030   ASSERT_TRUE(PathExists(dir_name_to));
2031 
2032   EXPECT_FALSE(Move(file_name_from, dir_name_to));
2033 }
2034 
2035 
TEST_F(FileUtilTest,MoveNew)2036 TEST_F(FileUtilTest, MoveNew) {
2037   // Create a directory
2038   FilePath dir_name_from =
2039       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Move_From_Subdir"));
2040   CreateDirectory(dir_name_from);
2041   ASSERT_TRUE(PathExists(dir_name_from));
2042 
2043   // Create a file under the directory
2044   FilePath txt_file_name(FILE_PATH_LITERAL("Move_Test_File.txt"));
2045   FilePath file_name_from = dir_name_from.Append(txt_file_name);
2046   CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
2047   ASSERT_TRUE(PathExists(file_name_from));
2048 
2049   // Move the directory.
2050   FilePath dir_name_to =
2051       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Move_To_Subdir"));
2052   FilePath file_name_to =
2053       dir_name_to.Append(FILE_PATH_LITERAL("Move_Test_File.txt"));
2054 
2055   ASSERT_FALSE(PathExists(dir_name_to));
2056 
2057   EXPECT_TRUE(Move(dir_name_from, dir_name_to));
2058 
2059   // Check everything has been moved.
2060   EXPECT_FALSE(PathExists(dir_name_from));
2061   EXPECT_FALSE(PathExists(file_name_from));
2062   EXPECT_TRUE(PathExists(dir_name_to));
2063   EXPECT_TRUE(PathExists(file_name_to));
2064 
2065   // Test path traversal.
2066   file_name_from = dir_name_to.Append(txt_file_name);
2067   file_name_to = dir_name_to.Append(FILE_PATH_LITERAL(".."));
2068   file_name_to = file_name_to.Append(txt_file_name);
2069   EXPECT_FALSE(Move(file_name_from, file_name_to));
2070   EXPECT_TRUE(PathExists(file_name_from));
2071   EXPECT_FALSE(PathExists(file_name_to));
2072   EXPECT_TRUE(internal::MoveUnsafe(file_name_from, file_name_to));
2073   EXPECT_FALSE(PathExists(file_name_from));
2074   EXPECT_TRUE(PathExists(file_name_to));
2075 }
2076 
TEST_F(FileUtilTest,MoveExist)2077 TEST_F(FileUtilTest, MoveExist) {
2078   // Create a directory
2079   FilePath dir_name_from =
2080       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Move_From_Subdir"));
2081   CreateDirectory(dir_name_from);
2082   ASSERT_TRUE(PathExists(dir_name_from));
2083 
2084   // Create a file under the directory
2085   FilePath file_name_from =
2086       dir_name_from.Append(FILE_PATH_LITERAL("Move_Test_File.txt"));
2087   CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
2088   ASSERT_TRUE(PathExists(file_name_from));
2089 
2090   // Move the directory
2091   FilePath dir_name_exists =
2092       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Destination"));
2093 
2094   FilePath dir_name_to =
2095       dir_name_exists.Append(FILE_PATH_LITERAL("Move_To_Subdir"));
2096   FilePath file_name_to =
2097       dir_name_to.Append(FILE_PATH_LITERAL("Move_Test_File.txt"));
2098 
2099   // Create the destination directory.
2100   CreateDirectory(dir_name_exists);
2101   ASSERT_TRUE(PathExists(dir_name_exists));
2102 
2103   EXPECT_TRUE(Move(dir_name_from, dir_name_to));
2104 
2105   // Check everything has been moved.
2106   EXPECT_FALSE(PathExists(dir_name_from));
2107   EXPECT_FALSE(PathExists(file_name_from));
2108   EXPECT_TRUE(PathExists(dir_name_to));
2109   EXPECT_TRUE(PathExists(file_name_to));
2110 }
2111 
TEST_F(FileUtilTest,CopyDirectoryRecursivelyNew)2112 TEST_F(FileUtilTest, CopyDirectoryRecursivelyNew) {
2113   // Create a directory.
2114   FilePath dir_name_from =
2115       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
2116   CreateDirectory(dir_name_from);
2117   ASSERT_TRUE(PathExists(dir_name_from));
2118 
2119   // Create a file under the directory.
2120   FilePath file_name_from =
2121       dir_name_from.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
2122   CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
2123   ASSERT_TRUE(PathExists(file_name_from));
2124 
2125   // Create a subdirectory.
2126   FilePath subdir_name_from =
2127       dir_name_from.Append(FILE_PATH_LITERAL("Subdir"));
2128   CreateDirectory(subdir_name_from);
2129   ASSERT_TRUE(PathExists(subdir_name_from));
2130 
2131   // Create a file under the subdirectory.
2132   FilePath file_name2_from =
2133       subdir_name_from.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
2134   CreateTextFile(file_name2_from, L"Gooooooooooooooooooooogle");
2135   ASSERT_TRUE(PathExists(file_name2_from));
2136 
2137   // Copy the directory recursively.
2138   FilePath dir_name_to =
2139       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_To_Subdir"));
2140   FilePath file_name_to =
2141       dir_name_to.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
2142   FilePath subdir_name_to =
2143       dir_name_to.Append(FILE_PATH_LITERAL("Subdir"));
2144   FilePath file_name2_to =
2145       subdir_name_to.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
2146 
2147   ASSERT_FALSE(PathExists(dir_name_to));
2148 
2149   EXPECT_TRUE(CopyDirectory(dir_name_from, dir_name_to, true));
2150 
2151   // Check everything has been copied.
2152   EXPECT_TRUE(PathExists(dir_name_from));
2153   EXPECT_TRUE(PathExists(file_name_from));
2154   EXPECT_TRUE(PathExists(subdir_name_from));
2155   EXPECT_TRUE(PathExists(file_name2_from));
2156   EXPECT_TRUE(PathExists(dir_name_to));
2157   EXPECT_TRUE(PathExists(file_name_to));
2158   EXPECT_TRUE(PathExists(subdir_name_to));
2159   EXPECT_TRUE(PathExists(file_name2_to));
2160 }
2161 
TEST_F(FileUtilTest,CopyDirectoryRecursivelyExists)2162 TEST_F(FileUtilTest, CopyDirectoryRecursivelyExists) {
2163   // Create a directory.
2164   FilePath dir_name_from =
2165       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
2166   CreateDirectory(dir_name_from);
2167   ASSERT_TRUE(PathExists(dir_name_from));
2168 
2169   // Create a file under the directory.
2170   FilePath file_name_from =
2171       dir_name_from.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
2172   CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
2173   ASSERT_TRUE(PathExists(file_name_from));
2174 
2175   // Create a subdirectory.
2176   FilePath subdir_name_from =
2177       dir_name_from.Append(FILE_PATH_LITERAL("Subdir"));
2178   CreateDirectory(subdir_name_from);
2179   ASSERT_TRUE(PathExists(subdir_name_from));
2180 
2181   // Create a file under the subdirectory.
2182   FilePath file_name2_from =
2183       subdir_name_from.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
2184   CreateTextFile(file_name2_from, L"Gooooooooooooooooooooogle");
2185   ASSERT_TRUE(PathExists(file_name2_from));
2186 
2187   // Copy the directory recursively.
2188   FilePath dir_name_exists =
2189       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Destination"));
2190 
2191   FilePath dir_name_to =
2192       dir_name_exists.Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
2193   FilePath file_name_to =
2194       dir_name_to.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
2195   FilePath subdir_name_to =
2196       dir_name_to.Append(FILE_PATH_LITERAL("Subdir"));
2197   FilePath file_name2_to =
2198       subdir_name_to.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
2199 
2200   // Create the destination directory.
2201   CreateDirectory(dir_name_exists);
2202   ASSERT_TRUE(PathExists(dir_name_exists));
2203 
2204   EXPECT_TRUE(CopyDirectory(dir_name_from, dir_name_exists, true));
2205 
2206   // Check everything has been copied.
2207   EXPECT_TRUE(PathExists(dir_name_from));
2208   EXPECT_TRUE(PathExists(file_name_from));
2209   EXPECT_TRUE(PathExists(subdir_name_from));
2210   EXPECT_TRUE(PathExists(file_name2_from));
2211   EXPECT_TRUE(PathExists(dir_name_to));
2212   EXPECT_TRUE(PathExists(file_name_to));
2213   EXPECT_TRUE(PathExists(subdir_name_to));
2214   EXPECT_TRUE(PathExists(file_name2_to));
2215 }
2216 
TEST_F(FileUtilTest,CopyDirectoryNew)2217 TEST_F(FileUtilTest, CopyDirectoryNew) {
2218   // Create a directory.
2219   FilePath dir_name_from =
2220       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
2221   CreateDirectory(dir_name_from);
2222   ASSERT_TRUE(PathExists(dir_name_from));
2223 
2224   // Create a file under the directory.
2225   FilePath file_name_from =
2226       dir_name_from.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
2227   CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
2228   ASSERT_TRUE(PathExists(file_name_from));
2229 
2230   // Create a subdirectory.
2231   FilePath subdir_name_from =
2232       dir_name_from.Append(FILE_PATH_LITERAL("Subdir"));
2233   CreateDirectory(subdir_name_from);
2234   ASSERT_TRUE(PathExists(subdir_name_from));
2235 
2236   // Create a file under the subdirectory.
2237   FilePath file_name2_from =
2238       subdir_name_from.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
2239   CreateTextFile(file_name2_from, L"Gooooooooooooooooooooogle");
2240   ASSERT_TRUE(PathExists(file_name2_from));
2241 
2242   // Copy the directory not recursively.
2243   FilePath dir_name_to =
2244       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_To_Subdir"));
2245   FilePath file_name_to =
2246       dir_name_to.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
2247   FilePath subdir_name_to =
2248       dir_name_to.Append(FILE_PATH_LITERAL("Subdir"));
2249 
2250   ASSERT_FALSE(PathExists(dir_name_to));
2251 
2252   EXPECT_TRUE(CopyDirectory(dir_name_from, dir_name_to, false));
2253 
2254   // Check everything has been copied.
2255   EXPECT_TRUE(PathExists(dir_name_from));
2256   EXPECT_TRUE(PathExists(file_name_from));
2257   EXPECT_TRUE(PathExists(subdir_name_from));
2258   EXPECT_TRUE(PathExists(file_name2_from));
2259   EXPECT_TRUE(PathExists(dir_name_to));
2260   EXPECT_TRUE(PathExists(file_name_to));
2261   EXPECT_FALSE(PathExists(subdir_name_to));
2262 }
2263 
TEST_F(FileUtilTest,CopyDirectoryExists)2264 TEST_F(FileUtilTest, CopyDirectoryExists) {
2265   // Create a directory.
2266   FilePath dir_name_from =
2267       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
2268   CreateDirectory(dir_name_from);
2269   ASSERT_TRUE(PathExists(dir_name_from));
2270 
2271   // Create a file under the directory.
2272   FilePath file_name_from =
2273       dir_name_from.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
2274   CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
2275   ASSERT_TRUE(PathExists(file_name_from));
2276 
2277   // Create a subdirectory.
2278   FilePath subdir_name_from =
2279       dir_name_from.Append(FILE_PATH_LITERAL("Subdir"));
2280   CreateDirectory(subdir_name_from);
2281   ASSERT_TRUE(PathExists(subdir_name_from));
2282 
2283   // Create a file under the subdirectory.
2284   FilePath file_name2_from =
2285       subdir_name_from.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
2286   CreateTextFile(file_name2_from, L"Gooooooooooooooooooooogle");
2287   ASSERT_TRUE(PathExists(file_name2_from));
2288 
2289   // Copy the directory not recursively.
2290   FilePath dir_name_to =
2291       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_To_Subdir"));
2292   FilePath file_name_to =
2293       dir_name_to.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
2294   FilePath subdir_name_to =
2295       dir_name_to.Append(FILE_PATH_LITERAL("Subdir"));
2296 
2297   // Create the destination directory.
2298   CreateDirectory(dir_name_to);
2299   ASSERT_TRUE(PathExists(dir_name_to));
2300 
2301   EXPECT_TRUE(CopyDirectory(dir_name_from, dir_name_to, false));
2302 
2303   // Check everything has been copied.
2304   EXPECT_TRUE(PathExists(dir_name_from));
2305   EXPECT_TRUE(PathExists(file_name_from));
2306   EXPECT_TRUE(PathExists(subdir_name_from));
2307   EXPECT_TRUE(PathExists(file_name2_from));
2308   EXPECT_TRUE(PathExists(dir_name_to));
2309   EXPECT_TRUE(PathExists(file_name_to));
2310   EXPECT_FALSE(PathExists(subdir_name_to));
2311 }
2312 
TEST_F(FileUtilTest,CopyFileWithCopyDirectoryRecursiveToNew)2313 TEST_F(FileUtilTest, CopyFileWithCopyDirectoryRecursiveToNew) {
2314   // Create a file
2315   FilePath file_name_from =
2316       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
2317   CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
2318   ASSERT_TRUE(PathExists(file_name_from));
2319 
2320   // The destination name
2321   FilePath file_name_to = temp_dir_.GetPath().Append(
2322       FILE_PATH_LITERAL("Copy_Test_File_Destination.txt"));
2323   ASSERT_FALSE(PathExists(file_name_to));
2324 
2325   EXPECT_TRUE(CopyDirectory(file_name_from, file_name_to, true));
2326 
2327   // Check the has been copied
2328   EXPECT_TRUE(PathExists(file_name_to));
2329 }
2330 
TEST_F(FileUtilTest,CopyFileWithCopyDirectoryRecursiveToExisting)2331 TEST_F(FileUtilTest, CopyFileWithCopyDirectoryRecursiveToExisting) {
2332   // Create a file
2333   FilePath file_name_from =
2334       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
2335   CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
2336   ASSERT_TRUE(PathExists(file_name_from));
2337 
2338   // The destination name
2339   FilePath file_name_to = temp_dir_.GetPath().Append(
2340       FILE_PATH_LITERAL("Copy_Test_File_Destination.txt"));
2341   CreateTextFile(file_name_to, L"Old file content");
2342   ASSERT_TRUE(PathExists(file_name_to));
2343 
2344   EXPECT_TRUE(CopyDirectory(file_name_from, file_name_to, true));
2345 
2346   // Check the has been copied
2347   EXPECT_TRUE(PathExists(file_name_to));
2348   EXPECT_TRUE(L"Gooooooooooooooooooooogle" == ReadTextFile(file_name_to));
2349 }
2350 
TEST_F(FileUtilTest,CopyFileWithCopyDirectoryRecursiveToExistingDirectory)2351 TEST_F(FileUtilTest, CopyFileWithCopyDirectoryRecursiveToExistingDirectory) {
2352   // Create a file
2353   FilePath file_name_from =
2354       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
2355   CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
2356   ASSERT_TRUE(PathExists(file_name_from));
2357 
2358   // The destination
2359   FilePath dir_name_to =
2360       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Destination"));
2361   CreateDirectory(dir_name_to);
2362   ASSERT_TRUE(PathExists(dir_name_to));
2363   FilePath file_name_to =
2364       dir_name_to.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
2365 
2366   EXPECT_TRUE(CopyDirectory(file_name_from, dir_name_to, true));
2367 
2368   // Check the has been copied
2369   EXPECT_TRUE(PathExists(file_name_to));
2370 }
2371 
TEST_F(FileUtilTest,CopyFileFailureWithCopyDirectoryExcl)2372 TEST_F(FileUtilTest, CopyFileFailureWithCopyDirectoryExcl) {
2373   // Create a file
2374   FilePath file_name_from =
2375       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
2376   CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
2377   ASSERT_TRUE(PathExists(file_name_from));
2378 
2379   // Make a destination file.
2380   FilePath file_name_to = temp_dir_.GetPath().Append(
2381       FILE_PATH_LITERAL("Copy_Test_File_Destination.txt"));
2382   CreateTextFile(file_name_to, L"Old file content");
2383   ASSERT_TRUE(PathExists(file_name_to));
2384 
2385   // Overwriting the destination should fail.
2386   EXPECT_FALSE(CopyDirectoryExcl(file_name_from, file_name_to, true));
2387   EXPECT_EQ(L"Old file content", ReadTextFile(file_name_to));
2388 }
2389 
TEST_F(FileUtilTest,CopyDirectoryWithTrailingSeparators)2390 TEST_F(FileUtilTest, CopyDirectoryWithTrailingSeparators) {
2391   // Create a directory.
2392   FilePath dir_name_from =
2393       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
2394   CreateDirectory(dir_name_from);
2395   ASSERT_TRUE(PathExists(dir_name_from));
2396 
2397   // Create a file under the directory.
2398   FilePath file_name_from =
2399       dir_name_from.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
2400   CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
2401   ASSERT_TRUE(PathExists(file_name_from));
2402 
2403   // Copy the directory recursively.
2404   FilePath dir_name_to =
2405       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_To_Subdir"));
2406   FilePath file_name_to =
2407       dir_name_to.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
2408 
2409   // Create from path with trailing separators.
2410 #if BUILDFLAG(IS_WIN)
2411   FilePath from_path =
2412       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_From_Subdir\\\\\\"));
2413 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
2414   FilePath from_path =
2415       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_From_Subdir///"));
2416 #endif
2417 
2418   EXPECT_TRUE(CopyDirectory(from_path, dir_name_to, true));
2419 
2420   // Check everything has been copied.
2421   EXPECT_TRUE(PathExists(dir_name_from));
2422   EXPECT_TRUE(PathExists(file_name_from));
2423   EXPECT_TRUE(PathExists(dir_name_to));
2424   EXPECT_TRUE(PathExists(file_name_to));
2425 }
2426 
2427 #if BUILDFLAG(IS_POSIX)
TEST_F(FileUtilTest,CopyDirectoryWithNonRegularFiles)2428 TEST_F(FileUtilTest, CopyDirectoryWithNonRegularFiles) {
2429   // Create a directory.
2430   FilePath dir_name_from =
2431       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
2432   ASSERT_TRUE(CreateDirectory(dir_name_from));
2433   ASSERT_TRUE(PathExists(dir_name_from));
2434 
2435   // Create a file under the directory.
2436   FilePath file_name_from =
2437       dir_name_from.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
2438   CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
2439   ASSERT_TRUE(PathExists(file_name_from));
2440 
2441   // Create a symbolic link under the directory pointing to that file.
2442   FilePath symlink_name_from =
2443       dir_name_from.Append(FILE_PATH_LITERAL("Symlink"));
2444   ASSERT_TRUE(CreateSymbolicLink(file_name_from, symlink_name_from));
2445   ASSERT_TRUE(PathExists(symlink_name_from));
2446 
2447   // Create a fifo under the directory.
2448   FilePath fifo_name_from =
2449       dir_name_from.Append(FILE_PATH_LITERAL("Fifo"));
2450   ASSERT_EQ(0, mkfifo(fifo_name_from.value().c_str(), 0644));
2451   ASSERT_TRUE(PathExists(fifo_name_from));
2452 
2453   // Copy the directory.
2454   FilePath dir_name_to =
2455       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_To_Subdir"));
2456   FilePath file_name_to =
2457       dir_name_to.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
2458   FilePath symlink_name_to =
2459       dir_name_to.Append(FILE_PATH_LITERAL("Symlink"));
2460   FilePath fifo_name_to =
2461       dir_name_to.Append(FILE_PATH_LITERAL("Fifo"));
2462 
2463   ASSERT_FALSE(PathExists(dir_name_to));
2464 
2465   EXPECT_TRUE(CopyDirectory(dir_name_from, dir_name_to, false));
2466 
2467   // Check that only directories and regular files are copied.
2468   EXPECT_TRUE(PathExists(dir_name_from));
2469   EXPECT_TRUE(PathExists(file_name_from));
2470   EXPECT_TRUE(PathExists(symlink_name_from));
2471   EXPECT_TRUE(PathExists(fifo_name_from));
2472   EXPECT_TRUE(PathExists(dir_name_to));
2473   EXPECT_TRUE(PathExists(file_name_to));
2474   EXPECT_FALSE(PathExists(symlink_name_to));
2475   EXPECT_FALSE(PathExists(fifo_name_to));
2476 }
2477 
TEST_F(FileUtilTest,CopyDirectoryExclFileOverSymlink)2478 TEST_F(FileUtilTest, CopyDirectoryExclFileOverSymlink) {
2479   // Create a directory.
2480   FilePath dir_name_from =
2481       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
2482   ASSERT_TRUE(CreateDirectory(dir_name_from));
2483   ASSERT_TRUE(PathExists(dir_name_from));
2484 
2485   // Create a file under the directory.
2486   FilePath file_name_from =
2487       dir_name_from.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
2488   CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
2489   ASSERT_TRUE(PathExists(file_name_from));
2490 
2491   // Create a destination directory with a symlink of the same name.
2492   FilePath dir_name_to =
2493       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_To_Subdir"));
2494   ASSERT_TRUE(CreateDirectory(dir_name_to));
2495   ASSERT_TRUE(PathExists(dir_name_to));
2496 
2497   FilePath symlink_target =
2498       dir_name_to.Append(FILE_PATH_LITERAL("Symlink_Target.txt"));
2499   CreateTextFile(symlink_target, L"asdf");
2500   ASSERT_TRUE(PathExists(symlink_target));
2501 
2502   FilePath symlink_name_to =
2503       dir_name_to.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
2504   ASSERT_TRUE(CreateSymbolicLink(symlink_target, symlink_name_to));
2505   ASSERT_TRUE(PathExists(symlink_name_to));
2506 
2507   // Check that copying fails.
2508   EXPECT_FALSE(CopyDirectoryExcl(dir_name_from, dir_name_to, false));
2509 }
2510 
TEST_F(FileUtilTest,CopyDirectoryExclDirectoryOverSymlink)2511 TEST_F(FileUtilTest, CopyDirectoryExclDirectoryOverSymlink) {
2512   // Create a directory.
2513   FilePath dir_name_from =
2514       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
2515   ASSERT_TRUE(CreateDirectory(dir_name_from));
2516   ASSERT_TRUE(PathExists(dir_name_from));
2517 
2518   // Create a subdirectory.
2519   FilePath subdir_name_from = dir_name_from.Append(FILE_PATH_LITERAL("Subsub"));
2520   CreateDirectory(subdir_name_from);
2521   ASSERT_TRUE(PathExists(subdir_name_from));
2522 
2523   // Create a destination directory with a symlink of the same name.
2524   FilePath dir_name_to =
2525       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_To_Subdir"));
2526   ASSERT_TRUE(CreateDirectory(dir_name_to));
2527   ASSERT_TRUE(PathExists(dir_name_to));
2528 
2529   FilePath symlink_target = dir_name_to.Append(FILE_PATH_LITERAL("Subsub"));
2530   CreateTextFile(symlink_target, L"asdf");
2531   ASSERT_TRUE(PathExists(symlink_target));
2532 
2533   FilePath symlink_name_to =
2534       dir_name_to.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
2535   ASSERT_TRUE(CreateSymbolicLink(symlink_target, symlink_name_to));
2536   ASSERT_TRUE(PathExists(symlink_name_to));
2537 
2538   // Check that copying fails.
2539   EXPECT_FALSE(CopyDirectoryExcl(dir_name_from, dir_name_to, false));
2540 }
2541 
TEST_F(FileUtilTest,CopyDirectoryExclFileOverDanglingSymlink)2542 TEST_F(FileUtilTest, CopyDirectoryExclFileOverDanglingSymlink) {
2543   // Create a directory.
2544   FilePath dir_name_from =
2545       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
2546   ASSERT_TRUE(CreateDirectory(dir_name_from));
2547   ASSERT_TRUE(PathExists(dir_name_from));
2548 
2549   // Create a file under the directory.
2550   FilePath file_name_from =
2551       dir_name_from.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
2552   CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
2553   ASSERT_TRUE(PathExists(file_name_from));
2554 
2555   // Create a destination directory with a dangling symlink of the same name.
2556   FilePath dir_name_to =
2557       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_To_Subdir"));
2558   ASSERT_TRUE(CreateDirectory(dir_name_to));
2559   ASSERT_TRUE(PathExists(dir_name_to));
2560 
2561   FilePath symlink_target =
2562       dir_name_to.Append(FILE_PATH_LITERAL("Symlink_Target.txt"));
2563   CreateTextFile(symlink_target, L"asdf");
2564   ASSERT_TRUE(PathExists(symlink_target));
2565 
2566   FilePath symlink_name_to =
2567       dir_name_to.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
2568   ASSERT_TRUE(CreateSymbolicLink(symlink_target, symlink_name_to));
2569   ASSERT_TRUE(PathExists(symlink_name_to));
2570   ASSERT_TRUE(DeleteFile(symlink_target));
2571 
2572   // Check that copying fails and that no file was created for the symlink's
2573   // referent.
2574   EXPECT_FALSE(CopyDirectoryExcl(dir_name_from, dir_name_to, false));
2575   EXPECT_FALSE(PathExists(symlink_target));
2576 }
2577 
TEST_F(FileUtilTest,CopyDirectoryExclDirectoryOverDanglingSymlink)2578 TEST_F(FileUtilTest, CopyDirectoryExclDirectoryOverDanglingSymlink) {
2579   // Create a directory.
2580   FilePath dir_name_from =
2581       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
2582   ASSERT_TRUE(CreateDirectory(dir_name_from));
2583   ASSERT_TRUE(PathExists(dir_name_from));
2584 
2585   // Create a subdirectory.
2586   FilePath subdir_name_from = dir_name_from.Append(FILE_PATH_LITERAL("Subsub"));
2587   CreateDirectory(subdir_name_from);
2588   ASSERT_TRUE(PathExists(subdir_name_from));
2589 
2590   // Create a destination directory with a dangling symlink of the same name.
2591   FilePath dir_name_to =
2592       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_To_Subdir"));
2593   ASSERT_TRUE(CreateDirectory(dir_name_to));
2594   ASSERT_TRUE(PathExists(dir_name_to));
2595 
2596   FilePath symlink_target =
2597       dir_name_to.Append(FILE_PATH_LITERAL("Symlink_Target.txt"));
2598   CreateTextFile(symlink_target, L"asdf");
2599   ASSERT_TRUE(PathExists(symlink_target));
2600 
2601   FilePath symlink_name_to =
2602       dir_name_to.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
2603   ASSERT_TRUE(CreateSymbolicLink(symlink_target, symlink_name_to));
2604   ASSERT_TRUE(PathExists(symlink_name_to));
2605   ASSERT_TRUE(DeleteFile(symlink_target));
2606 
2607   // Check that copying fails and that no directory was created for the
2608   // symlink's referent.
2609   EXPECT_FALSE(CopyDirectoryExcl(dir_name_from, dir_name_to, false));
2610   EXPECT_FALSE(PathExists(symlink_target));
2611 }
2612 
TEST_F(FileUtilTest,CopyDirectoryExclFileOverFifo)2613 TEST_F(FileUtilTest, CopyDirectoryExclFileOverFifo) {
2614   // Create a directory.
2615   FilePath dir_name_from =
2616       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
2617   ASSERT_TRUE(CreateDirectory(dir_name_from));
2618   ASSERT_TRUE(PathExists(dir_name_from));
2619 
2620   // Create a file under the directory.
2621   FilePath file_name_from =
2622       dir_name_from.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
2623   CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
2624   ASSERT_TRUE(PathExists(file_name_from));
2625 
2626   // Create a destination directory with a fifo of the same name.
2627   FilePath dir_name_to =
2628       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_To_Subdir"));
2629   ASSERT_TRUE(CreateDirectory(dir_name_to));
2630   ASSERT_TRUE(PathExists(dir_name_to));
2631 
2632   FilePath fifo_name_to =
2633       dir_name_to.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
2634   ASSERT_EQ(0, mkfifo(fifo_name_to.value().c_str(), 0644));
2635   ASSERT_TRUE(PathExists(fifo_name_to));
2636 
2637   // Check that copying fails.
2638   EXPECT_FALSE(CopyDirectoryExcl(dir_name_from, dir_name_to, false));
2639 }
2640 #endif  // BUILDFLAG(IS_POSIX)
2641 
TEST_F(FileUtilTest,CopyFile)2642 TEST_F(FileUtilTest, CopyFile) {
2643   // Create a directory
2644   FilePath dir_name_from =
2645       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
2646   ASSERT_TRUE(CreateDirectory(dir_name_from));
2647   ASSERT_TRUE(DirectoryExists(dir_name_from));
2648 
2649   // Create a file under the directory
2650   FilePath file_name_from =
2651       dir_name_from.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
2652   const std::wstring file_contents(L"Gooooooooooooooooooooogle");
2653   CreateTextFile(file_name_from, file_contents);
2654   ASSERT_TRUE(PathExists(file_name_from));
2655 
2656   // Copy the file.
2657   FilePath dest_file = dir_name_from.Append(FILE_PATH_LITERAL("DestFile.txt"));
2658   ASSERT_TRUE(CopyFile(file_name_from, dest_file));
2659 
2660   // Try to copy the file to another location using '..' in the path.
2661   FilePath dest_file2(dir_name_from);
2662   dest_file2 = dest_file2.AppendASCII("..");
2663   dest_file2 = dest_file2.AppendASCII("DestFile.txt");
2664   ASSERT_FALSE(CopyFile(file_name_from, dest_file2));
2665 
2666   FilePath dest_file2_test(dir_name_from);
2667   dest_file2_test = dest_file2_test.DirName();
2668   dest_file2_test = dest_file2_test.AppendASCII("DestFile.txt");
2669 
2670   // Check expected copy results.
2671   EXPECT_TRUE(PathExists(file_name_from));
2672   EXPECT_TRUE(PathExists(dest_file));
2673   EXPECT_EQ(file_contents, ReadTextFile(dest_file));
2674   EXPECT_FALSE(PathExists(dest_file2_test));
2675   EXPECT_FALSE(PathExists(dest_file2));
2676 
2677   // Change |file_name_from| contents.
2678   const std::wstring new_file_contents(L"Moogle");
2679   CreateTextFile(file_name_from, new_file_contents);
2680   ASSERT_TRUE(PathExists(file_name_from));
2681   EXPECT_EQ(new_file_contents, ReadTextFile(file_name_from));
2682 
2683   // Overwrite |dest_file|.
2684   ASSERT_TRUE(CopyFile(file_name_from, dest_file));
2685   EXPECT_TRUE(PathExists(dest_file));
2686   EXPECT_EQ(new_file_contents, ReadTextFile(dest_file));
2687 
2688   // Create another directory.
2689   FilePath dest_dir = temp_dir_.GetPath().Append(FPL("dest_dir"));
2690   ASSERT_TRUE(CreateDirectory(dest_dir));
2691   EXPECT_TRUE(DirectoryExists(dest_dir));
2692   EXPECT_TRUE(IsDirectoryEmpty(dest_dir));
2693 
2694   // Make sure CopyFile() cannot overwrite a directory.
2695   ASSERT_FALSE(CopyFile(file_name_from, dest_dir));
2696   EXPECT_TRUE(DirectoryExists(dest_dir));
2697   EXPECT_TRUE(IsDirectoryEmpty(dest_dir));
2698 }
2699 
2700 // file_util winds up using autoreleased objects on the Mac, so this needs
2701 // to be a PlatformTest.
2702 typedef PlatformTest ReadOnlyFileUtilTest;
2703 
TEST_F(ReadOnlyFileUtilTest,ContentsEqual)2704 TEST_F(ReadOnlyFileUtilTest, ContentsEqual) {
2705   FilePath data_dir;
2706   ASSERT_TRUE(PathService::Get(DIR_TEST_DATA, &data_dir));
2707   data_dir = data_dir.AppendASCII("file_util");
2708   ASSERT_TRUE(PathExists(data_dir));
2709 
2710   FilePath original_file =
2711       data_dir.Append(FILE_PATH_LITERAL("original.txt"));
2712   FilePath same_file =
2713       data_dir.Append(FILE_PATH_LITERAL("same.txt"));
2714   FilePath same_length_file =
2715       data_dir.Append(FILE_PATH_LITERAL("same_length.txt"));
2716   FilePath different_file =
2717       data_dir.Append(FILE_PATH_LITERAL("different.txt"));
2718   FilePath different_first_file =
2719       data_dir.Append(FILE_PATH_LITERAL("different_first.txt"));
2720   FilePath different_last_file =
2721       data_dir.Append(FILE_PATH_LITERAL("different_last.txt"));
2722   FilePath empty1_file =
2723       data_dir.Append(FILE_PATH_LITERAL("empty1.txt"));
2724   FilePath empty2_file =
2725       data_dir.Append(FILE_PATH_LITERAL("empty2.txt"));
2726   FilePath shortened_file =
2727       data_dir.Append(FILE_PATH_LITERAL("shortened.txt"));
2728   FilePath binary_file =
2729       data_dir.Append(FILE_PATH_LITERAL("binary_file.bin"));
2730   FilePath binary_file_same =
2731       data_dir.Append(FILE_PATH_LITERAL("binary_file_same.bin"));
2732   FilePath binary_file_diff =
2733       data_dir.Append(FILE_PATH_LITERAL("binary_file_diff.bin"));
2734 
2735   EXPECT_TRUE(ContentsEqual(original_file, original_file));
2736   EXPECT_TRUE(ContentsEqual(original_file, same_file));
2737   EXPECT_FALSE(ContentsEqual(original_file, same_length_file));
2738   EXPECT_FALSE(ContentsEqual(original_file, different_file));
2739   EXPECT_FALSE(ContentsEqual(FilePath(FILE_PATH_LITERAL("bogusname")),
2740                              FilePath(FILE_PATH_LITERAL("bogusname"))));
2741   EXPECT_FALSE(ContentsEqual(original_file, different_first_file));
2742   EXPECT_FALSE(ContentsEqual(original_file, different_last_file));
2743   EXPECT_TRUE(ContentsEqual(empty1_file, empty2_file));
2744   EXPECT_FALSE(ContentsEqual(original_file, shortened_file));
2745   EXPECT_FALSE(ContentsEqual(shortened_file, original_file));
2746   EXPECT_TRUE(ContentsEqual(binary_file, binary_file_same));
2747   EXPECT_FALSE(ContentsEqual(binary_file, binary_file_diff));
2748 }
2749 
TEST_F(ReadOnlyFileUtilTest,TextContentsEqual)2750 TEST_F(ReadOnlyFileUtilTest, TextContentsEqual) {
2751   FilePath data_dir;
2752   ASSERT_TRUE(PathService::Get(DIR_TEST_DATA, &data_dir));
2753   data_dir = data_dir.AppendASCII("file_util");
2754   ASSERT_TRUE(PathExists(data_dir));
2755 
2756   FilePath original_file =
2757       data_dir.Append(FILE_PATH_LITERAL("original.txt"));
2758   FilePath same_file =
2759       data_dir.Append(FILE_PATH_LITERAL("same.txt"));
2760   FilePath crlf_file =
2761       data_dir.Append(FILE_PATH_LITERAL("crlf.txt"));
2762   FilePath shortened_file =
2763       data_dir.Append(FILE_PATH_LITERAL("shortened.txt"));
2764   FilePath different_file =
2765       data_dir.Append(FILE_PATH_LITERAL("different.txt"));
2766   FilePath different_first_file =
2767       data_dir.Append(FILE_PATH_LITERAL("different_first.txt"));
2768   FilePath different_last_file =
2769       data_dir.Append(FILE_PATH_LITERAL("different_last.txt"));
2770   FilePath first1_file =
2771       data_dir.Append(FILE_PATH_LITERAL("first1.txt"));
2772   FilePath first2_file =
2773       data_dir.Append(FILE_PATH_LITERAL("first2.txt"));
2774   FilePath empty1_file =
2775       data_dir.Append(FILE_PATH_LITERAL("empty1.txt"));
2776   FilePath empty2_file =
2777       data_dir.Append(FILE_PATH_LITERAL("empty2.txt"));
2778   FilePath blank_line_file =
2779       data_dir.Append(FILE_PATH_LITERAL("blank_line.txt"));
2780   FilePath blank_line_crlf_file =
2781       data_dir.Append(FILE_PATH_LITERAL("blank_line_crlf.txt"));
2782 
2783   EXPECT_TRUE(TextContentsEqual(original_file, same_file));
2784   EXPECT_TRUE(TextContentsEqual(original_file, crlf_file));
2785   EXPECT_FALSE(TextContentsEqual(original_file, shortened_file));
2786   EXPECT_FALSE(TextContentsEqual(original_file, different_file));
2787   EXPECT_FALSE(TextContentsEqual(original_file, different_first_file));
2788   EXPECT_FALSE(TextContentsEqual(original_file, different_last_file));
2789   EXPECT_FALSE(TextContentsEqual(first1_file, first2_file));
2790   EXPECT_TRUE(TextContentsEqual(empty1_file, empty2_file));
2791   EXPECT_FALSE(TextContentsEqual(original_file, empty1_file));
2792   EXPECT_TRUE(TextContentsEqual(blank_line_file, blank_line_crlf_file));
2793 }
2794 
2795 // We don't need equivalent functionality outside of Windows.
2796 #if BUILDFLAG(IS_WIN)
TEST_F(FileUtilTest,CopyAndDeleteDirectoryTest)2797 TEST_F(FileUtilTest, CopyAndDeleteDirectoryTest) {
2798   // Create a directory
2799   FilePath dir_name_from = temp_dir_.GetPath().Append(
2800       FILE_PATH_LITERAL("CopyAndDelete_From_Subdir"));
2801   CreateDirectory(dir_name_from);
2802   ASSERT_TRUE(PathExists(dir_name_from));
2803 
2804   // Create a file under the directory
2805   FilePath file_name_from =
2806       dir_name_from.Append(FILE_PATH_LITERAL("CopyAndDelete_Test_File.txt"));
2807   CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
2808   ASSERT_TRUE(PathExists(file_name_from));
2809 
2810   // Move the directory by using CopyAndDeleteDirectory
2811   FilePath dir_name_to =
2812       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("CopyAndDelete_To_Subdir"));
2813   FilePath file_name_to =
2814       dir_name_to.Append(FILE_PATH_LITERAL("CopyAndDelete_Test_File.txt"));
2815 
2816   ASSERT_FALSE(PathExists(dir_name_to));
2817 
2818   EXPECT_TRUE(internal::CopyAndDeleteDirectory(dir_name_from,
2819                                                      dir_name_to));
2820 
2821   // Check everything has been moved.
2822   EXPECT_FALSE(PathExists(dir_name_from));
2823   EXPECT_FALSE(PathExists(file_name_from));
2824   EXPECT_TRUE(PathExists(dir_name_to));
2825   EXPECT_TRUE(PathExists(file_name_to));
2826 }
2827 
TEST_F(FileUtilTest,GetTempDirTest)2828 TEST_F(FileUtilTest, GetTempDirTest) {
2829   static const TCHAR* kTmpKey = _T("TMP");
2830   static const TCHAR* kTmpValues[] = {
2831     _T(""), _T("C:"), _T("C:\\"), _T("C:\\tmp"), _T("C:\\tmp\\")
2832   };
2833   // Save the original $TMP.
2834   size_t original_tmp_size;
2835   TCHAR* original_tmp;
2836   ASSERT_EQ(0, ::_tdupenv_s(&original_tmp, &original_tmp_size, kTmpKey));
2837   // original_tmp may be NULL.
2838 
2839   for (unsigned int i = 0; i < std::size(kTmpValues); ++i) {
2840     FilePath path;
2841     ::_tputenv_s(kTmpKey, kTmpValues[i]);
2842     GetTempDir(&path);
2843     EXPECT_TRUE(path.IsAbsolute()) << "$TMP=" << kTmpValues[i] <<
2844         " result=" << path.value();
2845   }
2846 
2847   // Restore the original $TMP.
2848   if (original_tmp) {
2849     ::_tputenv_s(kTmpKey, original_tmp);
2850     free(original_tmp);
2851   } else {
2852     ::_tputenv_s(kTmpKey, _T(""));
2853   }
2854 }
2855 #endif  // BUILDFLAG(IS_WIN)
2856 
2857 // Test that files opened by OpenFile are not set up for inheritance into child
2858 // procs.
TEST_F(FileUtilTest,OpenFileNoInheritance)2859 TEST_F(FileUtilTest, OpenFileNoInheritance) {
2860   FilePath file_path(temp_dir_.GetPath().Append(FPL("a_file")));
2861 
2862 // Character set handling is leaking according to ASAN. http://crbug.com/883698
2863 #if defined(ADDRESS_SANITIZER)
2864   static constexpr const char* modes[] = {"wb", "r"};
2865 #else
2866   static constexpr const char* modes[] = {"wb", "r,ccs=UTF-8"};
2867 #endif
2868 
2869   for (const char* mode : modes) {
2870     SCOPED_TRACE(mode);
2871     ASSERT_NO_FATAL_FAILURE(CreateTextFile(file_path, L"Geepers"));
2872     FILE* file = OpenFile(file_path, mode);
2873     ASSERT_NE(nullptr, file);
2874     {
2875       ScopedClosureRunner file_closer(BindOnce(IgnoreResult(&CloseFile), file));
2876       bool is_inheritable = true;
2877       ASSERT_NO_FATAL_FAILURE(GetIsInheritable(file, &is_inheritable));
2878       EXPECT_FALSE(is_inheritable);
2879     }
2880     ASSERT_TRUE(DeleteFile(file_path));
2881   }
2882 }
2883 
TEST_F(FileUtilTest,CreateAndOpenTemporaryFileInDir)2884 TEST_F(FileUtilTest, CreateAndOpenTemporaryFileInDir) {
2885   // Create a temporary file.
2886   FilePath path;
2887   File file = CreateAndOpenTemporaryFileInDir(temp_dir_.GetPath(), &path);
2888   ASSERT_TRUE(file.IsValid());
2889   EXPECT_FALSE(path.empty());
2890 
2891   // Try to open another handle to it.
2892   File file2(path,
2893              File::FLAG_OPEN | File::FLAG_READ | File::FLAG_WIN_SHARE_DELETE);
2894 #if BUILDFLAG(IS_WIN)
2895   // The file cannot be opened again on account of the exclusive access.
2896   EXPECT_FALSE(file2.IsValid());
2897 #else
2898   // Exclusive access isn't a thing on non-Windows platforms.
2899   EXPECT_TRUE(file2.IsValid());
2900 #endif
2901 }
2902 
TEST_F(FileUtilTest,CreateTemporaryFileTest)2903 TEST_F(FileUtilTest, CreateTemporaryFileTest) {
2904   FilePath temp_files[3];
2905   for (auto& i : temp_files) {
2906     ASSERT_TRUE(CreateTemporaryFile(&i));
2907     EXPECT_TRUE(PathExists(i));
2908     EXPECT_FALSE(DirectoryExists(i));
2909   }
2910   for (int i = 0; i < 3; i++)
2911     EXPECT_FALSE(temp_files[i] == temp_files[(i+1)%3]);
2912   for (const auto& i : temp_files)
2913     EXPECT_TRUE(DeleteFile(i));
2914 }
2915 
TEST_F(FileUtilTest,CreateAndOpenTemporaryStreamTest)2916 TEST_F(FileUtilTest, CreateAndOpenTemporaryStreamTest) {
2917   FilePath names[3];
2918   ScopedFILE fps[3];
2919   int i;
2920 
2921   // Create; make sure they are open and exist.
2922   for (i = 0; i < 3; ++i) {
2923     fps[i] = CreateAndOpenTemporaryStream(&(names[i]));
2924     ASSERT_TRUE(fps[i]);
2925     EXPECT_TRUE(PathExists(names[i]));
2926   }
2927 
2928   // Make sure all names are unique.
2929   for (i = 0; i < 3; ++i) {
2930     EXPECT_FALSE(names[i] == names[(i+1)%3]);
2931   }
2932 
2933   // Close and delete.
2934   for (i = 0; i < 3; ++i) {
2935     fps[i].reset();
2936     EXPECT_TRUE(DeleteFile(names[i]));
2937   }
2938 }
2939 
TEST_F(FileUtilTest,GetUniquePathTest)2940 TEST_F(FileUtilTest, GetUniquePathTest) {
2941   // Create a unique temp directory and use it to generate a unique file path.
2942   base::ScopedTempDir temp_dir;
2943   EXPECT_TRUE(temp_dir.CreateUniqueTempDir());
2944   EXPECT_TRUE(temp_dir.IsValid());
2945   FilePath base_name(FILE_PATH_LITERAL("Unique_Base_Name.txt"));
2946   FilePath base_path = temp_dir.GetPath().Append(base_name);
2947   EXPECT_FALSE(PathExists(base_path));
2948 
2949   // GetUniquePath() should return unchanged path if file does not exist.
2950   EXPECT_EQ(base_path, GetUniquePath(base_path));
2951 
2952   // Create the file.
2953   {
2954     File file(base_path,
2955               File::FLAG_CREATE | File::FLAG_READ | File::FLAG_WRITE);
2956     EXPECT_TRUE(PathExists(base_path));
2957   }
2958 
2959   static const FilePath::CharType* const kExpectedNames[] = {
2960       FILE_PATH_LITERAL("Unique_Base_Name (1).txt"),
2961       FILE_PATH_LITERAL("Unique_Base_Name (2).txt"),
2962       FILE_PATH_LITERAL("Unique_Base_Name (3).txt"),
2963   };
2964 
2965   // Call GetUniquePath() three times against this existing file name.
2966   for (const FilePath::CharType* expected_name : kExpectedNames) {
2967     FilePath expected_path = temp_dir.GetPath().Append(expected_name);
2968     FilePath path = GetUniquePath(base_path);
2969     EXPECT_EQ(expected_path, path);
2970 
2971     // Verify that a file with this path indeed does not exist on the file
2972     // system.
2973     EXPECT_FALSE(PathExists(path));
2974 
2975     // Create the file so it exists for the next call to GetUniquePath() in the
2976     // loop.
2977     File file(path, File::FLAG_CREATE | File::FLAG_READ | File::FLAG_WRITE);
2978     EXPECT_TRUE(PathExists(path));
2979   }
2980 }
2981 
TEST_F(FileUtilTest,FileToFILE)2982 TEST_F(FileUtilTest, FileToFILE) {
2983   File file;
2984   FILE* stream = FileToFILE(std::move(file), "w");
2985   EXPECT_FALSE(stream);
2986 
2987   FilePath file_name = temp_dir_.GetPath().Append(FPL("The file.txt"));
2988   file = File(file_name, File::FLAG_CREATE | File::FLAG_WRITE);
2989   EXPECT_TRUE(file.IsValid());
2990 
2991   stream = FileToFILE(std::move(file), "w");
2992   EXPECT_TRUE(stream);
2993   EXPECT_FALSE(file.IsValid());
2994   EXPECT_TRUE(CloseFile(stream));
2995 }
2996 
TEST_F(FileUtilTest,FILEToFile)2997 TEST_F(FileUtilTest, FILEToFile) {
2998   ScopedFILE stream;
2999   EXPECT_FALSE(FILEToFile(stream.get()).IsValid());
3000 
3001   stream.reset(OpenFile(temp_dir_.GetPath().Append(FPL("hello.txt")), "wb+"));
3002   ASSERT_TRUE(stream);
3003   File file = FILEToFile(stream.get());
3004   EXPECT_TRUE(file.IsValid());
3005   ASSERT_EQ(fprintf(stream.get(), "there"), 5);
3006   ASSERT_EQ(fflush(stream.get()), 0);
3007   EXPECT_EQ(file.GetLength(), 5L);
3008 }
3009 
3010 #if BUILDFLAG(IS_WIN)
TEST_F(FileUtilTest,GetSecureSystemTemp)3011 TEST_F(FileUtilTest, GetSecureSystemTemp) {
3012   FilePath secure_system_temp;
3013   ASSERT_EQ(GetSecureSystemTemp(&secure_system_temp), !!::IsUserAnAdmin());
3014   if (!::IsUserAnAdmin()) {
3015     GTEST_SKIP() << "This test must be run by an admin user";
3016   }
3017 
3018   FilePath dir_windows;
3019   ASSERT_TRUE(PathService::Get(DIR_WINDOWS, &dir_windows));
3020   FilePath dir_program_files;
3021   ASSERT_TRUE(PathService::Get(DIR_PROGRAM_FILES, &dir_program_files));
3022 
3023   ASSERT_TRUE((dir_windows.AppendASCII("SystemTemp") == secure_system_temp) ||
3024               (dir_program_files == secure_system_temp));
3025 }
3026 #endif  // BUILDFLAG(IS_WIN)
3027 
TEST_F(FileUtilTest,CreateNewTempDirectoryTest)3028 TEST_F(FileUtilTest, CreateNewTempDirectoryTest) {
3029   FilePath temp_dir;
3030   ASSERT_TRUE(CreateNewTempDirectory(FilePath::StringType(), &temp_dir));
3031   EXPECT_TRUE(PathExists(temp_dir));
3032   EXPECT_TRUE(DeleteFile(temp_dir));
3033 }
3034 
3035 #if BUILDFLAG(IS_WIN)
TEST_F(FileUtilTest,TempDirectoryParentTest)3036 TEST_F(FileUtilTest, TempDirectoryParentTest) {
3037   if (!::IsUserAnAdmin()) {
3038     GTEST_SKIP() << "This test must be run by an admin user";
3039   }
3040   FilePath temp_dir;
3041   ASSERT_TRUE(CreateNewTempDirectory(FilePath::StringType(), &temp_dir));
3042   EXPECT_TRUE(PathExists(temp_dir));
3043 
3044   FilePath expected_parent_dir;
3045   if (!GetSecureSystemTemp(&expected_parent_dir)) {
3046     EXPECT_TRUE(PathService::Get(DIR_TEMP, &expected_parent_dir));
3047   }
3048   EXPECT_TRUE(expected_parent_dir.IsParent(temp_dir));
3049   EXPECT_TRUE(DeleteFile(temp_dir));
3050 }
3051 #endif  // BUILDFLAG(IS_WIN)
3052 
TEST_F(FileUtilTest,CreateNewTemporaryDirInDirTest)3053 TEST_F(FileUtilTest, CreateNewTemporaryDirInDirTest) {
3054   FilePath new_dir;
3055   ASSERT_TRUE(CreateTemporaryDirInDir(
3056       temp_dir_.GetPath(), FILE_PATH_LITERAL("CreateNewTemporaryDirInDirTest"),
3057       &new_dir));
3058   EXPECT_TRUE(PathExists(new_dir));
3059   EXPECT_TRUE(temp_dir_.GetPath().IsParent(new_dir));
3060   EXPECT_TRUE(DeleteFile(new_dir));
3061 }
3062 
3063 #if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
TEST_F(FileUtilTest,GetShmemTempDirTest)3064 TEST_F(FileUtilTest, GetShmemTempDirTest) {
3065   FilePath dir;
3066   EXPECT_TRUE(GetShmemTempDir(false, &dir));
3067   EXPECT_TRUE(DirectoryExists(dir));
3068 }
3069 
TEST_F(FileUtilTest,AllocateFileRegionTest_ZeroOffset)3070 TEST_F(FileUtilTest, AllocateFileRegionTest_ZeroOffset) {
3071   const int kTestFileLength = 9;
3072   char test_data[] = "test_data";
3073   FilePath file_path = temp_dir_.GetPath().Append(
3074       FILE_PATH_LITERAL("allocate_file_region_test_zero_offset"));
3075   WriteFile(file_path, test_data, kTestFileLength);
3076 
3077   File file(file_path, base::File::FLAG_OPEN | base::File::FLAG_READ |
3078                            base::File::FLAG_WRITE);
3079   ASSERT_TRUE(file.IsValid());
3080   ASSERT_EQ(file.GetLength(), kTestFileLength);
3081 
3082   const int kExtendedFileLength = 23;
3083   ASSERT_TRUE(AllocateFileRegion(&file, 0, kExtendedFileLength));
3084   EXPECT_EQ(file.GetLength(), kExtendedFileLength);
3085 
3086   char data_read[32];
3087   int bytes_read = file.Read(0, data_read, kExtendedFileLength);
3088   EXPECT_EQ(bytes_read, kExtendedFileLength);
3089   for (int i = 0; i < kTestFileLength; ++i)
3090     EXPECT_EQ(test_data[i], data_read[i]);
3091   for (int i = kTestFileLength; i < kExtendedFileLength; ++i)
3092     EXPECT_EQ(0, data_read[i]);
3093 }
3094 
TEST_F(FileUtilTest,AllocateFileRegionTest_NonZeroOffset)3095 TEST_F(FileUtilTest, AllocateFileRegionTest_NonZeroOffset) {
3096   const int kTestFileLength = 9;
3097   char test_data[] = "test_data";
3098   FilePath file_path = temp_dir_.GetPath().Append(
3099       FILE_PATH_LITERAL("allocate_file_region_test_non_zero_offset"));
3100   WriteFile(file_path, test_data, kTestFileLength);
3101 
3102   File file(file_path, base::File::FLAG_OPEN | base::File::FLAG_READ |
3103                            base::File::FLAG_WRITE);
3104   ASSERT_TRUE(file.IsValid());
3105   ASSERT_EQ(file.GetLength(), kTestFileLength);
3106 
3107   const int kExtensionOffset = 5;
3108   const int kExtensionSize = 10;
3109   ASSERT_TRUE(AllocateFileRegion(&file, kExtensionOffset, kExtensionSize));
3110   const int kExtendedFileLength = kExtensionOffset + kExtensionSize;
3111   EXPECT_EQ(file.GetLength(), kExtendedFileLength);
3112 
3113   char data_read[32];
3114   int bytes_read = file.Read(0, data_read, kExtendedFileLength);
3115   EXPECT_EQ(bytes_read, kExtendedFileLength);
3116   for (int i = 0; i < kTestFileLength; ++i)
3117     EXPECT_EQ(test_data[i], data_read[i]);
3118   for (int i = kTestFileLength; i < kExtendedFileLength; ++i)
3119     EXPECT_EQ(0, data_read[i]);
3120 }
3121 
TEST_F(FileUtilTest,AllocateFileRegionTest_DontTruncate)3122 TEST_F(FileUtilTest, AllocateFileRegionTest_DontTruncate) {
3123   const int kTestFileLength = 9;
3124   char test_data[] = "test_data";
3125   FilePath file_path = temp_dir_.GetPath().Append(
3126       FILE_PATH_LITERAL("allocate_file_region_test_dont_truncate"));
3127   WriteFile(file_path, test_data, kTestFileLength);
3128 
3129   File file(file_path, base::File::FLAG_OPEN | base::File::FLAG_READ |
3130                            base::File::FLAG_WRITE);
3131   ASSERT_TRUE(file.IsValid());
3132   ASSERT_EQ(file.GetLength(), kTestFileLength);
3133 
3134   const int kTruncatedFileLength = 4;
3135   ASSERT_TRUE(AllocateFileRegion(&file, 0, kTruncatedFileLength));
3136   EXPECT_EQ(file.GetLength(), kTestFileLength);
3137 }
3138 #endif
3139 
TEST_F(FileUtilTest,GetHomeDirTest)3140 TEST_F(FileUtilTest, GetHomeDirTest) {
3141 #if !BUILDFLAG(IS_ANDROID)  // Not implemented on Android.
3142   // We don't actually know what the home directory is supposed to be without
3143   // calling some OS functions which would just duplicate the implementation.
3144   // So here we just test that it returns something "reasonable".
3145   FilePath home = GetHomeDir();
3146   ASSERT_FALSE(home.empty());
3147   ASSERT_TRUE(home.IsAbsolute());
3148 #endif
3149 }
3150 
TEST_F(FileUtilTest,CreateDirectoryTest)3151 TEST_F(FileUtilTest, CreateDirectoryTest) {
3152   FilePath test_root =
3153       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("create_directory_test"));
3154 #if BUILDFLAG(IS_WIN)
3155   FilePath test_path =
3156       test_root.Append(FILE_PATH_LITERAL("dir\\tree\\likely\\doesnt\\exist\\"));
3157 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
3158   FilePath test_path =
3159       test_root.Append(FILE_PATH_LITERAL("dir/tree/likely/doesnt/exist/"));
3160 #endif
3161 
3162   EXPECT_FALSE(PathExists(test_path));
3163   EXPECT_TRUE(CreateDirectory(test_path));
3164   EXPECT_TRUE(PathExists(test_path));
3165   // CreateDirectory returns true if the DirectoryExists returns true.
3166   EXPECT_TRUE(CreateDirectory(test_path));
3167 
3168   // Doesn't work to create it on top of a non-dir
3169   test_path = test_path.Append(FILE_PATH_LITERAL("foobar.txt"));
3170   EXPECT_FALSE(PathExists(test_path));
3171   CreateTextFile(test_path, L"test file");
3172   EXPECT_TRUE(PathExists(test_path));
3173   EXPECT_FALSE(CreateDirectory(test_path));
3174 
3175   EXPECT_TRUE(DeletePathRecursively(test_root));
3176   EXPECT_FALSE(PathExists(test_root));
3177   EXPECT_FALSE(PathExists(test_path));
3178 
3179   // Verify assumptions made by the Windows implementation:
3180   // 1. The current directory always exists.
3181   // 2. The root directory always exists.
3182   ASSERT_TRUE(DirectoryExists(FilePath(FilePath::kCurrentDirectory)));
3183   FilePath top_level = test_root;
3184   while (top_level != top_level.DirName()) {
3185     top_level = top_level.DirName();
3186   }
3187   ASSERT_TRUE(DirectoryExists(top_level));
3188 
3189   // Given these assumptions hold, it should be safe to
3190   // test that "creating" these directories succeeds.
3191   EXPECT_TRUE(CreateDirectory(
3192       FilePath(FilePath::kCurrentDirectory)));
3193   EXPECT_TRUE(CreateDirectory(top_level));
3194 
3195 #if BUILDFLAG(IS_WIN)
3196   FilePath invalid_drive(FILE_PATH_LITERAL("o:\\"));
3197   FilePath invalid_path =
3198       invalid_drive.Append(FILE_PATH_LITERAL("some\\inaccessible\\dir"));
3199   if (!PathExists(invalid_drive)) {
3200     EXPECT_FALSE(CreateDirectory(invalid_path));
3201   }
3202 #endif
3203 }
3204 
TEST_F(FileUtilTest,DetectDirectoryTest)3205 TEST_F(FileUtilTest, DetectDirectoryTest) {
3206   // Check a directory
3207   FilePath test_root =
3208       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("detect_directory_test"));
3209   EXPECT_FALSE(PathExists(test_root));
3210   EXPECT_TRUE(CreateDirectory(test_root));
3211   EXPECT_TRUE(PathExists(test_root));
3212   EXPECT_TRUE(DirectoryExists(test_root));
3213   // Check a file
3214   FilePath test_path =
3215       test_root.Append(FILE_PATH_LITERAL("foobar.txt"));
3216   EXPECT_FALSE(PathExists(test_path));
3217   CreateTextFile(test_path, L"test file");
3218   EXPECT_TRUE(PathExists(test_path));
3219   EXPECT_FALSE(DirectoryExists(test_path));
3220   EXPECT_TRUE(DeleteFile(test_path));
3221 
3222   EXPECT_TRUE(DeletePathRecursively(test_root));
3223 }
3224 
TEST_F(FileUtilTest,FileEnumeratorTest)3225 TEST_F(FileUtilTest, FileEnumeratorTest) {
3226   // Test an empty directory.
3227   FileEnumerator f0(temp_dir_.GetPath(), true, FILES_AND_DIRECTORIES);
3228   EXPECT_EQ(FPL(""), f0.Next().value());
3229   EXPECT_EQ(FPL(""), f0.Next().value());
3230 
3231   // Test an empty directory, non-recursively, including "..".
3232   FileEnumerator f0_dotdot(
3233       temp_dir_.GetPath(), false,
3234       FILES_AND_DIRECTORIES | FileEnumerator::INCLUDE_DOT_DOT);
3235   EXPECT_EQ(temp_dir_.GetPath().Append(FPL("..")).value(),
3236             f0_dotdot.Next().value());
3237   EXPECT_EQ(FPL(""), f0_dotdot.Next().value());
3238 
3239   // create the directories
3240   FilePath dir1 = temp_dir_.GetPath().Append(FPL("dir1"));
3241   EXPECT_TRUE(CreateDirectory(dir1));
3242   FilePath dir2 = temp_dir_.GetPath().Append(FPL("dir2"));
3243   EXPECT_TRUE(CreateDirectory(dir2));
3244   FilePath dir2inner = dir2.Append(FPL("inner"));
3245   EXPECT_TRUE(CreateDirectory(dir2inner));
3246 
3247   // create the files
3248   FilePath dir2file = dir2.Append(FPL("dir2file.txt"));
3249   CreateTextFile(dir2file, std::wstring());
3250   FilePath dir2innerfile = dir2inner.Append(FPL("innerfile.txt"));
3251   CreateTextFile(dir2innerfile, std::wstring());
3252   FilePath file1 = temp_dir_.GetPath().Append(FPL("file1.txt"));
3253   CreateTextFile(file1, std::wstring());
3254   FilePath file2_rel = dir2.Append(FilePath::kParentDirectory)
3255       .Append(FPL("file2.txt"));
3256   CreateTextFile(file2_rel, std::wstring());
3257   FilePath file2_abs = temp_dir_.GetPath().Append(FPL("file2.txt"));
3258 
3259   // Only enumerate files.
3260   FileEnumerator f1(temp_dir_.GetPath(), true, FileEnumerator::FILES);
3261   FindResultCollector c1(&f1);
3262   EXPECT_TRUE(c1.HasFile(file1));
3263   EXPECT_TRUE(c1.HasFile(file2_abs));
3264   EXPECT_TRUE(c1.HasFile(dir2file));
3265   EXPECT_TRUE(c1.HasFile(dir2innerfile));
3266   EXPECT_EQ(4, c1.size());
3267 
3268   // Only enumerate directories.
3269   FileEnumerator f2(temp_dir_.GetPath(), true, FileEnumerator::DIRECTORIES);
3270   FindResultCollector c2(&f2);
3271   EXPECT_TRUE(c2.HasFile(dir1));
3272   EXPECT_TRUE(c2.HasFile(dir2));
3273   EXPECT_TRUE(c2.HasFile(dir2inner));
3274   EXPECT_EQ(3, c2.size());
3275 
3276   // Only enumerate directories non-recursively.
3277   FileEnumerator f2_non_recursive(temp_dir_.GetPath(), false,
3278                                   FileEnumerator::DIRECTORIES);
3279   FindResultCollector c2_non_recursive(&f2_non_recursive);
3280   EXPECT_TRUE(c2_non_recursive.HasFile(dir1));
3281   EXPECT_TRUE(c2_non_recursive.HasFile(dir2));
3282   EXPECT_EQ(2, c2_non_recursive.size());
3283 
3284   // Only enumerate directories, non-recursively, including "..".
3285   FileEnumerator f2_dotdot(
3286       temp_dir_.GetPath(), false,
3287       FileEnumerator::DIRECTORIES | FileEnumerator::INCLUDE_DOT_DOT);
3288   FindResultCollector c2_dotdot(&f2_dotdot);
3289   EXPECT_TRUE(c2_dotdot.HasFile(dir1));
3290   EXPECT_TRUE(c2_dotdot.HasFile(dir2));
3291   EXPECT_TRUE(c2_dotdot.HasFile(temp_dir_.GetPath().Append(FPL(".."))));
3292   EXPECT_EQ(3, c2_dotdot.size());
3293 
3294   // Enumerate files and directories.
3295   FileEnumerator f3(temp_dir_.GetPath(), true, FILES_AND_DIRECTORIES);
3296   FindResultCollector c3(&f3);
3297   EXPECT_TRUE(c3.HasFile(dir1));
3298   EXPECT_TRUE(c3.HasFile(dir2));
3299   EXPECT_TRUE(c3.HasFile(file1));
3300   EXPECT_TRUE(c3.HasFile(file2_abs));
3301   EXPECT_TRUE(c3.HasFile(dir2file));
3302   EXPECT_TRUE(c3.HasFile(dir2inner));
3303   EXPECT_TRUE(c3.HasFile(dir2innerfile));
3304   EXPECT_EQ(7, c3.size());
3305 
3306   // Non-recursive operation.
3307   FileEnumerator f4(temp_dir_.GetPath(), false, FILES_AND_DIRECTORIES);
3308   FindResultCollector c4(&f4);
3309   EXPECT_TRUE(c4.HasFile(dir2));
3310   EXPECT_TRUE(c4.HasFile(dir2));
3311   EXPECT_TRUE(c4.HasFile(file1));
3312   EXPECT_TRUE(c4.HasFile(file2_abs));
3313   EXPECT_EQ(4, c4.size());
3314 
3315   // Enumerate with a pattern.
3316   FileEnumerator f5(temp_dir_.GetPath(), true, FILES_AND_DIRECTORIES,
3317                     FPL("dir*"));
3318   FindResultCollector c5(&f5);
3319   EXPECT_TRUE(c5.HasFile(dir1));
3320   EXPECT_TRUE(c5.HasFile(dir2));
3321   EXPECT_TRUE(c5.HasFile(dir2file));
3322   EXPECT_TRUE(c5.HasFile(dir2inner));
3323   EXPECT_TRUE(c5.HasFile(dir2innerfile));
3324   EXPECT_EQ(5, c5.size());
3325 
3326 #if BUILDFLAG(IS_WIN)
3327   {
3328     // Make dir1 point to dir2.
3329     ReparsePoint reparse_point(dir1, dir2);
3330     EXPECT_TRUE(reparse_point.IsValid());
3331 
3332     // There can be a delay for the enumeration code to see the change on
3333     // the file system so skip this test for XP.
3334     // Enumerate the reparse point.
3335     FileEnumerator f6(dir1, true, FILES_AND_DIRECTORIES);
3336     FindResultCollector c6(&f6);
3337     FilePath inner2 = dir1.Append(FPL("inner"));
3338     EXPECT_TRUE(c6.HasFile(inner2));
3339     EXPECT_TRUE(c6.HasFile(inner2.Append(FPL("innerfile.txt"))));
3340     EXPECT_TRUE(c6.HasFile(dir1.Append(FPL("dir2file.txt"))));
3341     EXPECT_EQ(3, c6.size());
3342 
3343     // No changes for non recursive operation.
3344     FileEnumerator f7(temp_dir_.GetPath(), false, FILES_AND_DIRECTORIES);
3345     FindResultCollector c7(&f7);
3346     EXPECT_TRUE(c7.HasFile(dir2));
3347     EXPECT_TRUE(c7.HasFile(dir2));
3348     EXPECT_TRUE(c7.HasFile(file1));
3349     EXPECT_TRUE(c7.HasFile(file2_abs));
3350     EXPECT_EQ(4, c7.size());
3351 
3352     // Should not enumerate inside dir1 when using recursion.
3353     FileEnumerator f8(temp_dir_.GetPath(), true, FILES_AND_DIRECTORIES);
3354     FindResultCollector c8(&f8);
3355     EXPECT_TRUE(c8.HasFile(dir1));
3356     EXPECT_TRUE(c8.HasFile(dir2));
3357     EXPECT_TRUE(c8.HasFile(file1));
3358     EXPECT_TRUE(c8.HasFile(file2_abs));
3359     EXPECT_TRUE(c8.HasFile(dir2file));
3360     EXPECT_TRUE(c8.HasFile(dir2inner));
3361     EXPECT_TRUE(c8.HasFile(dir2innerfile));
3362     EXPECT_EQ(7, c8.size());
3363   }
3364 #endif
3365 
3366   // Make sure the destructor closes the find handle while in the middle of a
3367   // query to allow TearDown to delete the directory.
3368   FileEnumerator f9(temp_dir_.GetPath(), true, FILES_AND_DIRECTORIES);
3369   EXPECT_FALSE(f9.Next().value().empty());  // Should have found something
3370                                             // (we don't care what).
3371 }
3372 
TEST_F(FileUtilTest,AppendToFile)3373 TEST_F(FileUtilTest, AppendToFile) {
3374   FilePath data_dir =
3375       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("FilePathTest"));
3376 
3377   // Create a fresh, empty copy of this directory.
3378   if (PathExists(data_dir)) {
3379     ASSERT_TRUE(DeletePathRecursively(data_dir));
3380   }
3381   ASSERT_TRUE(CreateDirectory(data_dir));
3382 
3383   // Create a fresh, empty copy of this directory.
3384   if (PathExists(data_dir)) {
3385     ASSERT_TRUE(DeletePathRecursively(data_dir));
3386   }
3387   ASSERT_TRUE(CreateDirectory(data_dir));
3388   FilePath foobar(data_dir.Append(FILE_PATH_LITERAL("foobar.txt")));
3389 
3390   std::string data("hello");
3391   EXPECT_FALSE(AppendToFile(foobar, data));
3392   EXPECT_TRUE(WriteFile(foobar, data));
3393   EXPECT_TRUE(AppendToFile(foobar, data));
3394 
3395   const std::wstring read_content = ReadTextFile(foobar);
3396   EXPECT_EQ(L"hellohello", read_content);
3397 }
3398 
TEST_F(FileUtilTest,ReadFile)3399 TEST_F(FileUtilTest, ReadFile) {
3400   // Create a test file to be read.
3401   const std::string kTestData("The quick brown fox jumps over the lazy dog.");
3402   FilePath file_path =
3403       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("ReadFileTest"));
3404 
3405   ASSERT_TRUE(WriteFile(file_path, kTestData));
3406 
3407   // Make buffers with various size.
3408   std::vector<char> small_buffer(kTestData.size() / 2);
3409   std::vector<char> exact_buffer(kTestData.size());
3410   std::vector<char> large_buffer(kTestData.size() * 2);
3411 
3412   // Read the file with smaller buffer.
3413   int bytes_read_small = ReadFile(
3414       file_path, &small_buffer[0], static_cast<int>(small_buffer.size()));
3415   EXPECT_EQ(static_cast<int>(small_buffer.size()), bytes_read_small);
3416   EXPECT_EQ(
3417       std::string(kTestData.begin(), kTestData.begin() + small_buffer.size()),
3418       std::string(small_buffer.begin(), small_buffer.end()));
3419 
3420   // Read the file with buffer which have exactly same size.
3421   int bytes_read_exact = ReadFile(
3422       file_path, &exact_buffer[0], static_cast<int>(exact_buffer.size()));
3423   EXPECT_EQ(static_cast<int>(kTestData.size()), bytes_read_exact);
3424   EXPECT_EQ(kTestData, std::string(exact_buffer.begin(), exact_buffer.end()));
3425 
3426   // Read the file with larger buffer.
3427   int bytes_read_large = ReadFile(
3428       file_path, &large_buffer[0], static_cast<int>(large_buffer.size()));
3429   EXPECT_EQ(static_cast<int>(kTestData.size()), bytes_read_large);
3430   EXPECT_EQ(kTestData, std::string(large_buffer.begin(),
3431                                    large_buffer.begin() + kTestData.size()));
3432 
3433   // Make sure the return value is -1 if the file doesn't exist.
3434   FilePath file_path_not_exist =
3435       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("ReadFileNotExistTest"));
3436   EXPECT_EQ(-1,
3437             ReadFile(file_path_not_exist,
3438                      &exact_buffer[0],
3439                      static_cast<int>(exact_buffer.size())));
3440 }
3441 
TEST_F(FileUtilTest,ReadFileToBytes)3442 TEST_F(FileUtilTest, ReadFileToBytes) {
3443   const std::vector<uint8_t> kTestData = {'0', '1', '2', '3'};
3444 
3445   FilePath file_path =
3446       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("ReadFileToStringTest"));
3447   FilePath file_path_dangerous =
3448       temp_dir_.GetPath()
3449           .Append(FILE_PATH_LITERAL(".."))
3450           .Append(temp_dir_.GetPath().BaseName())
3451           .Append(FILE_PATH_LITERAL("ReadFileToStringTest"));
3452 
3453   // Create test file.
3454   ASSERT_TRUE(WriteFile(file_path, kTestData));
3455 
3456   absl::optional<std::vector<uint8_t>> bytes = ReadFileToBytes(file_path);
3457   ASSERT_TRUE(bytes.has_value());
3458   EXPECT_EQ(kTestData, bytes);
3459 
3460   // Write empty file.
3461   ASSERT_TRUE(WriteFile(file_path, ""));
3462   bytes = ReadFileToBytes(file_path);
3463   ASSERT_TRUE(bytes.has_value());
3464   EXPECT_TRUE(bytes->empty());
3465 
3466   ASSERT_FALSE(ReadFileToBytes(file_path_dangerous));
3467 }
3468 
TEST_F(FileUtilTest,ReadFileToString)3469 TEST_F(FileUtilTest, ReadFileToString) {
3470   const char kTestData[] = "0123";
3471   std::string data;
3472 
3473   FilePath file_path =
3474       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("ReadFileToStringTest"));
3475   FilePath file_path_dangerous =
3476       temp_dir_.GetPath()
3477           .Append(FILE_PATH_LITERAL(".."))
3478           .Append(temp_dir_.GetPath().BaseName())
3479           .Append(FILE_PATH_LITERAL("ReadFileToStringTest"));
3480 
3481   // Create test file.
3482   ASSERT_TRUE(WriteFile(file_path, kTestData));
3483 
3484   EXPECT_TRUE(ReadFileToString(file_path, &data));
3485   EXPECT_EQ(kTestData, data);
3486 
3487   data = "temp";
3488   EXPECT_FALSE(ReadFileToStringWithMaxSize(file_path, &data, 0));
3489   EXPECT_EQ(0u, data.length());
3490 
3491   data = "temp";
3492   EXPECT_FALSE(ReadFileToStringWithMaxSize(file_path, &data, 2));
3493   EXPECT_EQ("01", data);
3494 
3495   data = "temp";
3496   EXPECT_FALSE(ReadFileToStringWithMaxSize(file_path, &data, 3));
3497   EXPECT_EQ("012", data);
3498 
3499   data = "temp";
3500   EXPECT_TRUE(ReadFileToStringWithMaxSize(file_path, &data, 4));
3501   EXPECT_EQ("0123", data);
3502 
3503   data = "temp";
3504   EXPECT_TRUE(ReadFileToStringWithMaxSize(file_path, &data, 6));
3505   EXPECT_EQ("0123", data);
3506 
3507   EXPECT_TRUE(ReadFileToStringWithMaxSize(file_path, nullptr, 6));
3508 
3509   EXPECT_TRUE(ReadFileToString(file_path, nullptr));
3510 
3511   data = "temp";
3512   EXPECT_FALSE(ReadFileToString(file_path_dangerous, &data));
3513   EXPECT_EQ(0u, data.length());
3514 
3515   // Delete test file.
3516   EXPECT_TRUE(DeleteFile(file_path));
3517 
3518   data = "temp";
3519   EXPECT_FALSE(ReadFileToString(file_path, &data));
3520   EXPECT_EQ(0u, data.length());
3521 
3522   data = "temp";
3523   EXPECT_FALSE(ReadFileToStringWithMaxSize(file_path, &data, 6));
3524   EXPECT_EQ(0u, data.length());
3525 }
3526 
3527 #if !BUILDFLAG(IS_WIN)
TEST_F(FileUtilTest,ReadFileToStringWithUnknownFileSize)3528 TEST_F(FileUtilTest, ReadFileToStringWithUnknownFileSize) {
3529 #if BUILDFLAG(IS_FUCHSIA)
3530   test::TaskEnvironment task_environment;
3531   auto dev_zero = ScopedDevZero::Get();
3532   ASSERT_TRUE(dev_zero);
3533 #endif
3534   FilePath file_path("/dev/zero");
3535   std::string data = "temp";
3536 
3537   EXPECT_FALSE(ReadFileToStringWithMaxSize(file_path, &data, 0));
3538   EXPECT_EQ(0u, data.length());
3539 
3540   data = "temp";
3541   EXPECT_FALSE(ReadFileToStringWithMaxSize(file_path, &data, 2));
3542   EXPECT_EQ(std::string(2, '\0'), data);
3543 
3544   EXPECT_FALSE(ReadFileToStringWithMaxSize(file_path, nullptr, 6));
3545 
3546   // Read more than buffer size.
3547   data = "temp";
3548   EXPECT_FALSE(ReadFileToStringWithMaxSize(file_path, &data, kLargeFileSize));
3549   EXPECT_EQ(kLargeFileSize, data.length());
3550   EXPECT_EQ(std::string(kLargeFileSize, '\0'), data);
3551 
3552   EXPECT_FALSE(ReadFileToStringWithMaxSize(file_path, nullptr, kLargeFileSize));
3553 }
3554 #endif  // !BUILDFLAG(IS_WIN)
3555 
3556 #if !BUILDFLAG(IS_WIN) && !BUILDFLAG(IS_NACL) && !BUILDFLAG(IS_FUCHSIA) && \
3557     !BUILDFLAG(IS_IOS)
3558 #define ChildMain WriteToPipeChildMain
3559 #define ChildMainString "WriteToPipeChildMain"
3560 
MULTIPROCESS_TEST_MAIN(ChildMain)3561 MULTIPROCESS_TEST_MAIN(ChildMain) {
3562   const char kTestData[] = "0123";
3563   CommandLine* command_line = CommandLine::ForCurrentProcess();
3564   const FilePath pipe_path = command_line->GetSwitchValuePath("pipe-path");
3565 
3566   int fd = open(pipe_path.value().c_str(), O_WRONLY);
3567   CHECK_NE(-1, fd);
3568   size_t written = 0;
3569   while (written < strlen(kTestData)) {
3570     ssize_t res = write(fd, kTestData + written, strlen(kTestData) - written);
3571     if (res == -1)
3572       break;
3573     written += res;
3574   }
3575   CHECK_EQ(strlen(kTestData), written);
3576   CHECK_EQ(0, close(fd));
3577   return 0;
3578 }
3579 
3580 #define MoreThanBufferSizeChildMain WriteToPipeMoreThanBufferSizeChildMain
3581 #define MoreThanBufferSizeChildMainString \
3582   "WriteToPipeMoreThanBufferSizeChildMain"
3583 
MULTIPROCESS_TEST_MAIN(MoreThanBufferSizeChildMain)3584 MULTIPROCESS_TEST_MAIN(MoreThanBufferSizeChildMain) {
3585   std::string data(kLargeFileSize, 'c');
3586   CommandLine* command_line = CommandLine::ForCurrentProcess();
3587   const FilePath pipe_path = command_line->GetSwitchValuePath("pipe-path");
3588 
3589   int fd = open(pipe_path.value().c_str(), O_WRONLY);
3590   CHECK_NE(-1, fd);
3591 
3592   size_t written = 0;
3593   while (written < data.size()) {
3594     ssize_t res = write(fd, data.c_str() + written, data.size() - written);
3595     if (res == -1) {
3596       // We are unable to write because reading process has already read
3597       // requested number of bytes and closed pipe.
3598       break;
3599     }
3600     written += res;
3601   }
3602   CHECK_EQ(0, close(fd));
3603   return 0;
3604 }
3605 
TEST_F(FileUtilTest,ReadFileToStringWithNamedPipe)3606 TEST_F(FileUtilTest, ReadFileToStringWithNamedPipe) {
3607   FilePath pipe_path =
3608       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("test_pipe"));
3609   ASSERT_EQ(0, mkfifo(pipe_path.value().c_str(), 0600));
3610 
3611   CommandLine child_command_line(GetMultiProcessTestChildBaseCommandLine());
3612   child_command_line.AppendSwitchPath("pipe-path", pipe_path);
3613 
3614   {
3615     Process child_process = SpawnMultiProcessTestChild(
3616         ChildMainString, child_command_line, LaunchOptions());
3617     ASSERT_TRUE(child_process.IsValid());
3618 
3619     std::string data = "temp";
3620     EXPECT_FALSE(ReadFileToStringWithMaxSize(pipe_path, &data, 2));
3621     EXPECT_EQ("01", data);
3622 
3623     int rv = -1;
3624     ASSERT_TRUE(WaitForMultiprocessTestChildExit(
3625         child_process, TestTimeouts::action_timeout(), &rv));
3626     ASSERT_EQ(0, rv);
3627   }
3628   {
3629     Process child_process = SpawnMultiProcessTestChild(
3630         ChildMainString, child_command_line, LaunchOptions());
3631     ASSERT_TRUE(child_process.IsValid());
3632 
3633     std::string data = "temp";
3634     EXPECT_TRUE(ReadFileToStringWithMaxSize(pipe_path, &data, 6));
3635     EXPECT_EQ("0123", data);
3636 
3637     int rv = -1;
3638     ASSERT_TRUE(WaitForMultiprocessTestChildExit(
3639         child_process, TestTimeouts::action_timeout(), &rv));
3640     ASSERT_EQ(0, rv);
3641   }
3642   {
3643     Process child_process = SpawnMultiProcessTestChild(
3644         MoreThanBufferSizeChildMainString, child_command_line, LaunchOptions());
3645     ASSERT_TRUE(child_process.IsValid());
3646 
3647     std::string data = "temp";
3648     EXPECT_FALSE(ReadFileToStringWithMaxSize(pipe_path, &data, 6));
3649     EXPECT_EQ("cccccc", data);
3650 
3651     int rv = -1;
3652     ASSERT_TRUE(WaitForMultiprocessTestChildExit(
3653         child_process, TestTimeouts::action_timeout(), &rv));
3654     ASSERT_EQ(0, rv);
3655   }
3656   {
3657     Process child_process = SpawnMultiProcessTestChild(
3658         MoreThanBufferSizeChildMainString, child_command_line, LaunchOptions());
3659     ASSERT_TRUE(child_process.IsValid());
3660 
3661     std::string data = "temp";
3662     EXPECT_FALSE(
3663         ReadFileToStringWithMaxSize(pipe_path, &data, kLargeFileSize - 1));
3664     EXPECT_EQ(std::string(kLargeFileSize - 1, 'c'), data);
3665 
3666     int rv = -1;
3667     ASSERT_TRUE(WaitForMultiprocessTestChildExit(
3668         child_process, TestTimeouts::action_timeout(), &rv));
3669     ASSERT_EQ(0, rv);
3670   }
3671   {
3672     Process child_process = SpawnMultiProcessTestChild(
3673         MoreThanBufferSizeChildMainString, child_command_line, LaunchOptions());
3674     ASSERT_TRUE(child_process.IsValid());
3675 
3676     std::string data = "temp";
3677     EXPECT_TRUE(ReadFileToStringWithMaxSize(pipe_path, &data, kLargeFileSize));
3678     EXPECT_EQ(std::string(kLargeFileSize, 'c'), data);
3679 
3680     int rv = -1;
3681     ASSERT_TRUE(WaitForMultiprocessTestChildExit(
3682         child_process, TestTimeouts::action_timeout(), &rv));
3683     ASSERT_EQ(0, rv);
3684   }
3685   {
3686     Process child_process = SpawnMultiProcessTestChild(
3687         MoreThanBufferSizeChildMainString, child_command_line, LaunchOptions());
3688     ASSERT_TRUE(child_process.IsValid());
3689 
3690     std::string data = "temp";
3691     EXPECT_TRUE(
3692         ReadFileToStringWithMaxSize(pipe_path, &data, kLargeFileSize * 5));
3693     EXPECT_EQ(std::string(kLargeFileSize, 'c'), data);
3694 
3695     int rv = -1;
3696     ASSERT_TRUE(WaitForMultiprocessTestChildExit(
3697         child_process, TestTimeouts::action_timeout(), &rv));
3698     ASSERT_EQ(0, rv);
3699   }
3700 
3701   ASSERT_EQ(0, unlink(pipe_path.value().c_str()));
3702 }
3703 #endif  // !BUILDFLAG(IS_WIN) && !BUILDFLAG(IS_NACL) && !BUILDFLAG(IS_FUCHSIA)
3704         // && !BUILDFLAG(IS_IOS)
3705 
3706 #if BUILDFLAG(IS_WIN)
3707 #define ChildMain WriteToPipeChildMain
3708 #define ChildMainString "WriteToPipeChildMain"
3709 
MULTIPROCESS_TEST_MAIN(ChildMain)3710 MULTIPROCESS_TEST_MAIN(ChildMain) {
3711   const char kTestData[] = "0123";
3712   CommandLine* command_line = CommandLine::ForCurrentProcess();
3713   const FilePath pipe_path = command_line->GetSwitchValuePath("pipe-path");
3714   std::string switch_string = command_line->GetSwitchValueASCII("sync_event");
3715   EXPECT_FALSE(switch_string.empty());
3716   unsigned int switch_uint = 0;
3717   EXPECT_TRUE(StringToUint(switch_string, &switch_uint));
3718   win::ScopedHandle sync_event(win::Uint32ToHandle(switch_uint));
3719 
3720   HANDLE ph = CreateNamedPipe(pipe_path.value().c_str(), PIPE_ACCESS_OUTBOUND,
3721                               PIPE_WAIT, 1, 0, 0, 0, NULL);
3722   EXPECT_NE(ph, INVALID_HANDLE_VALUE);
3723   EXPECT_TRUE(SetEvent(sync_event.get()));
3724   if (!::ConnectNamedPipe(ph, /*lpOverlapped=*/nullptr)) {
3725     // ERROR_PIPE_CONNECTED means that the other side has already connected.
3726     auto error = ::GetLastError();
3727     EXPECT_EQ(error, DWORD{ERROR_PIPE_CONNECTED});
3728   }
3729 
3730   DWORD written;
3731   EXPECT_TRUE(::WriteFile(ph, kTestData, strlen(kTestData), &written, NULL));
3732   EXPECT_EQ(strlen(kTestData), written);
3733   CloseHandle(ph);
3734   return 0;
3735 }
3736 
3737 #define MoreThanBufferSizeChildMain WriteToPipeMoreThanBufferSizeChildMain
3738 #define MoreThanBufferSizeChildMainString \
3739   "WriteToPipeMoreThanBufferSizeChildMain"
3740 
MULTIPROCESS_TEST_MAIN(MoreThanBufferSizeChildMain)3741 MULTIPROCESS_TEST_MAIN(MoreThanBufferSizeChildMain) {
3742   std::string data(kLargeFileSize, 'c');
3743   CommandLine* command_line = CommandLine::ForCurrentProcess();
3744   const FilePath pipe_path = command_line->GetSwitchValuePath("pipe-path");
3745   std::string switch_string = command_line->GetSwitchValueASCII("sync_event");
3746   EXPECT_FALSE(switch_string.empty());
3747   unsigned int switch_uint = 0;
3748   EXPECT_TRUE(StringToUint(switch_string, &switch_uint));
3749   win::ScopedHandle sync_event(win::Uint32ToHandle(switch_uint));
3750 
3751   HANDLE ph = CreateNamedPipe(pipe_path.value().c_str(), PIPE_ACCESS_OUTBOUND,
3752                               PIPE_WAIT, 1, data.size(), data.size(), 0, NULL);
3753   EXPECT_NE(ph, INVALID_HANDLE_VALUE);
3754   EXPECT_TRUE(SetEvent(sync_event.get()));
3755   if (!::ConnectNamedPipe(ph, /*lpOverlapped=*/nullptr)) {
3756     // ERROR_PIPE_CONNECTED means that the other side has already connected.
3757     auto error = ::GetLastError();
3758     EXPECT_EQ(error, DWORD{ERROR_PIPE_CONNECTED});
3759   }
3760 
3761   DWORD written;
3762   EXPECT_TRUE(::WriteFile(ph, data.c_str(), data.size(), &written, NULL));
3763   EXPECT_EQ(data.size(), written);
3764   CloseHandle(ph);
3765   return 0;
3766 }
3767 
TEST_F(FileUtilTest,ReadFileToStringWithNamedPipe)3768 TEST_F(FileUtilTest, ReadFileToStringWithNamedPipe) {
3769   FilePath pipe_path(FILE_PATH_LITERAL("\\\\.\\pipe\\test_pipe"));
3770   win::ScopedHandle sync_event(CreateEvent(0, false, false, nullptr));
3771 
3772   CommandLine child_command_line(GetMultiProcessTestChildBaseCommandLine());
3773   child_command_line.AppendSwitchPath("pipe-path", pipe_path);
3774   child_command_line.AppendSwitchASCII(
3775       "sync_event", NumberToString(win::HandleToUint32(sync_event.get())));
3776 
3777   LaunchOptions options;
3778   options.handles_to_inherit.push_back(sync_event.get());
3779 
3780   {
3781     Process child_process = SpawnMultiProcessTestChild(
3782         ChildMainString, child_command_line, options);
3783     ASSERT_TRUE(child_process.IsValid());
3784     // Wait for pipe creation in child process.
3785     EXPECT_EQ(WAIT_OBJECT_0, WaitForSingleObject(sync_event.get(), INFINITE));
3786 
3787     std::string data = "temp";
3788     EXPECT_FALSE(ReadFileToStringWithMaxSize(pipe_path, &data, 2));
3789     EXPECT_EQ("01", data);
3790 
3791     int rv = -1;
3792     ASSERT_TRUE(WaitForMultiprocessTestChildExit(
3793         child_process, TestTimeouts::action_timeout(), &rv));
3794     ASSERT_EQ(0, rv);
3795   }
3796   {
3797     Process child_process = SpawnMultiProcessTestChild(
3798         ChildMainString, child_command_line, options);
3799     ASSERT_TRUE(child_process.IsValid());
3800     // Wait for pipe creation in child process.
3801     EXPECT_EQ(WAIT_OBJECT_0, WaitForSingleObject(sync_event.get(), INFINITE));
3802 
3803     std::string data = "temp";
3804     EXPECT_TRUE(ReadFileToStringWithMaxSize(pipe_path, &data, 6));
3805     EXPECT_EQ("0123", data);
3806 
3807     int rv = -1;
3808     ASSERT_TRUE(WaitForMultiprocessTestChildExit(
3809         child_process, TestTimeouts::action_timeout(), &rv));
3810     ASSERT_EQ(0, rv);
3811   }
3812   {
3813     Process child_process = SpawnMultiProcessTestChild(
3814         MoreThanBufferSizeChildMainString, child_command_line, options);
3815     ASSERT_TRUE(child_process.IsValid());
3816     // Wait for pipe creation in child process.
3817     EXPECT_EQ(WAIT_OBJECT_0, WaitForSingleObject(sync_event.get(), INFINITE));
3818 
3819     std::string data = "temp";
3820     EXPECT_FALSE(ReadFileToStringWithMaxSize(pipe_path, &data, 6));
3821     EXPECT_EQ("cccccc", data);
3822 
3823     int rv = -1;
3824     ASSERT_TRUE(WaitForMultiprocessTestChildExit(
3825         child_process, TestTimeouts::action_timeout(), &rv));
3826     ASSERT_EQ(0, rv);
3827   }
3828   {
3829     Process child_process = SpawnMultiProcessTestChild(
3830         MoreThanBufferSizeChildMainString, child_command_line, options);
3831     ASSERT_TRUE(child_process.IsValid());
3832     // Wait for pipe creation in child process.
3833     EXPECT_EQ(WAIT_OBJECT_0, WaitForSingleObject(sync_event.get(), INFINITE));
3834 
3835     std::string data = "temp";
3836     EXPECT_FALSE(
3837         ReadFileToStringWithMaxSize(pipe_path, &data, kLargeFileSize - 1));
3838     EXPECT_EQ(std::string(kLargeFileSize - 1, 'c'), data);
3839 
3840     int rv = -1;
3841     ASSERT_TRUE(WaitForMultiprocessTestChildExit(
3842         child_process, TestTimeouts::action_timeout(), &rv));
3843     ASSERT_EQ(0, rv);
3844   }
3845   {
3846     Process child_process = SpawnMultiProcessTestChild(
3847         MoreThanBufferSizeChildMainString, child_command_line, options);
3848     ASSERT_TRUE(child_process.IsValid());
3849     // Wait for pipe creation in child process.
3850     EXPECT_EQ(WAIT_OBJECT_0, WaitForSingleObject(sync_event.get(), INFINITE));
3851 
3852     std::string data = "temp";
3853     EXPECT_TRUE(ReadFileToStringWithMaxSize(pipe_path, &data, kLargeFileSize));
3854     EXPECT_EQ(std::string(kLargeFileSize, 'c'), data);
3855 
3856     int rv = -1;
3857     ASSERT_TRUE(WaitForMultiprocessTestChildExit(
3858         child_process, TestTimeouts::action_timeout(), &rv));
3859     ASSERT_EQ(0, rv);
3860   }
3861   {
3862     Process child_process = SpawnMultiProcessTestChild(
3863         MoreThanBufferSizeChildMainString, child_command_line, options);
3864     ASSERT_TRUE(child_process.IsValid());
3865     // Wait for pipe creation in child process.
3866     EXPECT_EQ(WAIT_OBJECT_0, WaitForSingleObject(sync_event.get(), INFINITE));
3867 
3868     std::string data = "temp";
3869     EXPECT_TRUE(
3870         ReadFileToStringWithMaxSize(pipe_path, &data, kLargeFileSize * 5));
3871     EXPECT_EQ(std::string(kLargeFileSize, 'c'), data);
3872 
3873     int rv = -1;
3874     ASSERT_TRUE(WaitForMultiprocessTestChildExit(
3875         child_process, TestTimeouts::action_timeout(), &rv));
3876     ASSERT_EQ(0, rv);
3877   }
3878 }
3879 #endif  // BUILDFLAG(IS_WIN)
3880 
3881 #if BUILDFLAG(IS_POSIX) && !BUILDFLAG(IS_APPLE)
TEST_F(FileUtilTest,ReadFileToStringWithProcFileSystem)3882 TEST_F(FileUtilTest, ReadFileToStringWithProcFileSystem) {
3883   FilePath file_path("/proc/cpuinfo");
3884   std::string data = "temp";
3885 
3886   EXPECT_FALSE(ReadFileToStringWithMaxSize(file_path, &data, 0));
3887   EXPECT_EQ(0u, data.length());
3888 
3889   data = "temp";
3890   EXPECT_FALSE(ReadFileToStringWithMaxSize(file_path, &data, 2));
3891   EXPECT_TRUE(EqualsCaseInsensitiveASCII("pr", data));
3892 
3893   data = "temp";
3894   EXPECT_FALSE(ReadFileToStringWithMaxSize(file_path, &data, 4));
3895   EXPECT_TRUE(EqualsCaseInsensitiveASCII("proc", data));
3896 
3897   EXPECT_FALSE(ReadFileToStringWithMaxSize(file_path, nullptr, 4));
3898 }
3899 #endif  // BUILDFLAG(IS_POSIX) && !BUILDFLAG(IS_APPLE)
3900 
TEST_F(FileUtilTest,ReadFileToStringWithLargeFile)3901 TEST_F(FileUtilTest, ReadFileToStringWithLargeFile) {
3902   std::string data(kLargeFileSize, 'c');
3903 
3904   FilePath file_path =
3905       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("ReadFileToStringTest"));
3906 
3907   // Create test file.
3908   ASSERT_TRUE(WriteFile(file_path, data));
3909 
3910   std::string actual_data = "temp";
3911   EXPECT_TRUE(ReadFileToString(file_path, &actual_data));
3912   EXPECT_EQ(data, actual_data);
3913 
3914   actual_data = "temp";
3915   EXPECT_FALSE(ReadFileToStringWithMaxSize(file_path, &actual_data, 0));
3916   EXPECT_EQ(0u, actual_data.length());
3917 
3918   // Read more than buffer size.
3919   actual_data = "temp";
3920   EXPECT_FALSE(
3921       ReadFileToStringWithMaxSize(file_path, &actual_data, kLargeFileSize - 1));
3922   EXPECT_EQ(std::string(kLargeFileSize - 1, 'c'), actual_data);
3923 }
3924 
TEST_F(FileUtilTest,ReadStreamToString)3925 TEST_F(FileUtilTest, ReadStreamToString) {
3926   ScopedFILE stream(
3927       OpenFile(temp_dir_.GetPath().Append(FPL("hello.txt")), "wb+"));
3928   ASSERT_TRUE(stream);
3929   File file = FILEToFile(stream.get());
3930   ASSERT_TRUE(file.IsValid());
3931   ASSERT_EQ(fprintf(stream.get(), "there"), 5);
3932   ASSERT_EQ(fflush(stream.get()), 0);
3933 
3934   std::string contents;
3935   EXPECT_TRUE(ReadStreamToString(stream.get(), &contents));
3936   EXPECT_EQ(contents, std::string("there"));
3937 }
3938 
3939 #if BUILDFLAG(IS_POSIX)
TEST_F(FileUtilTest,ReadStreamToString_ZeroLengthFile)3940 TEST_F(FileUtilTest, ReadStreamToString_ZeroLengthFile) {
3941   Thread write_thread("write thread");
3942   ASSERT_TRUE(write_thread.Start());
3943 
3944   const size_t kSizes[] = {0, 1, 4095, 4096, 4097, 65535, 65536, 65537};
3945 
3946   for (size_t size : kSizes) {
3947     ScopedFD read_fd, write_fd;
3948     // Pipes have a length of zero when stat()'d.
3949     ASSERT_TRUE(CreatePipe(&read_fd, &write_fd, false /* non_blocking */));
3950 
3951     std::string random_data;
3952     if (size > 0) {
3953       random_data = RandBytesAsString(size);
3954     }
3955     EXPECT_EQ(size, random_data.size());
3956     write_thread.task_runner()->PostTask(
3957         FROM_HERE,
3958         BindLambdaForTesting([random_data, write_fd = std::move(write_fd)]() {
3959           ASSERT_TRUE(WriteFileDescriptor(write_fd.get(), random_data));
3960         }));
3961 
3962     ScopedFILE read_file(fdopen(read_fd.release(), "r"));
3963     ASSERT_TRUE(read_file);
3964 
3965     std::string contents;
3966     EXPECT_TRUE(ReadStreamToString(read_file.get(), &contents));
3967     EXPECT_EQ(contents, random_data);
3968   }
3969 }
3970 #endif
3971 
TEST_F(FileUtilTest,ReadStreamToStringWithMaxSize)3972 TEST_F(FileUtilTest, ReadStreamToStringWithMaxSize) {
3973   ScopedFILE stream(
3974       OpenFile(temp_dir_.GetPath().Append(FPL("hello.txt")), "wb+"));
3975   ASSERT_TRUE(stream);
3976   File file = FILEToFile(stream.get());
3977   ASSERT_TRUE(file.IsValid());
3978   ASSERT_EQ(fprintf(stream.get(), "there"), 5);
3979   ASSERT_EQ(fflush(stream.get()), 0);
3980 
3981   std::string contents;
3982   EXPECT_FALSE(ReadStreamToStringWithMaxSize(stream.get(), 2, &contents));
3983 }
3984 
TEST_F(FileUtilTest,ReadStreamToStringNullStream)3985 TEST_F(FileUtilTest, ReadStreamToStringNullStream) {
3986   std::string contents;
3987   EXPECT_FALSE(ReadStreamToString(nullptr, &contents));
3988 }
3989 
TEST_F(FileUtilTest,TouchFile)3990 TEST_F(FileUtilTest, TouchFile) {
3991   FilePath data_dir =
3992       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("FilePathTest"));
3993 
3994   // Create a fresh, empty copy of this directory.
3995   if (PathExists(data_dir)) {
3996     ASSERT_TRUE(DeletePathRecursively(data_dir));
3997   }
3998   ASSERT_TRUE(CreateDirectory(data_dir));
3999 
4000   FilePath foobar(data_dir.Append(FILE_PATH_LITERAL("foobar.txt")));
4001   std::string data("hello");
4002   ASSERT_TRUE(WriteFile(foobar, data));
4003 
4004   Time access_time;
4005   // This timestamp is divisible by one day (in local timezone),
4006   // to make it work on FAT too.
4007   ASSERT_TRUE(Time::FromString("Wed, 16 Nov 1994, 00:00:00",
4008                                &access_time));
4009 
4010   Time modification_time;
4011   // Note that this timestamp is divisible by two (seconds) - FAT stores
4012   // modification times with 2s resolution.
4013   ASSERT_TRUE(Time::FromString("Tue, 15 Nov 1994, 12:45:26 GMT",
4014               &modification_time));
4015 
4016   ASSERT_TRUE(TouchFile(foobar, access_time, modification_time));
4017   File::Info file_info;
4018   ASSERT_TRUE(GetFileInfo(foobar, &file_info));
4019 #if !BUILDFLAG(IS_FUCHSIA)
4020   // Access time is not supported on Fuchsia, see https://crbug.com/735233.
4021   EXPECT_EQ(access_time.ToInternalValue(),
4022             file_info.last_accessed.ToInternalValue());
4023 #endif
4024   EXPECT_EQ(modification_time.ToInternalValue(),
4025             file_info.last_modified.ToInternalValue());
4026 }
4027 
TEST_F(FileUtilTest,WriteFileSpanVariant)4028 TEST_F(FileUtilTest, WriteFileSpanVariant) {
4029   FilePath empty_file =
4030       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("empty_file"));
4031   ASSERT_FALSE(PathExists(empty_file));
4032   EXPECT_TRUE(WriteFile(empty_file, base::span<const uint8_t>()));
4033   EXPECT_TRUE(PathExists(empty_file));
4034 
4035   std::string data = "not empty";
4036   EXPECT_TRUE(ReadFileToString(empty_file, &data));
4037   EXPECT_TRUE(data.empty());
4038 
4039   FilePath write_span_file =
4040       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("write_span_file"));
4041   ASSERT_FALSE(PathExists(write_span_file));
4042   static constexpr uint8_t kInput[] = {'h', 'e', 'l', 'l', 'o'};
4043   EXPECT_TRUE(WriteFile(write_span_file, kInput));
4044   EXPECT_TRUE(PathExists(write_span_file));
4045 
4046   data.clear();
4047   EXPECT_TRUE(ReadFileToString(write_span_file, &data));
4048   EXPECT_EQ("hello", data);
4049 }
4050 
TEST_F(FileUtilTest,WriteFileStringVariant)4051 TEST_F(FileUtilTest, WriteFileStringVariant) {
4052   FilePath empty_file =
4053       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("empty_file"));
4054   ASSERT_FALSE(PathExists(empty_file));
4055   EXPECT_TRUE(WriteFile(empty_file, ""));
4056   EXPECT_TRUE(PathExists(empty_file));
4057 
4058   std::string data = "not empty";
4059   EXPECT_TRUE(ReadFileToString(empty_file, &data));
4060   EXPECT_TRUE(data.empty());
4061 
4062   FilePath write_span_file =
4063       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("write_string_file"));
4064   ASSERT_FALSE(PathExists(write_span_file));
4065   EXPECT_TRUE(WriteFile(write_span_file, "world"));
4066   EXPECT_TRUE(PathExists(write_span_file));
4067 
4068   data.clear();
4069   EXPECT_TRUE(ReadFileToString(write_span_file, &data));
4070   EXPECT_EQ("world", data);
4071 }
4072 
TEST_F(FileUtilTest,IsDirectoryEmpty)4073 TEST_F(FileUtilTest, IsDirectoryEmpty) {
4074   FilePath empty_dir =
4075       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("EmptyDir"));
4076 
4077   ASSERT_FALSE(PathExists(empty_dir));
4078 
4079   ASSERT_TRUE(CreateDirectory(empty_dir));
4080 
4081   EXPECT_TRUE(IsDirectoryEmpty(empty_dir));
4082 
4083   FilePath foo(empty_dir.Append(FILE_PATH_LITERAL("foo.txt")));
4084   std::string bar("baz");
4085   ASSERT_TRUE(WriteFile(foo, bar));
4086 
4087   EXPECT_FALSE(IsDirectoryEmpty(empty_dir));
4088 }
4089 
4090 #if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
4091 
TEST_F(FileUtilTest,SetNonBlocking)4092 TEST_F(FileUtilTest, SetNonBlocking) {
4093   const int kBogusFd = 99999;
4094   EXPECT_FALSE(SetNonBlocking(kBogusFd));
4095 
4096   FilePath path;
4097   ASSERT_TRUE(PathService::Get(DIR_TEST_DATA, &path));
4098   path = path.Append(FPL("file_util")).Append(FPL("original.txt"));
4099   ScopedFD fd(open(path.value().c_str(), O_RDONLY));
4100   ASSERT_GE(fd.get(), 0);
4101   EXPECT_TRUE(SetNonBlocking(fd.get()));
4102 }
4103 
TEST_F(FileUtilTest,SetCloseOnExec)4104 TEST_F(FileUtilTest, SetCloseOnExec) {
4105   const int kBogusFd = 99999;
4106   EXPECT_FALSE(SetCloseOnExec(kBogusFd));
4107 
4108   FilePath path;
4109   ASSERT_TRUE(PathService::Get(DIR_TEST_DATA, &path));
4110   path = path.Append(FPL("file_util")).Append(FPL("original.txt"));
4111   ScopedFD fd(open(path.value().c_str(), O_RDONLY));
4112   ASSERT_GE(fd.get(), 0);
4113   EXPECT_TRUE(SetCloseOnExec(fd.get()));
4114 }
4115 
4116 #endif
4117 
4118 #if BUILDFLAG(IS_MAC)
4119 
4120 // Testing VerifyPathControlledByAdmin() is hard, because there is no
4121 // way a test can make a file owned by root, or change file paths
4122 // at the root of the file system.  VerifyPathControlledByAdmin()
4123 // is implemented as a call to VerifyPathControlledByUser, which gives
4124 // us the ability to test with paths under the test's temp directory,
4125 // using a user id we control.
4126 // Pull tests of VerifyPathControlledByUserTest() into a separate test class
4127 // with a common SetUp() method.
4128 class VerifyPathControlledByUserTest : public FileUtilTest {
4129  protected:
SetUp()4130   void SetUp() override {
4131     FileUtilTest::SetUp();
4132 
4133     // Create a basic structure used by each test.
4134     // base_dir_
4135     //  |-> sub_dir_
4136     //       |-> text_file_
4137 
4138     base_dir_ = temp_dir_.GetPath().AppendASCII("base_dir");
4139     ASSERT_TRUE(CreateDirectory(base_dir_));
4140 
4141     sub_dir_ = base_dir_.AppendASCII("sub_dir");
4142     ASSERT_TRUE(CreateDirectory(sub_dir_));
4143 
4144     text_file_ = sub_dir_.AppendASCII("file.txt");
4145     CreateTextFile(text_file_, L"This text file has some text in it.");
4146 
4147     // Get the user and group files are created with from |base_dir_|.
4148     stat_wrapper_t stat_buf;
4149     ASSERT_EQ(0, File::Stat(base_dir_.value().c_str(), &stat_buf));
4150     uid_ = stat_buf.st_uid;
4151     ok_gids_.insert(stat_buf.st_gid);
4152     bad_gids_.insert(stat_buf.st_gid + 1);
4153 
4154     ASSERT_EQ(uid_, getuid());  // This process should be the owner.
4155 
4156     // To ensure that umask settings do not cause the initial state
4157     // of permissions to be different from what we expect, explicitly
4158     // set permissions on the directories we create.
4159     // Make all files and directories non-world-writable.
4160 
4161     // Users and group can read, write, traverse
4162     int enabled_permissions =
4163         FILE_PERMISSION_USER_MASK | FILE_PERMISSION_GROUP_MASK;
4164     // Other users can't read, write, traverse
4165     int disabled_permissions = FILE_PERMISSION_OTHERS_MASK;
4166 
4167     ASSERT_NO_FATAL_FAILURE(
4168         ChangePosixFilePermissions(
4169             base_dir_, enabled_permissions, disabled_permissions));
4170     ASSERT_NO_FATAL_FAILURE(
4171         ChangePosixFilePermissions(
4172             sub_dir_, enabled_permissions, disabled_permissions));
4173   }
4174 
4175   FilePath base_dir_;
4176   FilePath sub_dir_;
4177   FilePath text_file_;
4178   uid_t uid_;
4179 
4180   std::set<gid_t> ok_gids_;
4181   std::set<gid_t> bad_gids_;
4182 };
4183 
TEST_F(VerifyPathControlledByUserTest,BadPaths)4184 TEST_F(VerifyPathControlledByUserTest, BadPaths) {
4185   // File does not exist.
4186   FilePath does_not_exist = base_dir_.AppendASCII("does")
4187                                      .AppendASCII("not")
4188                                      .AppendASCII("exist");
4189   EXPECT_FALSE(
4190       VerifyPathControlledByUser(base_dir_, does_not_exist, uid_, ok_gids_));
4191 
4192   // |base| not a subpath of |path|.
4193   EXPECT_FALSE(VerifyPathControlledByUser(sub_dir_, base_dir_, uid_, ok_gids_));
4194 
4195   // An empty base path will fail to be a prefix for any path.
4196   FilePath empty;
4197   EXPECT_FALSE(VerifyPathControlledByUser(empty, base_dir_, uid_, ok_gids_));
4198 
4199   // Finding that a bad call fails proves nothing unless a good call succeeds.
4200   EXPECT_TRUE(VerifyPathControlledByUser(base_dir_, sub_dir_, uid_, ok_gids_));
4201 }
4202 
TEST_F(VerifyPathControlledByUserTest,Symlinks)4203 TEST_F(VerifyPathControlledByUserTest, Symlinks) {
4204   // Symlinks in the path should cause failure.
4205 
4206   // Symlink to the file at the end of the path.
4207   FilePath file_link =  base_dir_.AppendASCII("file_link");
4208   ASSERT_TRUE(CreateSymbolicLink(text_file_, file_link))
4209       << "Failed to create symlink.";
4210 
4211   EXPECT_FALSE(
4212       VerifyPathControlledByUser(base_dir_, file_link, uid_, ok_gids_));
4213   EXPECT_FALSE(
4214       VerifyPathControlledByUser(file_link, file_link, uid_, ok_gids_));
4215 
4216   // Symlink from one directory to another within the path.
4217   FilePath link_to_sub_dir =  base_dir_.AppendASCII("link_to_sub_dir");
4218   ASSERT_TRUE(CreateSymbolicLink(sub_dir_, link_to_sub_dir))
4219     << "Failed to create symlink.";
4220 
4221   FilePath file_path_with_link = link_to_sub_dir.AppendASCII("file.txt");
4222   ASSERT_TRUE(PathExists(file_path_with_link));
4223 
4224   EXPECT_FALSE(VerifyPathControlledByUser(base_dir_, file_path_with_link, uid_,
4225                                           ok_gids_));
4226 
4227   EXPECT_FALSE(VerifyPathControlledByUser(link_to_sub_dir, file_path_with_link,
4228                                           uid_, ok_gids_));
4229 
4230   // Symlinks in parents of base path are allowed.
4231   EXPECT_TRUE(VerifyPathControlledByUser(file_path_with_link,
4232                                          file_path_with_link, uid_, ok_gids_));
4233 }
4234 
TEST_F(VerifyPathControlledByUserTest,OwnershipChecks)4235 TEST_F(VerifyPathControlledByUserTest, OwnershipChecks) {
4236   // Get a uid that is not the uid of files we create.
4237   uid_t bad_uid = uid_ + 1;
4238 
4239   // Make all files and directories non-world-writable.
4240   ASSERT_NO_FATAL_FAILURE(
4241       ChangePosixFilePermissions(base_dir_, 0u, S_IWOTH));
4242   ASSERT_NO_FATAL_FAILURE(
4243       ChangePosixFilePermissions(sub_dir_, 0u, S_IWOTH));
4244   ASSERT_NO_FATAL_FAILURE(
4245       ChangePosixFilePermissions(text_file_, 0u, S_IWOTH));
4246 
4247   // We control these paths.
4248   EXPECT_TRUE(VerifyPathControlledByUser(base_dir_, sub_dir_, uid_, ok_gids_));
4249   EXPECT_TRUE(
4250       VerifyPathControlledByUser(base_dir_, text_file_, uid_, ok_gids_));
4251   EXPECT_TRUE(VerifyPathControlledByUser(sub_dir_, text_file_, uid_, ok_gids_));
4252 
4253   // Another user does not control these paths.
4254   EXPECT_FALSE(
4255       VerifyPathControlledByUser(base_dir_, sub_dir_, bad_uid, ok_gids_));
4256   EXPECT_FALSE(
4257       VerifyPathControlledByUser(base_dir_, text_file_, bad_uid, ok_gids_));
4258   EXPECT_FALSE(
4259       VerifyPathControlledByUser(sub_dir_, text_file_, bad_uid, ok_gids_));
4260 
4261   // Another group does not control the paths.
4262   EXPECT_FALSE(
4263       VerifyPathControlledByUser(base_dir_, sub_dir_, uid_, bad_gids_));
4264   EXPECT_FALSE(
4265       VerifyPathControlledByUser(base_dir_, text_file_, uid_, bad_gids_));
4266   EXPECT_FALSE(
4267       VerifyPathControlledByUser(sub_dir_, text_file_, uid_, bad_gids_));
4268 }
4269 
TEST_F(VerifyPathControlledByUserTest,GroupWriteTest)4270 TEST_F(VerifyPathControlledByUserTest, GroupWriteTest) {
4271   // Make all files and directories writable only by their owner.
4272   ASSERT_NO_FATAL_FAILURE(
4273       ChangePosixFilePermissions(base_dir_, 0u, S_IWOTH|S_IWGRP));
4274   ASSERT_NO_FATAL_FAILURE(
4275       ChangePosixFilePermissions(sub_dir_, 0u, S_IWOTH|S_IWGRP));
4276   ASSERT_NO_FATAL_FAILURE(
4277       ChangePosixFilePermissions(text_file_, 0u, S_IWOTH|S_IWGRP));
4278 
4279   // Any group is okay because the path is not group-writable.
4280   EXPECT_TRUE(VerifyPathControlledByUser(base_dir_, sub_dir_, uid_, ok_gids_));
4281   EXPECT_TRUE(
4282       VerifyPathControlledByUser(base_dir_, text_file_, uid_, ok_gids_));
4283   EXPECT_TRUE(VerifyPathControlledByUser(sub_dir_, text_file_, uid_, ok_gids_));
4284 
4285   EXPECT_TRUE(VerifyPathControlledByUser(base_dir_, sub_dir_, uid_, bad_gids_));
4286   EXPECT_TRUE(
4287       VerifyPathControlledByUser(base_dir_, text_file_, uid_, bad_gids_));
4288   EXPECT_TRUE(
4289       VerifyPathControlledByUser(sub_dir_, text_file_, uid_, bad_gids_));
4290 
4291   // No group is okay, because we don't check the group
4292   // if no group can write.
4293   std::set<gid_t> no_gids;  // Empty set of gids.
4294   EXPECT_TRUE(VerifyPathControlledByUser(base_dir_, sub_dir_, uid_, no_gids));
4295   EXPECT_TRUE(VerifyPathControlledByUser(base_dir_, text_file_, uid_, no_gids));
4296   EXPECT_TRUE(VerifyPathControlledByUser(sub_dir_, text_file_, uid_, no_gids));
4297 
4298   // Make all files and directories writable by their group.
4299   ASSERT_NO_FATAL_FAILURE(ChangePosixFilePermissions(base_dir_, S_IWGRP, 0u));
4300   ASSERT_NO_FATAL_FAILURE(ChangePosixFilePermissions(sub_dir_, S_IWGRP, 0u));
4301   ASSERT_NO_FATAL_FAILURE(ChangePosixFilePermissions(text_file_, S_IWGRP, 0u));
4302 
4303   // Now |ok_gids_| works, but |bad_gids_| fails.
4304   EXPECT_TRUE(VerifyPathControlledByUser(base_dir_, sub_dir_, uid_, ok_gids_));
4305   EXPECT_TRUE(
4306       VerifyPathControlledByUser(base_dir_, text_file_, uid_, ok_gids_));
4307   EXPECT_TRUE(VerifyPathControlledByUser(sub_dir_, text_file_, uid_, ok_gids_));
4308 
4309   EXPECT_FALSE(
4310       VerifyPathControlledByUser(base_dir_, sub_dir_, uid_, bad_gids_));
4311   EXPECT_FALSE(
4312       VerifyPathControlledByUser(base_dir_, text_file_, uid_, bad_gids_));
4313   EXPECT_FALSE(
4314       VerifyPathControlledByUser(sub_dir_, text_file_, uid_, bad_gids_));
4315 
4316   // Because any group in the group set is allowed,
4317   // the union of good and bad gids passes.
4318 
4319   std::set<gid_t> multiple_gids;
4320   std::set_union(
4321       ok_gids_.begin(), ok_gids_.end(),
4322       bad_gids_.begin(), bad_gids_.end(),
4323       std::inserter(multiple_gids, multiple_gids.begin()));
4324 
4325   EXPECT_TRUE(
4326       VerifyPathControlledByUser(base_dir_, sub_dir_, uid_, multiple_gids));
4327   EXPECT_TRUE(
4328       VerifyPathControlledByUser(base_dir_, text_file_, uid_, multiple_gids));
4329   EXPECT_TRUE(
4330       VerifyPathControlledByUser(sub_dir_, text_file_, uid_, multiple_gids));
4331 }
4332 
TEST_F(VerifyPathControlledByUserTest,WriteBitChecks)4333 TEST_F(VerifyPathControlledByUserTest, WriteBitChecks) {
4334   // Make all files and directories non-world-writable.
4335   ASSERT_NO_FATAL_FAILURE(
4336       ChangePosixFilePermissions(base_dir_, 0u, S_IWOTH));
4337   ASSERT_NO_FATAL_FAILURE(
4338       ChangePosixFilePermissions(sub_dir_, 0u, S_IWOTH));
4339   ASSERT_NO_FATAL_FAILURE(
4340       ChangePosixFilePermissions(text_file_, 0u, S_IWOTH));
4341 
4342   // Initialy, we control all parts of the path.
4343   EXPECT_TRUE(VerifyPathControlledByUser(base_dir_, sub_dir_, uid_, ok_gids_));
4344   EXPECT_TRUE(
4345       VerifyPathControlledByUser(base_dir_, text_file_, uid_, ok_gids_));
4346   EXPECT_TRUE(VerifyPathControlledByUser(sub_dir_, text_file_, uid_, ok_gids_));
4347 
4348   // Make base_dir_ world-writable.
4349   ASSERT_NO_FATAL_FAILURE(
4350       ChangePosixFilePermissions(base_dir_, S_IWOTH, 0u));
4351   EXPECT_FALSE(VerifyPathControlledByUser(base_dir_, sub_dir_, uid_, ok_gids_));
4352   EXPECT_FALSE(
4353       VerifyPathControlledByUser(base_dir_, text_file_, uid_, ok_gids_));
4354   EXPECT_TRUE(VerifyPathControlledByUser(sub_dir_, text_file_, uid_, ok_gids_));
4355 
4356   // Make sub_dir_ world writable.
4357   ASSERT_NO_FATAL_FAILURE(
4358       ChangePosixFilePermissions(sub_dir_, S_IWOTH, 0u));
4359   EXPECT_FALSE(VerifyPathControlledByUser(base_dir_, sub_dir_, uid_, ok_gids_));
4360   EXPECT_FALSE(
4361       VerifyPathControlledByUser(base_dir_, text_file_, uid_, ok_gids_));
4362   EXPECT_FALSE(
4363       VerifyPathControlledByUser(sub_dir_, text_file_, uid_, ok_gids_));
4364 
4365   // Make text_file_ world writable.
4366   ASSERT_NO_FATAL_FAILURE(
4367       ChangePosixFilePermissions(text_file_, S_IWOTH, 0u));
4368   EXPECT_FALSE(VerifyPathControlledByUser(base_dir_, sub_dir_, uid_, ok_gids_));
4369   EXPECT_FALSE(
4370       VerifyPathControlledByUser(base_dir_, text_file_, uid_, ok_gids_));
4371   EXPECT_FALSE(
4372       VerifyPathControlledByUser(sub_dir_, text_file_, uid_, ok_gids_));
4373 
4374   // Make sub_dir_ non-world writable.
4375   ASSERT_NO_FATAL_FAILURE(
4376       ChangePosixFilePermissions(sub_dir_, 0u, S_IWOTH));
4377   EXPECT_FALSE(VerifyPathControlledByUser(base_dir_, sub_dir_, uid_, ok_gids_));
4378   EXPECT_FALSE(
4379       VerifyPathControlledByUser(base_dir_, text_file_, uid_, ok_gids_));
4380   EXPECT_FALSE(
4381       VerifyPathControlledByUser(sub_dir_, text_file_, uid_, ok_gids_));
4382 
4383   // Make base_dir_ non-world-writable.
4384   ASSERT_NO_FATAL_FAILURE(
4385       ChangePosixFilePermissions(base_dir_, 0u, S_IWOTH));
4386   EXPECT_TRUE(VerifyPathControlledByUser(base_dir_, sub_dir_, uid_, ok_gids_));
4387   EXPECT_FALSE(
4388       VerifyPathControlledByUser(base_dir_, text_file_, uid_, ok_gids_));
4389   EXPECT_FALSE(
4390       VerifyPathControlledByUser(sub_dir_, text_file_, uid_, ok_gids_));
4391 
4392   // Back to the initial state: Nothing is writable, so every path
4393   // should pass.
4394   ASSERT_NO_FATAL_FAILURE(
4395       ChangePosixFilePermissions(text_file_, 0u, S_IWOTH));
4396   EXPECT_TRUE(VerifyPathControlledByUser(base_dir_, sub_dir_, uid_, ok_gids_));
4397   EXPECT_TRUE(
4398       VerifyPathControlledByUser(base_dir_, text_file_, uid_, ok_gids_));
4399   EXPECT_TRUE(VerifyPathControlledByUser(sub_dir_, text_file_, uid_, ok_gids_));
4400 }
4401 
4402 #endif  // BUILDFLAG(IS_MAC)
4403 
4404 // Flaky test: crbug/1054637
4405 #if BUILDFLAG(IS_ANDROID)
TEST_F(FileUtilTest,DISABLED_ValidContentUriTest)4406 TEST_F(FileUtilTest, DISABLED_ValidContentUriTest) {
4407   // Get the test image path.
4408   FilePath data_dir;
4409   ASSERT_TRUE(PathService::Get(DIR_TEST_DATA, &data_dir));
4410   data_dir = data_dir.AppendASCII("file_util");
4411   ASSERT_TRUE(PathExists(data_dir));
4412   FilePath image_file = data_dir.Append(FILE_PATH_LITERAL("red.png"));
4413   int64_t image_size;
4414   GetFileSize(image_file, &image_size);
4415   ASSERT_GT(image_size, 0);
4416 
4417   // Insert the image into MediaStore. MediaStore will do some conversions, and
4418   // return the content URI.
4419   FilePath path = InsertImageIntoMediaStore(image_file);
4420   EXPECT_TRUE(path.IsContentUri());
4421   EXPECT_TRUE(PathExists(path));
4422   // The file size may not equal to the input image as MediaStore may convert
4423   // the image.
4424   int64_t content_uri_size;
4425   GetFileSize(path, &content_uri_size);
4426   EXPECT_EQ(image_size, content_uri_size);
4427 
4428   // We should be able to read the file.
4429   File file = OpenContentUriForRead(path);
4430   EXPECT_TRUE(file.IsValid());
4431   auto buffer = std::make_unique<char[]>(image_size);
4432   EXPECT_TRUE(file.ReadAtCurrentPos(buffer.get(), image_size));
4433 }
4434 
TEST_F(FileUtilTest,NonExistentContentUriTest)4435 TEST_F(FileUtilTest, NonExistentContentUriTest) {
4436   FilePath path("content://foo.bar");
4437   EXPECT_TRUE(path.IsContentUri());
4438   EXPECT_FALSE(PathExists(path));
4439   // Size should be smaller than 0.
4440   int64_t size;
4441   EXPECT_FALSE(GetFileSize(path, &size));
4442 
4443   // We should not be able to read the file.
4444   File file = OpenContentUriForRead(path);
4445   EXPECT_FALSE(file.IsValid());
4446 }
4447 #endif
4448 
TEST_F(FileUtilTest,GetUniquePathNumberNoFile)4449 TEST_F(FileUtilTest, GetUniquePathNumberNoFile) {
4450   // This file does not exist.
4451   const FilePath some_file = temp_dir_.GetPath().Append(FPL("SomeFile.txt"));
4452 
4453   // The path is unique as-is.
4454   EXPECT_EQ(GetUniquePathNumber(some_file), 0);
4455 }
4456 
TEST_F(FileUtilTest,GetUniquePathNumberFileExists)4457 TEST_F(FileUtilTest, GetUniquePathNumberFileExists) {
4458   // Create a file with the desired path.
4459   const FilePath some_file = temp_dir_.GetPath().Append(FPL("SomeFile.txt"));
4460   ASSERT_TRUE(File(some_file, File::FLAG_CREATE | File::FLAG_WRITE).IsValid());
4461 
4462   // The file exists, so the number 1 is needed to make it unique.
4463   EXPECT_EQ(GetUniquePathNumber(some_file), 1);
4464 }
4465 
TEST_F(FileUtilTest,GetUniquePathNumberFilesExist)4466 TEST_F(FileUtilTest, GetUniquePathNumberFilesExist) {
4467   // Create a file with the desired path and with it suffixed with " (1)"
4468   const FilePath some_file = temp_dir_.GetPath().Append(FPL("SomeFile.txt"));
4469   ASSERT_TRUE(File(some_file, File::FLAG_CREATE | File::FLAG_WRITE).IsValid());
4470   const FilePath some_file_one =
4471       temp_dir_.GetPath().Append(FPL("SomeFile (1).txt"));
4472   ASSERT_TRUE(
4473       File(some_file_one, File::FLAG_CREATE | File::FLAG_WRITE).IsValid());
4474 
4475   // This time the number 2 is needed to make it unique.
4476   EXPECT_EQ(GetUniquePathNumber(some_file), 2);
4477 }
4478 
TEST_F(FileUtilTest,GetUniquePathNumberTooManyFiles)4479 TEST_F(FileUtilTest, GetUniquePathNumberTooManyFiles) {
4480   // Create a file with the desired path.
4481   const FilePath some_file = temp_dir_.GetPath().Append(FPL("SomeFile.txt"));
4482   ASSERT_TRUE(File(some_file, File::FLAG_CREATE | File::FLAG_WRITE).IsValid());
4483 
4484   // Now create 100 collisions.
4485   for (int i = 1; i <= kMaxUniqueFiles; ++i) {
4486     ASSERT_EQ(GetUniquePathNumber(some_file), i);
4487     ASSERT_TRUE(File(temp_dir_.GetPath().AppendASCII(
4488                          StringPrintf("SomeFile (%d).txt", i)),
4489                      File::FLAG_CREATE | File::FLAG_WRITE)
4490                     .IsValid());
4491   }
4492 
4493   // Verify that the limit has been reached.
4494   EXPECT_EQ(GetUniquePathNumber(some_file), -1);
4495 }
4496 
TEST_F(FileUtilTest,PreReadFile_ExistingFile_NoSize)4497 TEST_F(FileUtilTest, PreReadFile_ExistingFile_NoSize) {
4498   FilePath text_file = temp_dir_.GetPath().Append(FPL("text_file"));
4499   CreateTextFile(text_file, bogus_content);
4500 
4501   EXPECT_TRUE(PreReadFile(text_file, /*is_executable=*/false));
4502 }
4503 
TEST_F(FileUtilTest,PreReadFile_ExistingFile_ExactSize)4504 TEST_F(FileUtilTest, PreReadFile_ExistingFile_ExactSize) {
4505   FilePath text_file = temp_dir_.GetPath().Append(FPL("text_file"));
4506   CreateTextFile(text_file, bogus_content);
4507 
4508   EXPECT_TRUE(PreReadFile(text_file, /*is_executable=*/false,
4509                           std::size(bogus_content)));
4510 }
4511 
TEST_F(FileUtilTest,PreReadFile_ExistingFile_OverSized)4512 TEST_F(FileUtilTest, PreReadFile_ExistingFile_OverSized) {
4513   FilePath text_file = temp_dir_.GetPath().Append(FPL("text_file"));
4514   CreateTextFile(text_file, bogus_content);
4515 
4516   EXPECT_TRUE(PreReadFile(text_file, /*is_executable=*/false,
4517                           std::size(bogus_content) * 2));
4518 }
4519 
TEST_F(FileUtilTest,PreReadFile_ExistingFile_UnderSized)4520 TEST_F(FileUtilTest, PreReadFile_ExistingFile_UnderSized) {
4521   FilePath text_file = temp_dir_.GetPath().Append(FPL("text_file"));
4522   CreateTextFile(text_file, bogus_content);
4523 
4524   EXPECT_TRUE(PreReadFile(text_file, /*is_executable=*/false,
4525                           std::size(bogus_content) / 2));
4526 }
4527 
TEST_F(FileUtilTest,PreReadFile_ExistingFile_ZeroSize)4528 TEST_F(FileUtilTest, PreReadFile_ExistingFile_ZeroSize) {
4529   FilePath text_file = temp_dir_.GetPath().Append(FPL("text_file"));
4530   CreateTextFile(text_file, bogus_content);
4531 
4532   EXPECT_TRUE(PreReadFile(text_file, /*is_executable=*/false, /*max_bytes=*/0));
4533 }
4534 
TEST_F(FileUtilTest,PreReadFile_ExistingEmptyFile_NoSize)4535 TEST_F(FileUtilTest, PreReadFile_ExistingEmptyFile_NoSize) {
4536   FilePath text_file = temp_dir_.GetPath().Append(FPL("text_file"));
4537   CreateTextFile(text_file, L"");
4538   // The test just asserts that this doesn't crash. The Windows implementation
4539   // fails in this case, due to the base::MemoryMappedFile implementation and
4540   // the limitations of ::MapViewOfFile().
4541   PreReadFile(text_file, /*is_executable=*/false);
4542 }
4543 
TEST_F(FileUtilTest,PreReadFile_ExistingEmptyFile_ZeroSize)4544 TEST_F(FileUtilTest, PreReadFile_ExistingEmptyFile_ZeroSize) {
4545   FilePath text_file = temp_dir_.GetPath().Append(FPL("text_file"));
4546   CreateTextFile(text_file, L"");
4547   EXPECT_TRUE(PreReadFile(text_file, /*is_executable=*/false, /*max_bytes=*/0));
4548 }
4549 
TEST_F(FileUtilTest,PreReadFile_InexistentFile)4550 TEST_F(FileUtilTest, PreReadFile_InexistentFile) {
4551   FilePath inexistent_file = temp_dir_.GetPath().Append(FPL("inexistent_file"));
4552   EXPECT_FALSE(PreReadFile(inexistent_file, /*is_executable=*/false));
4553 }
4554 
TEST_F(FileUtilTest,PreReadFile_Executable)4555 TEST_F(FileUtilTest, PreReadFile_Executable) {
4556   FilePath exe_data_dir;
4557   ASSERT_TRUE(PathService::Get(DIR_TEST_DATA, &exe_data_dir));
4558   exe_data_dir = exe_data_dir.Append(FPL("pe_image_reader"));
4559   ASSERT_TRUE(PathExists(exe_data_dir));
4560 
4561   // Load a sample executable and confirm that it was successfully prefetched.
4562   // `test_exe` is a Windows binary, which is fine in this case because only the
4563   // Windows implementation treats binaries differently from other files.
4564   const FilePath test_exe = exe_data_dir.Append(FPL("signed.exe"));
4565   EXPECT_TRUE(PreReadFile(test_exe, /*is_executable=*/true));
4566 }
4567 
4568 // Test that temp files obtained racily are all unique (no interference between
4569 // threads). Mimics file operations in DoLaunchChildTestProcess() to rule out
4570 // thread-safety issues @ https://crbug.com/826408#c17.
TEST(FileUtilMultiThreadedTest,MultiThreadedTempFiles)4571 TEST(FileUtilMultiThreadedTest, MultiThreadedTempFiles) {
4572 #if BUILDFLAG(IS_FUCHSIA)
4573   // TODO(crbug.com/844416): Too slow to run on infra due to QEMU overhead.
4574   constexpr int kNumThreads = 8;
4575 #else
4576   constexpr int kNumThreads = 64;
4577 #endif
4578   constexpr int kNumWritesPerThread = 32;
4579 
4580   std::unique_ptr<Thread> threads[kNumThreads];
4581   for (auto& thread : threads) {
4582     thread = std::make_unique<Thread>("test worker");
4583     thread->Start();
4584   }
4585 
4586   // Wait until all threads are started for max parallelism.
4587   for (auto& thread : threads)
4588     thread->WaitUntilThreadStarted();
4589 
4590   const RepeatingClosure open_write_close_read = BindRepeating([]() {
4591     FilePath output_filename;
4592     ScopedFILE output_file(CreateAndOpenTemporaryStream(&output_filename));
4593     EXPECT_TRUE(output_file);
4594 
4595     const std::string content = Uuid::GenerateRandomV4().AsLowercaseString();
4596 #if BUILDFLAG(IS_WIN)
4597     HANDLE handle =
4598         reinterpret_cast<HANDLE>(_get_osfhandle(_fileno(output_file.get())));
4599     DWORD bytes_written = 0;
4600     ::WriteFile(handle, content.c_str(), content.length(), &bytes_written,
4601                 NULL);
4602 #else
4603     size_t bytes_written =
4604         ::write(::fileno(output_file.get()), content.c_str(), content.length());
4605 #endif
4606     EXPECT_EQ(content.length(), bytes_written);
4607     ::fflush(output_file.get());
4608     output_file.reset();
4609 
4610     std::string output_file_contents;
4611     EXPECT_TRUE(ReadFileToString(output_filename, &output_file_contents))
4612         << output_filename;
4613 
4614     EXPECT_EQ(content, output_file_contents);
4615 
4616     DeleteFile(output_filename);
4617   });
4618 
4619   // Post tasks to each thread in a round-robin fashion to ensure as much
4620   // parallelism as possible.
4621   for (int i = 0; i < kNumWritesPerThread; ++i) {
4622     for (auto& thread : threads) {
4623       thread->task_runner()->PostTask(FROM_HERE, open_write_close_read);
4624     }
4625   }
4626 
4627   for (auto& thread : threads)
4628     thread->Stop();
4629 }
4630 
4631 #if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
4632 
TEST(ScopedFD,ScopedFDDoesClose)4633 TEST(ScopedFD, ScopedFDDoesClose) {
4634   int fds[2];
4635   char c = 0;
4636   ASSERT_EQ(0, pipe(fds));
4637   const int write_end = fds[1];
4638   ScopedFD read_end_closer(fds[0]);
4639   {
4640     ScopedFD write_end_closer(fds[1]);
4641   }
4642   // This is the only thread. This file descriptor should no longer be valid.
4643   int ret = close(write_end);
4644   EXPECT_EQ(-1, ret);
4645   EXPECT_EQ(EBADF, errno);
4646   // Make sure read(2) won't block.
4647   ASSERT_EQ(0, fcntl(fds[0], F_SETFL, O_NONBLOCK));
4648   // Reading the pipe should EOF.
4649   EXPECT_EQ(0, read(fds[0], &c, 1));
4650 }
4651 
4652 #if defined(GTEST_HAS_DEATH_TEST)
CloseWithScopedFD(int fd)4653 void CloseWithScopedFD(int fd) {
4654   ScopedFD fd_closer(fd);
4655 }
4656 #endif
4657 
TEST(ScopedFD,ScopedFDCrashesOnCloseFailure)4658 TEST(ScopedFD, ScopedFDCrashesOnCloseFailure) {
4659   int fds[2];
4660   ASSERT_EQ(0, pipe(fds));
4661   ScopedFD read_end_closer(fds[0]);
4662   EXPECT_EQ(0, IGNORE_EINTR(close(fds[1])));
4663 #if defined(GTEST_HAS_DEATH_TEST)
4664   // This is the only thread. This file descriptor should no longer be valid.
4665   // Trying to close it should crash. This is important for security.
4666   EXPECT_DEATH(CloseWithScopedFD(fds[1]), "");
4667 #endif
4668 }
4669 
4670 #endif  // BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
4671 
4672 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID)
TEST_F(FileUtilTest,CopyFileContentsWithSendfile)4673 TEST_F(FileUtilTest, CopyFileContentsWithSendfile) {
4674   // This test validates that sendfile(2) can be used to copy a file contents
4675   // and that it will honor the file offsets as CopyFileContents does.
4676   FilePath file_name_from = temp_dir_.GetPath().Append(
4677       FILE_PATH_LITERAL("copy_contents_file_in.txt"));
4678   FilePath file_name_to = temp_dir_.GetPath().Append(
4679       FILE_PATH_LITERAL("copy_contents_file_out.txt"));
4680 
4681   const std::wstring from_contents(L"0123456789ABCDEF");
4682   CreateTextFile(file_name_from, from_contents);
4683   ASSERT_TRUE(PathExists(file_name_from));
4684 
4685   const std::wstring to_contents(L"GHIJKL");
4686   CreateTextFile(file_name_to, to_contents);
4687   ASSERT_TRUE(PathExists(file_name_to));
4688 
4689   File from(file_name_from, File::FLAG_OPEN | File::FLAG_READ);
4690   ASSERT_TRUE(from.IsValid());
4691 
4692   File to(file_name_to, File::FLAG_OPEN | File::FLAG_WRITE);
4693   ASSERT_TRUE(to.IsValid());
4694 
4695   // See to the 1st byte in each file.
4696   ASSERT_EQ(from.Seek(File::Whence::FROM_BEGIN, 1), 1);
4697   ASSERT_EQ(to.Seek(File::Whence::FROM_BEGIN, 1), 1);
4698 
4699   bool retry_slow = false;
4700 
4701   // Given the test setup there should never be a sendfile(2) failure.
4702   ASSERT_TRUE(internal::CopyFileContentsWithSendfile(from, to, retry_slow));
4703   from.Close();
4704   to.Close();
4705 
4706   // Expect the output file contents to be: G123456789ABCDEF because both
4707   // file positions when we copied the file contents were at 1.
4708   EXPECT_EQ(L"G123456789ABCDEF", ReadTextFile(file_name_to));
4709 }
4710 
TEST_F(FileUtilTest,CopyFileContentsWithSendfileEmpty)4711 TEST_F(FileUtilTest, CopyFileContentsWithSendfileEmpty) {
4712   FilePath file_name_from = temp_dir_.GetPath().Append(
4713       FILE_PATH_LITERAL("copy_contents_file_in.txt"));
4714   FilePath file_name_to = temp_dir_.GetPath().Append(
4715       FILE_PATH_LITERAL("copy_contents_file_out.txt"));
4716 
4717   const std::wstring from_contents(L"");
4718   CreateTextFile(file_name_from, from_contents);
4719   ASSERT_TRUE(PathExists(file_name_from));
4720 
4721   const std::wstring to_contents(L"");
4722   CreateTextFile(file_name_to, to_contents);
4723   ASSERT_TRUE(PathExists(file_name_to));
4724 
4725   File from(file_name_from, File::FLAG_OPEN | File::FLAG_READ);
4726   ASSERT_TRUE(from.IsValid());
4727 
4728   File to(file_name_to, File::FLAG_OPEN | File::FLAG_WRITE);
4729   ASSERT_TRUE(to.IsValid());
4730 
4731   bool retry_slow = false;
4732 
4733   ASSERT_FALSE(internal::CopyFileContentsWithSendfile(from, to, retry_slow));
4734   ASSERT_TRUE(retry_slow);
4735 
4736   from.Close();
4737   to.Close();
4738 
4739   EXPECT_EQ(L"", ReadTextFile(file_name_to));
4740 }
4741 
TEST_F(FileUtilTest,CopyFileContentsWithSendfilePipe)4742 TEST_F(FileUtilTest, CopyFileContentsWithSendfilePipe) {
4743   FilePath file_name_to = temp_dir_.GetPath().Append(
4744       FILE_PATH_LITERAL("copy_contents_file_out.txt"));
4745 
4746   File to(file_name_to,
4747           File::FLAG_OPEN | File::FLAG_WRITE | File::FLAG_CREATE_ALWAYS);
4748   ASSERT_TRUE(to.IsValid());
4749 
4750   // This test validates that CopyFileContentsWithSendfile fails with a pipe and
4751   // retry_slow is set.
4752   int fd[2];
4753   ASSERT_EQ(pipe2(fd, O_CLOEXEC), 0);
4754 
4755   // For good measure write some data into the pipe.
4756   const char* buf = "hello world";
4757   ASSERT_EQ(write(fd[1], buf, sizeof(buf)), static_cast<int>(sizeof(buf)));
4758 
4759   // fd[0] refers to the read end of the pipe.
4760   bool retry_slow = false;
4761   base::PlatformFile pipe_read_end(fd[0]);
4762   base::File pipe_read(pipe_read_end);
4763   ASSERT_FALSE(
4764       internal::CopyFileContentsWithSendfile(pipe_read, to, retry_slow));
4765   ASSERT_TRUE(retry_slow);
4766 }
4767 
TEST_F(FileUtilTest,CopyFileContentsWithSendfileSocket)4768 TEST_F(FileUtilTest, CopyFileContentsWithSendfileSocket) {
4769   // This test validates that CopyFileContentsWithSendfile fails with a socket
4770   // and retry_slow is set.
4771   int sock[2];
4772   ASSERT_EQ(socketpair(AF_UNIX, SOCK_STREAM, 0, sock), 0);
4773 
4774   FilePath file_name_from = temp_dir_.GetPath().Append(
4775       FILE_PATH_LITERAL("copy_contents_file_in.txt"));
4776   FilePath file_name_to = temp_dir_.GetPath().Append(
4777       FILE_PATH_LITERAL("copy_contents_file_out.txt"));
4778   const std::wstring from_contents(L"0123456789ABCDEF");
4779   CreateTextFile(file_name_from, from_contents);
4780   ASSERT_TRUE(PathExists(file_name_from));
4781 
4782   File from(file_name_from, File::FLAG_OPEN | File::FLAG_READ);
4783   ASSERT_TRUE(from.IsValid());
4784 
4785   base::PlatformFile to_file(sock[0]);
4786   base::File to_sock(to_file);
4787 
4788   // Copying from a file to a socket will work.
4789   bool retry_slow = false;
4790   ASSERT_TRUE(
4791       internal::CopyFileContentsWithSendfile(from, to_sock, retry_slow));
4792 
4793   // But copying for a socket to a file will not.
4794   base::PlatformFile from_sock_file(sock[1]);
4795   base::File from_sock(from_sock_file);
4796 
4797   File to(file_name_to,
4798           File::FLAG_OPEN | File::FLAG_WRITE | File::FLAG_CREATE_ALWAYS);
4799   ASSERT_TRUE(to.IsValid());
4800   ASSERT_FALSE(
4801       internal::CopyFileContentsWithSendfile(from_sock, to, retry_slow));
4802   ASSERT_TRUE(retry_slow);
4803 }
4804 
TEST_F(FileUtilTest,CopyFileContentsWithSendfileSeqFile)4805 TEST_F(FileUtilTest, CopyFileContentsWithSendfileSeqFile) {
4806   // This test verifies the special case where we have a regular file with zero
4807   // length that might actually have contents (such as a seq_file).
4808   for (auto* const file : {"/proc/meminfo", "/proc/self/cmdline",
4809                            "/proc/self/environ", "/proc/self/auxv"}) {
4810     FilePath proc_file_from(file);
4811     File from(proc_file_from, File::FLAG_OPEN | File::FLAG_READ);
4812     ASSERT_TRUE(from.IsValid()) << "could not open " << file;
4813 
4814     FilePath file_name_to = temp_dir_.GetPath().Append(
4815         FILE_PATH_LITERAL("copy_contents_file_out.txt"));
4816     File to(file_name_to,
4817             File::FLAG_OPEN | File::FLAG_WRITE | File::FLAG_CREATE_ALWAYS);
4818     ASSERT_TRUE(to.IsValid());
4819 
4820     bool retry_slow = false;
4821     ASSERT_FALSE(internal::CopyFileContentsWithSendfile(from, to, retry_slow))
4822         << proc_file_from << " should have failed";
4823     ASSERT_TRUE(retry_slow)
4824         << "retry slow for " << proc_file_from << " should be set";
4825 
4826     // Now let's make sure we can copy it the "slow" way.
4827     ASSERT_TRUE(base::CopyFileContents(from, to));
4828     ASSERT_GT(to.GetLength(), 0);
4829     ASSERT_TRUE(base::DeleteFile(file_name_to));
4830   }
4831 }
4832 
4833 #endif  // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) ||
4834         // BUILDFLAG(IS_ANDROID)
4835 
4836 }  // namespace
4837 
4838 }  // namespace base
4839