• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include <stddef.h>
6 #include <stdint.h>
7 #include <stdio.h>
8 
9 #include <algorithm>
10 #include <fstream>
11 #include <initializer_list>
12 #include <memory>
13 #include <set>
14 #include <utility>
15 #include <vector>
16 
17 #include "base/base_paths.h"
18 #include "base/bind.h"
19 #include "base/bind_helpers.h"
20 #include "base/callback_helpers.h"
21 #include "base/command_line.h"
22 #include "base/environment.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/file_util.h"
27 #include "base/files/scoped_file.h"
28 #include "base/files/scoped_temp_dir.h"
29 #include "base/guid.h"
30 #include "base/macros.h"
31 #include "base/path_service.h"
32 #include "base/strings/string_util.h"
33 #include "base/strings/utf_string_conversions.h"
34 #include "base/test/multiprocess_test.h"
35 #include "base/test/scoped_environment_variable_override.h"
36 #include "base/test/test_file_util.h"
37 #include "base/test/test_timeouts.h"
38 #include "base/threading/platform_thread.h"
39 #include "base/threading/thread.h"
40 #include "build/build_config.h"
41 #include "testing/gtest/include/gtest/gtest.h"
42 #include "testing/multiprocess_func_list.h"
43 #include "testing/platform_test.h"
44 
45 #if defined(OS_WIN)
46 #include <shellapi.h>
47 #include <shlobj.h>
48 #include <tchar.h>
49 #include <windows.h>
50 #include <winioctl.h>
51 #include "base/strings/string_number_conversions.h"
52 #include "base/win/scoped_handle.h"
53 #include "base/win/win_util.h"
54 #endif
55 
56 #if defined(OS_POSIX) || defined(OS_FUCHSIA)
57 #include <errno.h>
58 #include <fcntl.h>
59 #include <sys/ioctl.h>
60 #include <sys/stat.h>
61 #include <sys/types.h>
62 #include <unistd.h>
63 #endif
64 
65 #if defined(OS_LINUX)
66 #include <linux/fs.h>
67 #endif
68 
69 #if defined(OS_ANDROID)
70 #include "base/android/content_uri_utils.h"
71 #endif
72 
73 // This macro helps avoid wrapped lines in the test structs.
74 #define FPL(x) FILE_PATH_LITERAL(x)
75 
76 namespace base {
77 
78 namespace {
79 
80 const size_t kLargeFileSize = (1 << 16) + 3;
81 
82 // To test that NormalizeFilePath() deals with NTFS reparse points correctly,
83 // we need functions to create and delete reparse points.
84 #if defined(OS_WIN)
85 typedef struct _REPARSE_DATA_BUFFER {
86   ULONG  ReparseTag;
87   USHORT  ReparseDataLength;
88   USHORT  Reserved;
89   union {
90     struct {
91       USHORT SubstituteNameOffset;
92       USHORT SubstituteNameLength;
93       USHORT PrintNameOffset;
94       USHORT PrintNameLength;
95       ULONG Flags;
96       WCHAR PathBuffer[1];
97     } SymbolicLinkReparseBuffer;
98     struct {
99       USHORT SubstituteNameOffset;
100       USHORT SubstituteNameLength;
101       USHORT PrintNameOffset;
102       USHORT PrintNameLength;
103       WCHAR PathBuffer[1];
104     } MountPointReparseBuffer;
105     struct {
106       UCHAR DataBuffer[1];
107     } GenericReparseBuffer;
108   };
109 } REPARSE_DATA_BUFFER, *PREPARSE_DATA_BUFFER;
110 
111 // Sets a reparse point. |source| will now point to |target|. Returns true if
112 // the call succeeds, false otherwise.
SetReparsePoint(HANDLE source,const FilePath & target_path)113 bool SetReparsePoint(HANDLE source, const FilePath& target_path) {
114   std::wstring kPathPrefix = L"\\??\\";
115   std::wstring target_str;
116   // The juction will not work if the target path does not start with \??\ .
117   if (kPathPrefix != target_path.value().substr(0, kPathPrefix.size()))
118     target_str += kPathPrefix;
119   target_str += target_path.value();
120   const wchar_t* target = target_str.c_str();
121   USHORT size_target = static_cast<USHORT>(wcslen(target)) * sizeof(target[0]);
122   char buffer[2000] = {0};
123   DWORD returned;
124 
125   REPARSE_DATA_BUFFER* data = reinterpret_cast<REPARSE_DATA_BUFFER*>(buffer);
126 
127   data->ReparseTag = 0xa0000003;
128   memcpy(data->MountPointReparseBuffer.PathBuffer, target, size_target + 2);
129 
130   data->MountPointReparseBuffer.SubstituteNameLength = size_target;
131   data->MountPointReparseBuffer.PrintNameOffset = size_target + 2;
132   data->ReparseDataLength = size_target + 4 + 8;
133 
134   int data_size = data->ReparseDataLength + 8;
135 
136   if (!DeviceIoControl(source, FSCTL_SET_REPARSE_POINT, &buffer, data_size,
137                        NULL, 0, &returned, NULL)) {
138     return false;
139   }
140   return true;
141 }
142 
143 // Delete the reparse point referenced by |source|. Returns true if the call
144 // succeeds, false otherwise.
DeleteReparsePoint(HANDLE source)145 bool DeleteReparsePoint(HANDLE source) {
146   DWORD returned;
147   REPARSE_DATA_BUFFER data = {0};
148   data.ReparseTag = 0xa0000003;
149   if (!DeviceIoControl(source, FSCTL_DELETE_REPARSE_POINT, &data, 8, NULL, 0,
150                        &returned, NULL)) {
151     return false;
152   }
153   return true;
154 }
155 
156 // Manages a reparse point for a test.
157 class ReparsePoint {
158  public:
159   // Creates a reparse point from |source| (an empty directory) to |target|.
ReparsePoint(const FilePath & source,const FilePath & target)160   ReparsePoint(const FilePath& source, const FilePath& target) {
161     dir_.Set(
162       ::CreateFile(source.value().c_str(),
163                    GENERIC_READ | GENERIC_WRITE,
164                    FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
165                    NULL,
166                    OPEN_EXISTING,
167                    FILE_FLAG_BACKUP_SEMANTICS,  // Needed to open a directory.
168                    NULL));
169     created_ = dir_.IsValid() && SetReparsePoint(dir_.Get(), target);
170   }
171 
~ReparsePoint()172   ~ReparsePoint() {
173     if (created_)
174       DeleteReparsePoint(dir_.Get());
175   }
176 
IsValid()177   bool IsValid() { return created_; }
178 
179  private:
180   win::ScopedHandle dir_;
181   bool created_;
182   DISALLOW_COPY_AND_ASSIGN(ReparsePoint);
183 };
184 
185 #endif
186 
187 // Fuchsia doesn't support file permissions.
188 #if !defined(OS_FUCHSIA)
189 #if defined(OS_POSIX)
190 // Provide a simple way to change the permissions bits on |path| in tests.
191 // ASSERT failures will return, but not stop the test.  Caller should wrap
192 // calls to this function in ASSERT_NO_FATAL_FAILURE().
ChangePosixFilePermissions(const FilePath & path,int mode_bits_to_set,int mode_bits_to_clear)193 void ChangePosixFilePermissions(const FilePath& path,
194                                 int mode_bits_to_set,
195                                 int mode_bits_to_clear) {
196   ASSERT_FALSE(mode_bits_to_set & mode_bits_to_clear)
197       << "Can't set and clear the same bits.";
198 
199   int mode = 0;
200   ASSERT_TRUE(GetPosixFilePermissions(path, &mode));
201   mode |= mode_bits_to_set;
202   mode &= ~mode_bits_to_clear;
203   ASSERT_TRUE(SetPosixFilePermissions(path, mode));
204 }
205 #endif  // defined(OS_POSIX)
206 
207 // Sets the source file to read-only.
SetReadOnly(const FilePath & path,bool read_only)208 void SetReadOnly(const FilePath& path, bool read_only) {
209 #if defined(OS_WIN)
210   // On Windows, it involves setting/removing the 'readonly' bit.
211   DWORD attrs = GetFileAttributes(path.value().c_str());
212   ASSERT_NE(INVALID_FILE_ATTRIBUTES, attrs);
213   ASSERT_TRUE(SetFileAttributes(
214       path.value().c_str(), read_only ? (attrs | FILE_ATTRIBUTE_READONLY)
215                                       : (attrs & ~FILE_ATTRIBUTE_READONLY)));
216 
217   DWORD expected =
218       read_only
219           ? ((attrs & (FILE_ATTRIBUTE_ARCHIVE | FILE_ATTRIBUTE_DIRECTORY)) |
220              FILE_ATTRIBUTE_READONLY)
221           : (attrs & (FILE_ATTRIBUTE_ARCHIVE | FILE_ATTRIBUTE_DIRECTORY));
222 
223   // Ignore FILE_ATTRIBUTE_NOT_CONTENT_INDEXED if present.
224   attrs = GetFileAttributes(path.value().c_str()) &
225           ~FILE_ATTRIBUTE_NOT_CONTENT_INDEXED;
226   ASSERT_EQ(expected, attrs);
227 #else
228   // On all other platforms, it involves removing/setting the write bit.
229   mode_t mode = read_only ? S_IRUSR : (S_IRUSR | S_IWUSR);
230   EXPECT_TRUE(SetPosixFilePermissions(
231       path, DirectoryExists(path) ? (mode | S_IXUSR) : mode));
232 #endif  // defined(OS_WIN)
233 }
234 
IsReadOnly(const FilePath & path)235 bool IsReadOnly(const FilePath& path) {
236 #if defined(OS_WIN)
237   DWORD attrs = GetFileAttributes(path.value().c_str());
238   EXPECT_NE(INVALID_FILE_ATTRIBUTES, attrs);
239   return attrs & FILE_ATTRIBUTE_READONLY;
240 #else
241   int mode = 0;
242   EXPECT_TRUE(GetPosixFilePermissions(path, &mode));
243   return !(mode & S_IWUSR);
244 #endif  // defined(OS_WIN)
245 }
246 
247 #endif  // defined(OS_FUCHSIA)
248 
249 const wchar_t bogus_content[] = L"I'm cannon fodder.";
250 
251 const int FILES_AND_DIRECTORIES =
252     FileEnumerator::FILES | FileEnumerator::DIRECTORIES;
253 
254 // file_util winds up using autoreleased objects on the Mac, so this needs
255 // to be a PlatformTest
256 class FileUtilTest : public PlatformTest {
257  protected:
SetUp()258   void SetUp() override {
259     PlatformTest::SetUp();
260     ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
261   }
262 
263   ScopedTempDir temp_dir_;
264 };
265 
266 // Collects all the results from the given file enumerator, and provides an
267 // interface to query whether a given file is present.
268 class FindResultCollector {
269  public:
FindResultCollector(FileEnumerator * enumerator)270   explicit FindResultCollector(FileEnumerator* enumerator) {
271     FilePath cur_file;
272     while (!(cur_file = enumerator->Next()).value().empty()) {
273       FilePath::StringType path = cur_file.value();
274       // The file should not be returned twice.
275       EXPECT_TRUE(files_.end() == files_.find(path))
276           << "Same file returned twice";
277 
278       // Save for later.
279       files_.insert(path);
280     }
281   }
282 
283   // Returns true if the enumerator found the file.
HasFile(const FilePath & file) const284   bool HasFile(const FilePath& file) const {
285     return files_.find(file.value()) != files_.end();
286   }
287 
size()288   int size() {
289     return static_cast<int>(files_.size());
290   }
291 
292  private:
293   std::set<FilePath::StringType> files_;
294 };
295 
296 // Simple function to dump some text into a new file.
CreateTextFile(const FilePath & filename,const std::wstring & contents)297 void CreateTextFile(const FilePath& filename,
298                     const std::wstring& contents) {
299   std::wofstream file;
300   file.open(filename.value().c_str());
301   ASSERT_TRUE(file.is_open());
302   file << contents;
303   file.close();
304 }
305 
306 // Simple function to take out some text from a file.
ReadTextFile(const FilePath & filename)307 std::wstring ReadTextFile(const FilePath& filename) {
308   wchar_t contents[64];
309   std::wifstream file;
310   file.open(filename.value().c_str());
311   EXPECT_TRUE(file.is_open());
312   file.getline(contents, arraysize(contents));
313   file.close();
314   return std::wstring(contents);
315 }
316 
317 // Sets |is_inheritable| to indicate whether or not |stream| is set up to be
318 // inerhited into child processes (i.e., HANDLE_FLAG_INHERIT is set on the
319 // underlying handle on Windows, or FD_CLOEXEC is not set on the underlying file
320 // descriptor on POSIX). Calls to this function must be wrapped with
321 // ASSERT_NO_FATAL_FAILURE to properly abort tests in case of fatal failure.
GetIsInheritable(FILE * stream,bool * is_inheritable)322 void GetIsInheritable(FILE* stream, bool* is_inheritable) {
323 #if defined(OS_WIN)
324   HANDLE handle = reinterpret_cast<HANDLE>(_get_osfhandle(_fileno(stream)));
325   ASSERT_NE(INVALID_HANDLE_VALUE, handle);
326 
327   DWORD info = 0;
328   ASSERT_EQ(TRUE, ::GetHandleInformation(handle, &info));
329   *is_inheritable = ((info & HANDLE_FLAG_INHERIT) != 0);
330 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
331   int fd = fileno(stream);
332   ASSERT_NE(-1, fd);
333   int flags = fcntl(fd, F_GETFD, 0);
334   ASSERT_NE(-1, flags);
335   *is_inheritable = ((flags & FD_CLOEXEC) == 0);
336 #else
337 #error Not implemented
338 #endif
339 }
340 
TEST_F(FileUtilTest,FileAndDirectorySize)341 TEST_F(FileUtilTest, FileAndDirectorySize) {
342   // Create three files of 20, 30 and 3 chars (utf8). ComputeDirectorySize
343   // should return 53 bytes.
344   FilePath file_01 = temp_dir_.GetPath().Append(FPL("The file 01.txt"));
345   CreateTextFile(file_01, L"12345678901234567890");
346   int64_t size_f1 = 0;
347   ASSERT_TRUE(GetFileSize(file_01, &size_f1));
348   EXPECT_EQ(20ll, size_f1);
349 
350   FilePath subdir_path = temp_dir_.GetPath().Append(FPL("Level2"));
351   CreateDirectory(subdir_path);
352 
353   FilePath file_02 = subdir_path.Append(FPL("The file 02.txt"));
354   CreateTextFile(file_02, L"123456789012345678901234567890");
355   int64_t size_f2 = 0;
356   ASSERT_TRUE(GetFileSize(file_02, &size_f2));
357   EXPECT_EQ(30ll, size_f2);
358 
359   FilePath subsubdir_path = subdir_path.Append(FPL("Level3"));
360   CreateDirectory(subsubdir_path);
361 
362   FilePath file_03 = subsubdir_path.Append(FPL("The file 03.txt"));
363   CreateTextFile(file_03, L"123");
364 
365   int64_t computed_size = ComputeDirectorySize(temp_dir_.GetPath());
366   EXPECT_EQ(size_f1 + size_f2 + 3, computed_size);
367 }
368 
TEST_F(FileUtilTest,NormalizeFilePathBasic)369 TEST_F(FileUtilTest, NormalizeFilePathBasic) {
370   // Create a directory under the test dir.  Because we create it,
371   // we know it is not a link.
372   FilePath file_a_path = temp_dir_.GetPath().Append(FPL("file_a"));
373   FilePath dir_path = temp_dir_.GetPath().Append(FPL("dir"));
374   FilePath file_b_path = dir_path.Append(FPL("file_b"));
375   CreateDirectory(dir_path);
376 
377   FilePath normalized_file_a_path, normalized_file_b_path;
378   ASSERT_FALSE(PathExists(file_a_path));
379   ASSERT_FALSE(NormalizeFilePath(file_a_path, &normalized_file_a_path))
380     << "NormalizeFilePath() should fail on nonexistent paths.";
381 
382   CreateTextFile(file_a_path, bogus_content);
383   ASSERT_TRUE(PathExists(file_a_path));
384   ASSERT_TRUE(NormalizeFilePath(file_a_path, &normalized_file_a_path));
385 
386   CreateTextFile(file_b_path, bogus_content);
387   ASSERT_TRUE(PathExists(file_b_path));
388   ASSERT_TRUE(NormalizeFilePath(file_b_path, &normalized_file_b_path));
389 
390   // Beacuse this test created |dir_path|, we know it is not a link
391   // or junction.  So, the real path of the directory holding file a
392   // must be the parent of the path holding file b.
393   ASSERT_TRUE(normalized_file_a_path.DirName()
394       .IsParent(normalized_file_b_path.DirName()));
395 }
396 
397 #if defined(OS_WIN)
398 
TEST_F(FileUtilTest,NormalizeFilePathReparsePoints)399 TEST_F(FileUtilTest, NormalizeFilePathReparsePoints) {
400   // Build the following directory structure:
401   //
402   // temp_dir
403   // |-> base_a
404   // |   |-> sub_a
405   // |       |-> file.txt
406   // |       |-> long_name___... (Very long name.)
407   // |           |-> sub_long
408   // |              |-> deep.txt
409   // |-> base_b
410   //     |-> to_sub_a (reparse point to temp_dir\base_a\sub_a)
411   //     |-> to_base_b (reparse point to temp_dir\base_b)
412   //     |-> to_sub_long (reparse point to temp_dir\sub_a\long_name_\sub_long)
413 
414   FilePath base_a = temp_dir_.GetPath().Append(FPL("base_a"));
415 #if defined(OS_WIN)
416   // TEMP can have a lower case drive letter.
417   string16 temp_base_a = base_a.value();
418   ASSERT_FALSE(temp_base_a.empty());
419   *temp_base_a.begin() = ToUpperASCII(*temp_base_a.begin());
420   base_a = FilePath(temp_base_a);
421 #endif
422   ASSERT_TRUE(CreateDirectory(base_a));
423 
424   FilePath sub_a = base_a.Append(FPL("sub_a"));
425   ASSERT_TRUE(CreateDirectory(sub_a));
426 
427   FilePath file_txt = sub_a.Append(FPL("file.txt"));
428   CreateTextFile(file_txt, bogus_content);
429 
430   // Want a directory whose name is long enough to make the path to the file
431   // inside just under MAX_PATH chars.  This will be used to test that when
432   // a junction expands to a path over MAX_PATH chars in length,
433   // NormalizeFilePath() fails without crashing.
434   FilePath sub_long_rel(FPL("sub_long"));
435   FilePath deep_txt(FPL("deep.txt"));
436 
437   int target_length = MAX_PATH;
438   target_length -= (sub_a.value().length() + 1);  // +1 for the sepperator '\'.
439   target_length -= (sub_long_rel.Append(deep_txt).value().length() + 1);
440   // Without making the path a bit shorter, CreateDirectory() fails.
441   // the resulting path is still long enough to hit the failing case in
442   // NormalizePath().
443   const int kCreateDirLimit = 4;
444   target_length -= kCreateDirLimit;
445   FilePath::StringType long_name_str = FPL("long_name_");
446   long_name_str.resize(target_length, '_');
447 
448   FilePath long_name = sub_a.Append(FilePath(long_name_str));
449   FilePath deep_file = long_name.Append(sub_long_rel).Append(deep_txt);
450   ASSERT_EQ(static_cast<size_t>(MAX_PATH - kCreateDirLimit),
451             deep_file.value().length());
452 
453   FilePath sub_long = deep_file.DirName();
454   ASSERT_TRUE(CreateDirectory(sub_long));
455   CreateTextFile(deep_file, bogus_content);
456 
457   FilePath base_b = temp_dir_.GetPath().Append(FPL("base_b"));
458   ASSERT_TRUE(CreateDirectory(base_b));
459 
460   FilePath to_sub_a = base_b.Append(FPL("to_sub_a"));
461   ASSERT_TRUE(CreateDirectory(to_sub_a));
462   FilePath normalized_path;
463   {
464     ReparsePoint reparse_to_sub_a(to_sub_a, sub_a);
465     ASSERT_TRUE(reparse_to_sub_a.IsValid());
466 
467     FilePath to_base_b = base_b.Append(FPL("to_base_b"));
468     ASSERT_TRUE(CreateDirectory(to_base_b));
469     ReparsePoint reparse_to_base_b(to_base_b, base_b);
470     ASSERT_TRUE(reparse_to_base_b.IsValid());
471 
472     FilePath to_sub_long = base_b.Append(FPL("to_sub_long"));
473     ASSERT_TRUE(CreateDirectory(to_sub_long));
474     ReparsePoint reparse_to_sub_long(to_sub_long, sub_long);
475     ASSERT_TRUE(reparse_to_sub_long.IsValid());
476 
477     // Normalize a junction free path: base_a\sub_a\file.txt .
478     ASSERT_TRUE(NormalizeFilePath(file_txt, &normalized_path));
479     ASSERT_STREQ(file_txt.value().c_str(), normalized_path.value().c_str());
480 
481     // Check that the path base_b\to_sub_a\file.txt can be normalized to exclude
482     // the junction to_sub_a.
483     ASSERT_TRUE(NormalizeFilePath(to_sub_a.Append(FPL("file.txt")),
484                                              &normalized_path));
485     ASSERT_STREQ(file_txt.value().c_str(), normalized_path.value().c_str());
486 
487     // Check that the path base_b\to_base_b\to_base_b\to_sub_a\file.txt can be
488     // normalized to exclude junctions to_base_b and to_sub_a .
489     ASSERT_TRUE(NormalizeFilePath(base_b.Append(FPL("to_base_b"))
490                                                    .Append(FPL("to_base_b"))
491                                                    .Append(FPL("to_sub_a"))
492                                                    .Append(FPL("file.txt")),
493                                              &normalized_path));
494     ASSERT_STREQ(file_txt.value().c_str(), normalized_path.value().c_str());
495 
496     // A long enough path will cause NormalizeFilePath() to fail.  Make a long
497     // path using to_base_b many times, and check that paths long enough to fail
498     // do not cause a crash.
499     FilePath long_path = base_b;
500     const int kLengthLimit = MAX_PATH + 200;
501     while (long_path.value().length() <= kLengthLimit) {
502       long_path = long_path.Append(FPL("to_base_b"));
503     }
504     long_path = long_path.Append(FPL("to_sub_a"))
505                          .Append(FPL("file.txt"));
506 
507     ASSERT_FALSE(NormalizeFilePath(long_path, &normalized_path));
508 
509     // Normalizing the junction to deep.txt should fail, because the expanded
510     // path to deep.txt is longer than MAX_PATH.
511     ASSERT_FALSE(NormalizeFilePath(to_sub_long.Append(deep_txt),
512                                               &normalized_path));
513 
514     // Delete the reparse points, and see that NormalizeFilePath() fails
515     // to traverse them.
516   }
517 
518   ASSERT_FALSE(NormalizeFilePath(to_sub_a.Append(FPL("file.txt")),
519                                             &normalized_path));
520 }
521 
TEST_F(FileUtilTest,DevicePathToDriveLetter)522 TEST_F(FileUtilTest, DevicePathToDriveLetter) {
523   // Get a drive letter.
524   string16 real_drive_letter =
525       ToUpperASCII(temp_dir_.GetPath().value().substr(0, 2));
526   if (!isalpha(real_drive_letter[0]) || ':' != real_drive_letter[1]) {
527     LOG(ERROR) << "Can't get a drive letter to test with.";
528     return;
529   }
530 
531   // Get the NT style path to that drive.
532   wchar_t device_path[MAX_PATH] = {'\0'};
533   ASSERT_TRUE(
534       ::QueryDosDevice(real_drive_letter.c_str(), device_path, MAX_PATH));
535   FilePath actual_device_path(device_path);
536   FilePath win32_path;
537 
538   // Run DevicePathToDriveLetterPath() on the NT style path we got from
539   // QueryDosDevice().  Expect the drive letter we started with.
540   ASSERT_TRUE(DevicePathToDriveLetterPath(actual_device_path, &win32_path));
541   ASSERT_EQ(real_drive_letter, win32_path.value());
542 
543   // Add some directories to the path.  Expect those extra path componenets
544   // to be preserved.
545   FilePath kRelativePath(FPL("dir1\\dir2\\file.txt"));
546   ASSERT_TRUE(DevicePathToDriveLetterPath(
547       actual_device_path.Append(kRelativePath),
548       &win32_path));
549   EXPECT_EQ(FilePath(real_drive_letter + L"\\").Append(kRelativePath).value(),
550             win32_path.value());
551 
552   // Deform the real path so that it is invalid by removing the last four
553   // characters.  The way windows names devices that are hard disks
554   // (\Device\HardDiskVolume${NUMBER}) guarantees that the string is longer
555   // than three characters.  The only way the truncated string could be a
556   // real drive is if more than 10^3 disks are mounted:
557   // \Device\HardDiskVolume10000 would be truncated to \Device\HardDiskVolume1
558   // Check that DevicePathToDriveLetterPath fails.
559   int path_length = actual_device_path.value().length();
560   int new_length = path_length - 4;
561   ASSERT_LT(0, new_length);
562   FilePath prefix_of_real_device_path(
563       actual_device_path.value().substr(0, new_length));
564   ASSERT_FALSE(DevicePathToDriveLetterPath(prefix_of_real_device_path,
565                                            &win32_path));
566 
567   ASSERT_FALSE(DevicePathToDriveLetterPath(
568       prefix_of_real_device_path.Append(kRelativePath),
569       &win32_path));
570 
571   // Deform the real path so that it is invalid by adding some characters. For
572   // example, if C: maps to \Device\HardDiskVolume8, then we simulate a
573   // request for the drive letter whose native path is
574   // \Device\HardDiskVolume812345 .  We assume such a device does not exist,
575   // because drives are numbered in order and mounting 112345 hard disks will
576   // never happen.
577   const FilePath::StringType kExtraChars = FPL("12345");
578 
579   FilePath real_device_path_plus_numbers(
580       actual_device_path.value() + kExtraChars);
581 
582   ASSERT_FALSE(DevicePathToDriveLetterPath(
583       real_device_path_plus_numbers,
584       &win32_path));
585 
586   ASSERT_FALSE(DevicePathToDriveLetterPath(
587       real_device_path_plus_numbers.Append(kRelativePath),
588       &win32_path));
589 }
590 
TEST_F(FileUtilTest,CreateTemporaryFileInDirLongPathTest)591 TEST_F(FileUtilTest, CreateTemporaryFileInDirLongPathTest) {
592   // Test that CreateTemporaryFileInDir() creates a path and returns a long path
593   // if it is available. This test requires that:
594   // - the filesystem at |temp_dir_| supports long filenames.
595   // - the account has FILE_LIST_DIRECTORY permission for all ancestor
596   //   directories of |temp_dir_|.
597   const FilePath::CharType kLongDirName[] = FPL("A long path");
598   const FilePath::CharType kTestSubDirName[] = FPL("test");
599   FilePath long_test_dir = temp_dir_.GetPath().Append(kLongDirName);
600   ASSERT_TRUE(CreateDirectory(long_test_dir));
601 
602   // kLongDirName is not a 8.3 component. So GetShortName() should give us a
603   // different short name.
604   WCHAR path_buffer[MAX_PATH];
605   DWORD path_buffer_length = GetShortPathName(long_test_dir.value().c_str(),
606                                               path_buffer, MAX_PATH);
607   ASSERT_LT(path_buffer_length, DWORD(MAX_PATH));
608   ASSERT_NE(DWORD(0), path_buffer_length);
609   FilePath short_test_dir(path_buffer);
610   ASSERT_STRNE(kLongDirName, short_test_dir.BaseName().value().c_str());
611 
612   FilePath temp_file;
613   ASSERT_TRUE(CreateTemporaryFileInDir(short_test_dir, &temp_file));
614   EXPECT_STREQ(kLongDirName, temp_file.DirName().BaseName().value().c_str());
615   EXPECT_TRUE(PathExists(temp_file));
616 
617   // Create a subdirectory of |long_test_dir| and make |long_test_dir|
618   // unreadable. We should still be able to create a temp file in the
619   // subdirectory, but we won't be able to determine the long path for it. This
620   // mimics the environment that some users run where their user profiles reside
621   // in a location where the don't have full access to the higher level
622   // directories. (Note that this assumption is true for NTFS, but not for some
623   // network file systems. E.g. AFS).
624   FilePath access_test_dir = long_test_dir.Append(kTestSubDirName);
625   ASSERT_TRUE(CreateDirectory(access_test_dir));
626   FilePermissionRestorer long_test_dir_restorer(long_test_dir);
627   ASSERT_TRUE(MakeFileUnreadable(long_test_dir));
628 
629   // Use the short form of the directory to create a temporary filename.
630   ASSERT_TRUE(CreateTemporaryFileInDir(
631       short_test_dir.Append(kTestSubDirName), &temp_file));
632   EXPECT_TRUE(PathExists(temp_file));
633   EXPECT_TRUE(short_test_dir.IsParent(temp_file.DirName()));
634 
635   // Check that the long path can't be determined for |temp_file|.
636   path_buffer_length = GetLongPathName(temp_file.value().c_str(),
637                                        path_buffer, MAX_PATH);
638   EXPECT_EQ(DWORD(0), path_buffer_length);
639 }
640 
641 #endif  // defined(OS_WIN)
642 
643 #if defined(OS_POSIX)
644 
TEST_F(FileUtilTest,CreateAndReadSymlinks)645 TEST_F(FileUtilTest, CreateAndReadSymlinks) {
646   FilePath link_from = temp_dir_.GetPath().Append(FPL("from_file"));
647   FilePath link_to = temp_dir_.GetPath().Append(FPL("to_file"));
648   CreateTextFile(link_to, bogus_content);
649 
650   ASSERT_TRUE(CreateSymbolicLink(link_to, link_from))
651     << "Failed to create file symlink.";
652 
653   // If we created the link properly, we should be able to read the contents
654   // through it.
655   EXPECT_EQ(bogus_content, ReadTextFile(link_from));
656 
657   FilePath result;
658   ASSERT_TRUE(ReadSymbolicLink(link_from, &result));
659   EXPECT_EQ(link_to.value(), result.value());
660 
661   // Link to a directory.
662   link_from = temp_dir_.GetPath().Append(FPL("from_dir"));
663   link_to = temp_dir_.GetPath().Append(FPL("to_dir"));
664   ASSERT_TRUE(CreateDirectory(link_to));
665   ASSERT_TRUE(CreateSymbolicLink(link_to, link_from))
666     << "Failed to create directory symlink.";
667 
668   // Test failures.
669   EXPECT_FALSE(CreateSymbolicLink(link_to, link_to));
670   EXPECT_FALSE(ReadSymbolicLink(link_to, &result));
671   FilePath missing = temp_dir_.GetPath().Append(FPL("missing"));
672   EXPECT_FALSE(ReadSymbolicLink(missing, &result));
673 }
674 
675 // The following test of NormalizeFilePath() require that we create a symlink.
676 // This can not be done on Windows before Vista.  On Vista, creating a symlink
677 // requires privilege "SeCreateSymbolicLinkPrivilege".
678 // TODO(skerner): Investigate the possibility of giving base_unittests the
679 // privileges required to create a symlink.
TEST_F(FileUtilTest,NormalizeFilePathSymlinks)680 TEST_F(FileUtilTest, NormalizeFilePathSymlinks) {
681   // Link one file to another.
682   FilePath link_from = temp_dir_.GetPath().Append(FPL("from_file"));
683   FilePath link_to = temp_dir_.GetPath().Append(FPL("to_file"));
684   CreateTextFile(link_to, bogus_content);
685 
686   ASSERT_TRUE(CreateSymbolicLink(link_to, link_from))
687     << "Failed to create file symlink.";
688 
689   // Check that NormalizeFilePath sees the link.
690   FilePath normalized_path;
691   ASSERT_TRUE(NormalizeFilePath(link_from, &normalized_path));
692   EXPECT_NE(link_from, link_to);
693   EXPECT_EQ(link_to.BaseName().value(), normalized_path.BaseName().value());
694   EXPECT_EQ(link_to.BaseName().value(), normalized_path.BaseName().value());
695 
696   // Link to a directory.
697   link_from = temp_dir_.GetPath().Append(FPL("from_dir"));
698   link_to = temp_dir_.GetPath().Append(FPL("to_dir"));
699   ASSERT_TRUE(CreateDirectory(link_to));
700   ASSERT_TRUE(CreateSymbolicLink(link_to, link_from))
701     << "Failed to create directory symlink.";
702 
703   EXPECT_FALSE(NormalizeFilePath(link_from, &normalized_path))
704     << "Links to directories should return false.";
705 
706   // Test that a loop in the links causes NormalizeFilePath() to return false.
707   link_from = temp_dir_.GetPath().Append(FPL("link_a"));
708   link_to = temp_dir_.GetPath().Append(FPL("link_b"));
709   ASSERT_TRUE(CreateSymbolicLink(link_to, link_from))
710     << "Failed to create loop symlink a.";
711   ASSERT_TRUE(CreateSymbolicLink(link_from, link_to))
712     << "Failed to create loop symlink b.";
713 
714   // Infinite loop!
715   EXPECT_FALSE(NormalizeFilePath(link_from, &normalized_path));
716 }
717 
TEST_F(FileUtilTest,DeleteSymlinkToExistentFile)718 TEST_F(FileUtilTest, DeleteSymlinkToExistentFile) {
719   // Create a file.
720   FilePath file_name = temp_dir_.GetPath().Append(FPL("Test DeleteFile 2.txt"));
721   CreateTextFile(file_name, bogus_content);
722   ASSERT_TRUE(PathExists(file_name));
723 
724   // Create a symlink to the file.
725   FilePath file_link = temp_dir_.GetPath().Append("file_link_2");
726   ASSERT_TRUE(CreateSymbolicLink(file_name, file_link))
727       << "Failed to create symlink.";
728 
729   // Delete the symbolic link.
730   EXPECT_TRUE(DeleteFile(file_link, false));
731 
732   // Make sure original file is not deleted.
733   EXPECT_FALSE(PathExists(file_link));
734   EXPECT_TRUE(PathExists(file_name));
735 }
736 
TEST_F(FileUtilTest,DeleteSymlinkToNonExistentFile)737 TEST_F(FileUtilTest, DeleteSymlinkToNonExistentFile) {
738   // Create a non-existent file path.
739   FilePath non_existent =
740       temp_dir_.GetPath().Append(FPL("Test DeleteFile 3.txt"));
741   EXPECT_FALSE(PathExists(non_existent));
742 
743   // Create a symlink to the non-existent file.
744   FilePath file_link = temp_dir_.GetPath().Append("file_link_3");
745   ASSERT_TRUE(CreateSymbolicLink(non_existent, file_link))
746       << "Failed to create symlink.";
747 
748   // Make sure the symbolic link is exist.
749   EXPECT_TRUE(IsLink(file_link));
750   EXPECT_FALSE(PathExists(file_link));
751 
752   // Delete the symbolic link.
753   EXPECT_TRUE(DeleteFile(file_link, false));
754 
755   // Make sure the symbolic link is deleted.
756   EXPECT_FALSE(IsLink(file_link));
757 }
758 
TEST_F(FileUtilTest,CopyFileFollowsSymlinks)759 TEST_F(FileUtilTest, CopyFileFollowsSymlinks) {
760   FilePath link_from = temp_dir_.GetPath().Append(FPL("from_file"));
761   FilePath link_to = temp_dir_.GetPath().Append(FPL("to_file"));
762   CreateTextFile(link_to, bogus_content);
763 
764   ASSERT_TRUE(CreateSymbolicLink(link_to, link_from));
765 
766   // If we created the link properly, we should be able to read the contents
767   // through it.
768   EXPECT_EQ(bogus_content, ReadTextFile(link_from));
769 
770   FilePath result;
771   ASSERT_TRUE(ReadSymbolicLink(link_from, &result));
772   EXPECT_EQ(link_to.value(), result.value());
773 
774   // Create another file and copy it to |link_from|.
775   FilePath src_file = temp_dir_.GetPath().Append(FPL("src.txt"));
776   const std::wstring file_contents(L"Gooooooooooooooooooooogle");
777   CreateTextFile(src_file, file_contents);
778   ASSERT_TRUE(CopyFile(src_file, link_from));
779 
780   // Make sure |link_from| is still a symlink, and |link_to| has been written to
781   // by CopyFile().
782   EXPECT_TRUE(IsLink(link_from));
783   EXPECT_EQ(file_contents, ReadTextFile(link_from));
784   EXPECT_EQ(file_contents, ReadTextFile(link_to));
785 }
786 
TEST_F(FileUtilTest,ChangeFilePermissionsAndRead)787 TEST_F(FileUtilTest, ChangeFilePermissionsAndRead) {
788   // Create a file path.
789   FilePath file_name =
790       temp_dir_.GetPath().Append(FPL("Test Readable File.txt"));
791   EXPECT_FALSE(PathExists(file_name));
792 
793   static constexpr char kData[] = "hello";
794   static constexpr int kDataSize = sizeof(kData) - 1;
795   char buffer[kDataSize];
796 
797   // Write file.
798   EXPECT_EQ(kDataSize, WriteFile(file_name, kData, kDataSize));
799   EXPECT_TRUE(PathExists(file_name));
800 
801   // Make sure the file is readable.
802   int32_t mode = 0;
803   EXPECT_TRUE(GetPosixFilePermissions(file_name, &mode));
804   EXPECT_TRUE(mode & FILE_PERMISSION_READ_BY_USER);
805 
806   // Get rid of the read permission.
807   EXPECT_TRUE(SetPosixFilePermissions(file_name, 0u));
808   EXPECT_TRUE(GetPosixFilePermissions(file_name, &mode));
809   EXPECT_FALSE(mode & FILE_PERMISSION_READ_BY_USER);
810   // Make sure the file can't be read.
811   EXPECT_EQ(-1, ReadFile(file_name, buffer, kDataSize));
812 
813   // Give the read permission.
814   EXPECT_TRUE(SetPosixFilePermissions(file_name, FILE_PERMISSION_READ_BY_USER));
815   EXPECT_TRUE(GetPosixFilePermissions(file_name, &mode));
816   EXPECT_TRUE(mode & FILE_PERMISSION_READ_BY_USER);
817   // Make sure the file can be read.
818   EXPECT_EQ(kDataSize, ReadFile(file_name, buffer, kDataSize));
819 
820   // Delete the file.
821   EXPECT_TRUE(DeleteFile(file_name, false));
822   EXPECT_FALSE(PathExists(file_name));
823 }
824 
TEST_F(FileUtilTest,ChangeFilePermissionsAndWrite)825 TEST_F(FileUtilTest, ChangeFilePermissionsAndWrite) {
826   // Create a file path.
827   FilePath file_name =
828       temp_dir_.GetPath().Append(FPL("Test Readable File.txt"));
829   EXPECT_FALSE(PathExists(file_name));
830 
831   const std::string kData("hello");
832 
833   // Write file.
834   EXPECT_EQ(static_cast<int>(kData.length()),
835             WriteFile(file_name, kData.data(), kData.length()));
836   EXPECT_TRUE(PathExists(file_name));
837 
838   // Make sure the file is writable.
839   int mode = 0;
840   EXPECT_TRUE(GetPosixFilePermissions(file_name, &mode));
841   EXPECT_TRUE(mode & FILE_PERMISSION_WRITE_BY_USER);
842   EXPECT_TRUE(PathIsWritable(file_name));
843 
844   // Get rid of the write permission.
845   EXPECT_TRUE(SetPosixFilePermissions(file_name, 0u));
846   EXPECT_TRUE(GetPosixFilePermissions(file_name, &mode));
847   EXPECT_FALSE(mode & FILE_PERMISSION_WRITE_BY_USER);
848   // Make sure the file can't be write.
849   EXPECT_EQ(-1, WriteFile(file_name, kData.data(), kData.length()));
850   EXPECT_FALSE(PathIsWritable(file_name));
851 
852   // Give read permission.
853   EXPECT_TRUE(SetPosixFilePermissions(file_name,
854                                       FILE_PERMISSION_WRITE_BY_USER));
855   EXPECT_TRUE(GetPosixFilePermissions(file_name, &mode));
856   EXPECT_TRUE(mode & FILE_PERMISSION_WRITE_BY_USER);
857   // Make sure the file can be write.
858   EXPECT_EQ(static_cast<int>(kData.length()),
859             WriteFile(file_name, kData.data(), kData.length()));
860   EXPECT_TRUE(PathIsWritable(file_name));
861 
862   // Delete the file.
863   EXPECT_TRUE(DeleteFile(file_name, false));
864   EXPECT_FALSE(PathExists(file_name));
865 }
866 
TEST_F(FileUtilTest,ChangeDirectoryPermissionsAndEnumerate)867 TEST_F(FileUtilTest, ChangeDirectoryPermissionsAndEnumerate) {
868   // Create a directory path.
869   FilePath subdir_path = temp_dir_.GetPath().Append(FPL("PermissionTest1"));
870   CreateDirectory(subdir_path);
871   ASSERT_TRUE(PathExists(subdir_path));
872 
873   // Create a dummy file to enumerate.
874   FilePath file_name = subdir_path.Append(FPL("Test Readable File.txt"));
875   EXPECT_FALSE(PathExists(file_name));
876   const std::string kData("hello");
877   EXPECT_EQ(static_cast<int>(kData.length()),
878             WriteFile(file_name, kData.data(), kData.length()));
879   EXPECT_TRUE(PathExists(file_name));
880 
881   // Make sure the directory has the all permissions.
882   int mode = 0;
883   EXPECT_TRUE(GetPosixFilePermissions(subdir_path, &mode));
884   EXPECT_EQ(FILE_PERMISSION_USER_MASK, mode & FILE_PERMISSION_USER_MASK);
885 
886   // Get rid of the permissions from the directory.
887   EXPECT_TRUE(SetPosixFilePermissions(subdir_path, 0u));
888   EXPECT_TRUE(GetPosixFilePermissions(subdir_path, &mode));
889   EXPECT_FALSE(mode & FILE_PERMISSION_USER_MASK);
890 
891   // Make sure the file in the directory can't be enumerated.
892   FileEnumerator f1(subdir_path, true, FileEnumerator::FILES);
893   EXPECT_TRUE(PathExists(subdir_path));
894   FindResultCollector c1(&f1);
895   EXPECT_EQ(0, c1.size());
896   EXPECT_FALSE(GetPosixFilePermissions(file_name, &mode));
897 
898   // Give the permissions to the directory.
899   EXPECT_TRUE(SetPosixFilePermissions(subdir_path, FILE_PERMISSION_USER_MASK));
900   EXPECT_TRUE(GetPosixFilePermissions(subdir_path, &mode));
901   EXPECT_EQ(FILE_PERMISSION_USER_MASK, mode & FILE_PERMISSION_USER_MASK);
902 
903   // Make sure the file in the directory can be enumerated.
904   FileEnumerator f2(subdir_path, true, FileEnumerator::FILES);
905   FindResultCollector c2(&f2);
906   EXPECT_TRUE(c2.HasFile(file_name));
907   EXPECT_EQ(1, c2.size());
908 
909   // Delete the file.
910   EXPECT_TRUE(DeleteFile(subdir_path, true));
911   EXPECT_FALSE(PathExists(subdir_path));
912 }
913 
TEST_F(FileUtilTest,ExecutableExistsInPath)914 TEST_F(FileUtilTest, ExecutableExistsInPath) {
915   // Create two directories that we will put in our PATH
916   const FilePath::CharType kDir1[] = FPL("dir1");
917   const FilePath::CharType kDir2[] = FPL("dir2");
918 
919   FilePath dir1 = temp_dir_.GetPath().Append(kDir1);
920   FilePath dir2 = temp_dir_.GetPath().Append(kDir2);
921   ASSERT_TRUE(CreateDirectory(dir1));
922   ASSERT_TRUE(CreateDirectory(dir2));
923 
924   test::ScopedEnvironmentVariableOverride scoped_env(
925       "PATH", dir1.value() + ":" + dir2.value());
926   ASSERT_TRUE(scoped_env.IsOverridden());
927 
928   const FilePath::CharType kRegularFileName[] = FPL("regular_file");
929   const FilePath::CharType kExeFileName[] = FPL("exe");
930   const FilePath::CharType kDneFileName[] = FPL("does_not_exist");
931 
932   const FilePath kExePath = dir1.Append(kExeFileName);
933   const FilePath kRegularFilePath = dir2.Append(kRegularFileName);
934 
935   // Write file.
936   const std::string kData("hello");
937   ASSERT_EQ(static_cast<int>(kData.length()),
938             WriteFile(kExePath, kData.data(), kData.length()));
939   ASSERT_TRUE(PathExists(kExePath));
940   ASSERT_EQ(static_cast<int>(kData.length()),
941             WriteFile(kRegularFilePath, kData.data(), kData.length()));
942   ASSERT_TRUE(PathExists(kRegularFilePath));
943 
944   ASSERT_TRUE(SetPosixFilePermissions(dir1.Append(kExeFileName),
945                                       FILE_PERMISSION_EXECUTE_BY_USER));
946 
947   EXPECT_TRUE(ExecutableExistsInPath(scoped_env.GetEnv(), kExeFileName));
948   EXPECT_FALSE(ExecutableExistsInPath(scoped_env.GetEnv(), kRegularFileName));
949   EXPECT_FALSE(ExecutableExistsInPath(scoped_env.GetEnv(), kDneFileName));
950 }
951 
TEST_F(FileUtilTest,CopyDirectoryPermissions)952 TEST_F(FileUtilTest, CopyDirectoryPermissions) {
953   // Create a directory.
954   FilePath dir_name_from =
955       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
956   CreateDirectory(dir_name_from);
957   ASSERT_TRUE(PathExists(dir_name_from));
958 
959   // Create some regular files under the directory with various permissions.
960   FilePath file_name_from =
961       dir_name_from.Append(FILE_PATH_LITERAL("Reggy-1.txt"));
962   CreateTextFile(file_name_from, L"Mordecai");
963   ASSERT_TRUE(PathExists(file_name_from));
964   ASSERT_TRUE(SetPosixFilePermissions(file_name_from, 0755));
965 
966   FilePath file2_name_from =
967       dir_name_from.Append(FILE_PATH_LITERAL("Reggy-2.txt"));
968   CreateTextFile(file2_name_from, L"Rigby");
969   ASSERT_TRUE(PathExists(file2_name_from));
970   ASSERT_TRUE(SetPosixFilePermissions(file2_name_from, 0777));
971 
972   FilePath file3_name_from =
973       dir_name_from.Append(FILE_PATH_LITERAL("Reggy-3.txt"));
974   CreateTextFile(file3_name_from, L"Benson");
975   ASSERT_TRUE(PathExists(file3_name_from));
976   ASSERT_TRUE(SetPosixFilePermissions(file3_name_from, 0400));
977 
978   // Copy the directory recursively.
979   FilePath dir_name_to =
980       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_To_Subdir"));
981   FilePath file_name_to =
982       dir_name_to.Append(FILE_PATH_LITERAL("Reggy-1.txt"));
983   FilePath file2_name_to =
984       dir_name_to.Append(FILE_PATH_LITERAL("Reggy-2.txt"));
985   FilePath file3_name_to =
986       dir_name_to.Append(FILE_PATH_LITERAL("Reggy-3.txt"));
987 
988   ASSERT_FALSE(PathExists(dir_name_to));
989 
990   EXPECT_TRUE(CopyDirectory(dir_name_from, dir_name_to, true));
991   ASSERT_TRUE(PathExists(file_name_to));
992   ASSERT_TRUE(PathExists(file2_name_to));
993   ASSERT_TRUE(PathExists(file3_name_to));
994 
995   int mode = 0;
996   int expected_mode;
997   ASSERT_TRUE(GetPosixFilePermissions(file_name_to, &mode));
998 #if defined(OS_MACOSX)
999   expected_mode = 0755;
1000 #elif defined(OS_CHROMEOS)
1001   expected_mode = 0644;
1002 #else
1003   expected_mode = 0600;
1004 #endif
1005   EXPECT_EQ(expected_mode, mode);
1006 
1007   ASSERT_TRUE(GetPosixFilePermissions(file2_name_to, &mode));
1008 #if defined(OS_MACOSX)
1009   expected_mode = 0755;
1010 #elif defined(OS_CHROMEOS)
1011   expected_mode = 0644;
1012 #else
1013   expected_mode = 0600;
1014 #endif
1015   EXPECT_EQ(expected_mode, mode);
1016 
1017   ASSERT_TRUE(GetPosixFilePermissions(file3_name_to, &mode));
1018 #if defined(OS_MACOSX)
1019   expected_mode = 0600;
1020 #elif defined(OS_CHROMEOS)
1021   expected_mode = 0644;
1022 #else
1023   expected_mode = 0600;
1024 #endif
1025   EXPECT_EQ(expected_mode, mode);
1026 }
1027 
TEST_F(FileUtilTest,CopyDirectoryPermissionsOverExistingFile)1028 TEST_F(FileUtilTest, CopyDirectoryPermissionsOverExistingFile) {
1029   // Create a directory.
1030   FilePath dir_name_from =
1031       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
1032   CreateDirectory(dir_name_from);
1033   ASSERT_TRUE(PathExists(dir_name_from));
1034 
1035   // Create a file under the directory.
1036   FilePath file_name_from =
1037       dir_name_from.Append(FILE_PATH_LITERAL("Reggy-1.txt"));
1038   CreateTextFile(file_name_from, L"Mordecai");
1039   ASSERT_TRUE(PathExists(file_name_from));
1040   ASSERT_TRUE(SetPosixFilePermissions(file_name_from, 0644));
1041 
1042   // Create a directory.
1043   FilePath dir_name_to =
1044       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_To_Subdir"));
1045   CreateDirectory(dir_name_to);
1046   ASSERT_TRUE(PathExists(dir_name_to));
1047 
1048   // Create a file under the directory with wider permissions.
1049   FilePath file_name_to =
1050       dir_name_to.Append(FILE_PATH_LITERAL("Reggy-1.txt"));
1051   CreateTextFile(file_name_to, L"Rigby");
1052   ASSERT_TRUE(PathExists(file_name_to));
1053   ASSERT_TRUE(SetPosixFilePermissions(file_name_to, 0777));
1054 
1055   // Ensure that when we copy the directory, the file contents are copied
1056   // but the permissions on the destination are left alone.
1057   EXPECT_TRUE(CopyDirectory(dir_name_from, dir_name_to, false));
1058   ASSERT_TRUE(PathExists(file_name_to));
1059   ASSERT_EQ(L"Mordecai", ReadTextFile(file_name_to));
1060 
1061   int mode = 0;
1062   ASSERT_TRUE(GetPosixFilePermissions(file_name_to, &mode));
1063   EXPECT_EQ(0777, mode);
1064 }
1065 
TEST_F(FileUtilTest,CopyDirectoryExclDoesNotOverwrite)1066 TEST_F(FileUtilTest, CopyDirectoryExclDoesNotOverwrite) {
1067   // Create source directory.
1068   FilePath dir_name_from =
1069       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
1070   CreateDirectory(dir_name_from);
1071   ASSERT_TRUE(PathExists(dir_name_from));
1072 
1073   // Create a file under the directory.
1074   FilePath file_name_from =
1075       dir_name_from.Append(FILE_PATH_LITERAL("Reggy-1.txt"));
1076   CreateTextFile(file_name_from, L"Mordecai");
1077   ASSERT_TRUE(PathExists(file_name_from));
1078 
1079   // Create destination directory.
1080   FilePath dir_name_to =
1081       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_To_Subdir"));
1082   CreateDirectory(dir_name_to);
1083   ASSERT_TRUE(PathExists(dir_name_to));
1084 
1085   // Create a file under the directory with the same name.
1086   FilePath file_name_to = dir_name_to.Append(FILE_PATH_LITERAL("Reggy-1.txt"));
1087   CreateTextFile(file_name_to, L"Rigby");
1088   ASSERT_TRUE(PathExists(file_name_to));
1089 
1090   // Ensure that copying failed and the file was not overwritten.
1091   EXPECT_FALSE(CopyDirectoryExcl(dir_name_from, dir_name_to, false));
1092   ASSERT_TRUE(PathExists(file_name_to));
1093   ASSERT_EQ(L"Rigby", ReadTextFile(file_name_to));
1094 }
1095 
TEST_F(FileUtilTest,CopyDirectoryExclDirectoryOverExistingFile)1096 TEST_F(FileUtilTest, CopyDirectoryExclDirectoryOverExistingFile) {
1097   // Create source directory.
1098   FilePath dir_name_from =
1099       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
1100   CreateDirectory(dir_name_from);
1101   ASSERT_TRUE(PathExists(dir_name_from));
1102 
1103   // Create a subdirectory.
1104   FilePath subdir_name_from = dir_name_from.Append(FILE_PATH_LITERAL("Subsub"));
1105   CreateDirectory(subdir_name_from);
1106   ASSERT_TRUE(PathExists(subdir_name_from));
1107 
1108   // Create destination directory.
1109   FilePath dir_name_to =
1110       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_To_Subdir"));
1111   CreateDirectory(dir_name_to);
1112   ASSERT_TRUE(PathExists(dir_name_to));
1113 
1114   // Create a regular file under the directory with the same name.
1115   FilePath file_name_to = dir_name_to.Append(FILE_PATH_LITERAL("Subsub"));
1116   CreateTextFile(file_name_to, L"Rigby");
1117   ASSERT_TRUE(PathExists(file_name_to));
1118 
1119   // Ensure that copying failed and the file was not overwritten.
1120   EXPECT_FALSE(CopyDirectoryExcl(dir_name_from, dir_name_to, false));
1121   ASSERT_TRUE(PathExists(file_name_to));
1122   ASSERT_EQ(L"Rigby", ReadTextFile(file_name_to));
1123 }
1124 
TEST_F(FileUtilTest,CopyDirectoryExclDirectoryOverExistingDirectory)1125 TEST_F(FileUtilTest, CopyDirectoryExclDirectoryOverExistingDirectory) {
1126   // Create source directory.
1127   FilePath dir_name_from =
1128       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
1129   CreateDirectory(dir_name_from);
1130   ASSERT_TRUE(PathExists(dir_name_from));
1131 
1132   // Create a subdirectory.
1133   FilePath subdir_name_from = dir_name_from.Append(FILE_PATH_LITERAL("Subsub"));
1134   CreateDirectory(subdir_name_from);
1135   ASSERT_TRUE(PathExists(subdir_name_from));
1136 
1137   // Create destination directory.
1138   FilePath dir_name_to =
1139       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_To_Subdir"));
1140   CreateDirectory(dir_name_to);
1141   ASSERT_TRUE(PathExists(dir_name_to));
1142 
1143   // Create a subdirectory under the directory with the same name.
1144   FilePath subdir_name_to = dir_name_to.Append(FILE_PATH_LITERAL("Subsub"));
1145   CreateDirectory(subdir_name_to);
1146   ASSERT_TRUE(PathExists(subdir_name_to));
1147 
1148   // Ensure that copying failed and the file was not overwritten.
1149   EXPECT_FALSE(CopyDirectoryExcl(dir_name_from, dir_name_to, false));
1150 }
1151 
TEST_F(FileUtilTest,CopyFileExecutablePermission)1152 TEST_F(FileUtilTest, CopyFileExecutablePermission) {
1153   FilePath src = temp_dir_.GetPath().Append(FPL("src.txt"));
1154   const std::wstring file_contents(L"Gooooooooooooooooooooogle");
1155   CreateTextFile(src, file_contents);
1156 
1157   ASSERT_TRUE(SetPosixFilePermissions(src, 0755));
1158   int mode = 0;
1159   ASSERT_TRUE(GetPosixFilePermissions(src, &mode));
1160   EXPECT_EQ(0755, mode);
1161 
1162   FilePath dst = temp_dir_.GetPath().Append(FPL("dst.txt"));
1163   ASSERT_TRUE(CopyFile(src, dst));
1164   EXPECT_EQ(file_contents, ReadTextFile(dst));
1165 
1166   ASSERT_TRUE(GetPosixFilePermissions(dst, &mode));
1167   int expected_mode;
1168 #if defined(OS_MACOSX)
1169   expected_mode = 0755;
1170 #elif defined(OS_CHROMEOS)
1171   expected_mode = 0644;
1172 #else
1173   expected_mode = 0600;
1174 #endif
1175   EXPECT_EQ(expected_mode, mode);
1176   ASSERT_TRUE(DeleteFile(dst, false));
1177 
1178   ASSERT_TRUE(SetPosixFilePermissions(src, 0777));
1179   ASSERT_TRUE(GetPosixFilePermissions(src, &mode));
1180   EXPECT_EQ(0777, mode);
1181 
1182   ASSERT_TRUE(CopyFile(src, dst));
1183   EXPECT_EQ(file_contents, ReadTextFile(dst));
1184 
1185   ASSERT_TRUE(GetPosixFilePermissions(dst, &mode));
1186 #if defined(OS_MACOSX)
1187   expected_mode = 0755;
1188 #elif defined(OS_CHROMEOS)
1189   expected_mode = 0644;
1190 #else
1191   expected_mode = 0600;
1192 #endif
1193   EXPECT_EQ(expected_mode, mode);
1194   ASSERT_TRUE(DeleteFile(dst, false));
1195 
1196   ASSERT_TRUE(SetPosixFilePermissions(src, 0400));
1197   ASSERT_TRUE(GetPosixFilePermissions(src, &mode));
1198   EXPECT_EQ(0400, mode);
1199 
1200   ASSERT_TRUE(CopyFile(src, dst));
1201   EXPECT_EQ(file_contents, ReadTextFile(dst));
1202 
1203   ASSERT_TRUE(GetPosixFilePermissions(dst, &mode));
1204 #if defined(OS_MACOSX)
1205   expected_mode = 0600;
1206 #elif defined(OS_CHROMEOS)
1207   expected_mode = 0644;
1208 #else
1209   expected_mode = 0600;
1210 #endif
1211   EXPECT_EQ(expected_mode, mode);
1212 
1213   // This time, do not delete |dst|. Instead set its permissions to 0777.
1214   ASSERT_TRUE(SetPosixFilePermissions(dst, 0777));
1215   ASSERT_TRUE(GetPosixFilePermissions(dst, &mode));
1216   EXPECT_EQ(0777, mode);
1217 
1218   // Overwrite it and check the permissions again.
1219   ASSERT_TRUE(CopyFile(src, dst));
1220   EXPECT_EQ(file_contents, ReadTextFile(dst));
1221   ASSERT_TRUE(GetPosixFilePermissions(dst, &mode));
1222   EXPECT_EQ(0777, mode);
1223 }
1224 
1225 #endif  // defined(OS_POSIX)
1226 
1227 #if !defined(OS_FUCHSIA)
1228 
TEST_F(FileUtilTest,CopyFileACL)1229 TEST_F(FileUtilTest, CopyFileACL) {
1230   // While FileUtilTest.CopyFile asserts the content is correctly copied over,
1231   // this test case asserts the access control bits are meeting expectations in
1232   // CopyFile().
1233   FilePath src = temp_dir_.GetPath().Append(FILE_PATH_LITERAL("src.txt"));
1234   const std::wstring file_contents(L"Gooooooooooooooooooooogle");
1235   CreateTextFile(src, file_contents);
1236 
1237   // Set the source file to read-only.
1238   ASSERT_FALSE(IsReadOnly(src));
1239   SetReadOnly(src, true);
1240   ASSERT_TRUE(IsReadOnly(src));
1241 
1242   // Copy the file.
1243   FilePath dst = temp_dir_.GetPath().Append(FILE_PATH_LITERAL("dst.txt"));
1244   ASSERT_TRUE(CopyFile(src, dst));
1245   EXPECT_EQ(file_contents, ReadTextFile(dst));
1246 
1247   ASSERT_FALSE(IsReadOnly(dst));
1248 }
1249 
TEST_F(FileUtilTest,CopyDirectoryACL)1250 TEST_F(FileUtilTest, CopyDirectoryACL) {
1251   // Create source directories.
1252   FilePath src = temp_dir_.GetPath().Append(FILE_PATH_LITERAL("src"));
1253   FilePath src_subdir = src.Append(FILE_PATH_LITERAL("subdir"));
1254   CreateDirectory(src_subdir);
1255   ASSERT_TRUE(PathExists(src_subdir));
1256 
1257   // Create a file under the directory.
1258   FilePath src_file = src.Append(FILE_PATH_LITERAL("src.txt"));
1259   CreateTextFile(src_file, L"Gooooooooooooooooooooogle");
1260   SetReadOnly(src_file, true);
1261   ASSERT_TRUE(IsReadOnly(src_file));
1262 
1263   // Make directory read-only.
1264   SetReadOnly(src_subdir, true);
1265   ASSERT_TRUE(IsReadOnly(src_subdir));
1266 
1267   // Copy the directory recursively.
1268   FilePath dst = temp_dir_.GetPath().Append(FILE_PATH_LITERAL("dst"));
1269   FilePath dst_file = dst.Append(FILE_PATH_LITERAL("src.txt"));
1270   EXPECT_TRUE(CopyDirectory(src, dst, true));
1271 
1272   FilePath dst_subdir = dst.Append(FILE_PATH_LITERAL("subdir"));
1273   ASSERT_FALSE(IsReadOnly(dst_subdir));
1274   ASSERT_FALSE(IsReadOnly(dst_file));
1275 
1276   // Give write permissions to allow deletion.
1277   SetReadOnly(src_subdir, false);
1278   ASSERT_FALSE(IsReadOnly(src_subdir));
1279 }
1280 
1281 #endif  // !defined(OS_FUCHSIA)
1282 
TEST_F(FileUtilTest,DeleteNonExistent)1283 TEST_F(FileUtilTest, DeleteNonExistent) {
1284   FilePath non_existent =
1285       temp_dir_.GetPath().AppendASCII("bogus_file_dne.foobar");
1286   ASSERT_FALSE(PathExists(non_existent));
1287 
1288   EXPECT_TRUE(DeleteFile(non_existent, false));
1289   ASSERT_FALSE(PathExists(non_existent));
1290   EXPECT_TRUE(DeleteFile(non_existent, true));
1291   ASSERT_FALSE(PathExists(non_existent));
1292 }
1293 
TEST_F(FileUtilTest,DeleteNonExistentWithNonExistentParent)1294 TEST_F(FileUtilTest, DeleteNonExistentWithNonExistentParent) {
1295   FilePath non_existent = temp_dir_.GetPath().AppendASCII("bogus_topdir");
1296   non_existent = non_existent.AppendASCII("bogus_subdir");
1297   ASSERT_FALSE(PathExists(non_existent));
1298 
1299   EXPECT_TRUE(DeleteFile(non_existent, false));
1300   ASSERT_FALSE(PathExists(non_existent));
1301   EXPECT_TRUE(DeleteFile(non_existent, true));
1302   ASSERT_FALSE(PathExists(non_existent));
1303 }
1304 
TEST_F(FileUtilTest,DeleteFile)1305 TEST_F(FileUtilTest, DeleteFile) {
1306   // Create a file
1307   FilePath file_name = temp_dir_.GetPath().Append(FPL("Test DeleteFile 1.txt"));
1308   CreateTextFile(file_name, bogus_content);
1309   ASSERT_TRUE(PathExists(file_name));
1310 
1311   // Make sure it's deleted
1312   EXPECT_TRUE(DeleteFile(file_name, false));
1313   EXPECT_FALSE(PathExists(file_name));
1314 
1315   // Test recursive case, create a new file
1316   file_name = temp_dir_.GetPath().Append(FPL("Test DeleteFile 2.txt"));
1317   CreateTextFile(file_name, bogus_content);
1318   ASSERT_TRUE(PathExists(file_name));
1319 
1320   // Make sure it's deleted
1321   EXPECT_TRUE(DeleteFile(file_name, true));
1322   EXPECT_FALSE(PathExists(file_name));
1323 }
1324 
1325 #if defined(OS_WIN)
1326 // Tests that the Delete function works for wild cards, especially
1327 // with the recursion flag.  Also coincidentally tests PathExists.
1328 // TODO(erikkay): see if anyone's actually using this feature of the API
TEST_F(FileUtilTest,DeleteWildCard)1329 TEST_F(FileUtilTest, DeleteWildCard) {
1330   // Create a file and a directory
1331   FilePath file_name =
1332       temp_dir_.GetPath().Append(FPL("Test DeleteWildCard.txt"));
1333   CreateTextFile(file_name, bogus_content);
1334   ASSERT_TRUE(PathExists(file_name));
1335 
1336   FilePath subdir_path = temp_dir_.GetPath().Append(FPL("DeleteWildCardDir"));
1337   CreateDirectory(subdir_path);
1338   ASSERT_TRUE(PathExists(subdir_path));
1339 
1340   // Create the wildcard path
1341   FilePath directory_contents = temp_dir_.GetPath();
1342   directory_contents = directory_contents.Append(FPL("*"));
1343 
1344   // Delete non-recursively and check that only the file is deleted
1345   EXPECT_TRUE(DeleteFile(directory_contents, false));
1346   EXPECT_FALSE(PathExists(file_name));
1347   EXPECT_TRUE(PathExists(subdir_path));
1348 
1349   // Delete recursively and make sure all contents are deleted
1350   EXPECT_TRUE(DeleteFile(directory_contents, true));
1351   EXPECT_FALSE(PathExists(file_name));
1352   EXPECT_FALSE(PathExists(subdir_path));
1353 }
1354 
1355 // TODO(erikkay): see if anyone's actually using this feature of the API
TEST_F(FileUtilTest,DeleteNonExistantWildCard)1356 TEST_F(FileUtilTest, DeleteNonExistantWildCard) {
1357   // Create a file and a directory
1358   FilePath subdir_path =
1359       temp_dir_.GetPath().Append(FPL("DeleteNonExistantWildCard"));
1360   CreateDirectory(subdir_path);
1361   ASSERT_TRUE(PathExists(subdir_path));
1362 
1363   // Create the wildcard path
1364   FilePath directory_contents = subdir_path;
1365   directory_contents = directory_contents.Append(FPL("*"));
1366 
1367   // Delete non-recursively and check nothing got deleted
1368   EXPECT_TRUE(DeleteFile(directory_contents, false));
1369   EXPECT_TRUE(PathExists(subdir_path));
1370 
1371   // Delete recursively and check nothing got deleted
1372   EXPECT_TRUE(DeleteFile(directory_contents, true));
1373   EXPECT_TRUE(PathExists(subdir_path));
1374 }
1375 #endif
1376 
1377 // Tests non-recursive Delete() for a directory.
TEST_F(FileUtilTest,DeleteDirNonRecursive)1378 TEST_F(FileUtilTest, DeleteDirNonRecursive) {
1379   // Create a subdirectory and put a file and two directories inside.
1380   FilePath test_subdir =
1381       temp_dir_.GetPath().Append(FPL("DeleteDirNonRecursive"));
1382   CreateDirectory(test_subdir);
1383   ASSERT_TRUE(PathExists(test_subdir));
1384 
1385   FilePath file_name = test_subdir.Append(FPL("Test DeleteDir.txt"));
1386   CreateTextFile(file_name, bogus_content);
1387   ASSERT_TRUE(PathExists(file_name));
1388 
1389   FilePath subdir_path1 = test_subdir.Append(FPL("TestSubDir1"));
1390   CreateDirectory(subdir_path1);
1391   ASSERT_TRUE(PathExists(subdir_path1));
1392 
1393   FilePath subdir_path2 = test_subdir.Append(FPL("TestSubDir2"));
1394   CreateDirectory(subdir_path2);
1395   ASSERT_TRUE(PathExists(subdir_path2));
1396 
1397   // Delete non-recursively and check that the empty dir got deleted
1398   EXPECT_TRUE(DeleteFile(subdir_path2, false));
1399   EXPECT_FALSE(PathExists(subdir_path2));
1400 
1401   // Delete non-recursively and check that nothing got deleted
1402   EXPECT_FALSE(DeleteFile(test_subdir, false));
1403   EXPECT_TRUE(PathExists(test_subdir));
1404   EXPECT_TRUE(PathExists(file_name));
1405   EXPECT_TRUE(PathExists(subdir_path1));
1406 }
1407 
1408 // Tests recursive Delete() for a directory.
TEST_F(FileUtilTest,DeleteDirRecursive)1409 TEST_F(FileUtilTest, DeleteDirRecursive) {
1410   // Create a subdirectory and put a file and two directories inside.
1411   FilePath test_subdir = temp_dir_.GetPath().Append(FPL("DeleteDirRecursive"));
1412   CreateDirectory(test_subdir);
1413   ASSERT_TRUE(PathExists(test_subdir));
1414 
1415   FilePath file_name = test_subdir.Append(FPL("Test DeleteDirRecursive.txt"));
1416   CreateTextFile(file_name, bogus_content);
1417   ASSERT_TRUE(PathExists(file_name));
1418 
1419   FilePath subdir_path1 = test_subdir.Append(FPL("TestSubDir1"));
1420   CreateDirectory(subdir_path1);
1421   ASSERT_TRUE(PathExists(subdir_path1));
1422 
1423   FilePath subdir_path2 = test_subdir.Append(FPL("TestSubDir2"));
1424   CreateDirectory(subdir_path2);
1425   ASSERT_TRUE(PathExists(subdir_path2));
1426 
1427   // Delete recursively and check that the empty dir got deleted
1428   EXPECT_TRUE(DeleteFile(subdir_path2, true));
1429   EXPECT_FALSE(PathExists(subdir_path2));
1430 
1431   // Delete recursively and check that everything got deleted
1432   EXPECT_TRUE(DeleteFile(test_subdir, true));
1433   EXPECT_FALSE(PathExists(file_name));
1434   EXPECT_FALSE(PathExists(subdir_path1));
1435   EXPECT_FALSE(PathExists(test_subdir));
1436 }
1437 
1438 // Tests recursive Delete() for a directory.
TEST_F(FileUtilTest,DeleteDirRecursiveWithOpenFile)1439 TEST_F(FileUtilTest, DeleteDirRecursiveWithOpenFile) {
1440   // Create a subdirectory and put a file and two directories inside.
1441   FilePath test_subdir = temp_dir_.GetPath().Append(FPL("DeleteWithOpenFile"));
1442   CreateDirectory(test_subdir);
1443   ASSERT_TRUE(PathExists(test_subdir));
1444 
1445   FilePath file_name1 = test_subdir.Append(FPL("Undeletebable File1.txt"));
1446   File file1(file_name1,
1447              File::FLAG_CREATE | File::FLAG_READ | File::FLAG_WRITE);
1448   ASSERT_TRUE(PathExists(file_name1));
1449 
1450   FilePath file_name2 = test_subdir.Append(FPL("Deleteable File2.txt"));
1451   CreateTextFile(file_name2, bogus_content);
1452   ASSERT_TRUE(PathExists(file_name2));
1453 
1454   FilePath file_name3 = test_subdir.Append(FPL("Undeletebable File3.txt"));
1455   File file3(file_name3,
1456              File::FLAG_CREATE | File::FLAG_READ | File::FLAG_WRITE);
1457   ASSERT_TRUE(PathExists(file_name3));
1458 
1459 #if defined(OS_LINUX)
1460   // On Windows, holding the file open in sufficient to make it un-deletable.
1461   // The POSIX code is verifiable on Linux by creating an "immutable" file but
1462   // this is best-effort because it's not supported by all file systems. Both
1463   // files will have the same flags so no need to get them individually.
1464   int flags;
1465   bool file_attrs_supported =
1466       ioctl(file1.GetPlatformFile(), FS_IOC_GETFLAGS, &flags) == 0;
1467   // Some filesystems (e.g. tmpfs) don't support file attributes.
1468   if (file_attrs_supported) {
1469     flags |= FS_IMMUTABLE_FL;
1470     ioctl(file1.GetPlatformFile(), FS_IOC_SETFLAGS, &flags);
1471     ioctl(file3.GetPlatformFile(), FS_IOC_SETFLAGS, &flags);
1472   }
1473 #endif
1474 
1475   // Delete recursively and check that at least the second file got deleted.
1476   // This ensures that un-deletable files don't impact those that can be.
1477   DeleteFile(test_subdir, true);
1478   EXPECT_FALSE(PathExists(file_name2));
1479 
1480 #if defined(OS_LINUX)
1481   // Make sure that the test can clean up after itself.
1482   if (file_attrs_supported) {
1483     flags &= ~FS_IMMUTABLE_FL;
1484     ioctl(file1.GetPlatformFile(), FS_IOC_SETFLAGS, &flags);
1485     ioctl(file3.GetPlatformFile(), FS_IOC_SETFLAGS, &flags);
1486   }
1487 #endif
1488 }
1489 
TEST_F(FileUtilTest,MoveFileNew)1490 TEST_F(FileUtilTest, MoveFileNew) {
1491   // Create a file
1492   FilePath file_name_from =
1493       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Move_Test_File.txt"));
1494   CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
1495   ASSERT_TRUE(PathExists(file_name_from));
1496 
1497   // The destination.
1498   FilePath file_name_to = temp_dir_.GetPath().Append(
1499       FILE_PATH_LITERAL("Move_Test_File_Destination.txt"));
1500   ASSERT_FALSE(PathExists(file_name_to));
1501 
1502   EXPECT_TRUE(Move(file_name_from, file_name_to));
1503 
1504   // Check everything has been moved.
1505   EXPECT_FALSE(PathExists(file_name_from));
1506   EXPECT_TRUE(PathExists(file_name_to));
1507 }
1508 
TEST_F(FileUtilTest,MoveFileExists)1509 TEST_F(FileUtilTest, MoveFileExists) {
1510   // Create a file
1511   FilePath file_name_from =
1512       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Move_Test_File.txt"));
1513   CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
1514   ASSERT_TRUE(PathExists(file_name_from));
1515 
1516   // The destination name.
1517   FilePath file_name_to = temp_dir_.GetPath().Append(
1518       FILE_PATH_LITERAL("Move_Test_File_Destination.txt"));
1519   CreateTextFile(file_name_to, L"Old file content");
1520   ASSERT_TRUE(PathExists(file_name_to));
1521 
1522   EXPECT_TRUE(Move(file_name_from, file_name_to));
1523 
1524   // Check everything has been moved.
1525   EXPECT_FALSE(PathExists(file_name_from));
1526   EXPECT_TRUE(PathExists(file_name_to));
1527   EXPECT_TRUE(L"Gooooooooooooooooooooogle" == ReadTextFile(file_name_to));
1528 }
1529 
TEST_F(FileUtilTest,MoveFileDirExists)1530 TEST_F(FileUtilTest, MoveFileDirExists) {
1531   // Create a file
1532   FilePath file_name_from =
1533       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Move_Test_File.txt"));
1534   CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
1535   ASSERT_TRUE(PathExists(file_name_from));
1536 
1537   // The destination directory
1538   FilePath dir_name_to =
1539       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Destination"));
1540   CreateDirectory(dir_name_to);
1541   ASSERT_TRUE(PathExists(dir_name_to));
1542 
1543   EXPECT_FALSE(Move(file_name_from, dir_name_to));
1544 }
1545 
1546 
TEST_F(FileUtilTest,MoveNew)1547 TEST_F(FileUtilTest, MoveNew) {
1548   // Create a directory
1549   FilePath dir_name_from =
1550       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Move_From_Subdir"));
1551   CreateDirectory(dir_name_from);
1552   ASSERT_TRUE(PathExists(dir_name_from));
1553 
1554   // Create a file under the directory
1555   FilePath txt_file_name(FILE_PATH_LITERAL("Move_Test_File.txt"));
1556   FilePath file_name_from = dir_name_from.Append(txt_file_name);
1557   CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
1558   ASSERT_TRUE(PathExists(file_name_from));
1559 
1560   // Move the directory.
1561   FilePath dir_name_to =
1562       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Move_To_Subdir"));
1563   FilePath file_name_to =
1564       dir_name_to.Append(FILE_PATH_LITERAL("Move_Test_File.txt"));
1565 
1566   ASSERT_FALSE(PathExists(dir_name_to));
1567 
1568   EXPECT_TRUE(Move(dir_name_from, dir_name_to));
1569 
1570   // Check everything has been moved.
1571   EXPECT_FALSE(PathExists(dir_name_from));
1572   EXPECT_FALSE(PathExists(file_name_from));
1573   EXPECT_TRUE(PathExists(dir_name_to));
1574   EXPECT_TRUE(PathExists(file_name_to));
1575 
1576   // Test path traversal.
1577   file_name_from = dir_name_to.Append(txt_file_name);
1578   file_name_to = dir_name_to.Append(FILE_PATH_LITERAL(".."));
1579   file_name_to = file_name_to.Append(txt_file_name);
1580   EXPECT_FALSE(Move(file_name_from, file_name_to));
1581   EXPECT_TRUE(PathExists(file_name_from));
1582   EXPECT_FALSE(PathExists(file_name_to));
1583   EXPECT_TRUE(internal::MoveUnsafe(file_name_from, file_name_to));
1584   EXPECT_FALSE(PathExists(file_name_from));
1585   EXPECT_TRUE(PathExists(file_name_to));
1586 }
1587 
TEST_F(FileUtilTest,MoveExist)1588 TEST_F(FileUtilTest, MoveExist) {
1589   // Create a directory
1590   FilePath dir_name_from =
1591       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Move_From_Subdir"));
1592   CreateDirectory(dir_name_from);
1593   ASSERT_TRUE(PathExists(dir_name_from));
1594 
1595   // Create a file under the directory
1596   FilePath file_name_from =
1597       dir_name_from.Append(FILE_PATH_LITERAL("Move_Test_File.txt"));
1598   CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
1599   ASSERT_TRUE(PathExists(file_name_from));
1600 
1601   // Move the directory
1602   FilePath dir_name_exists =
1603       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Destination"));
1604 
1605   FilePath dir_name_to =
1606       dir_name_exists.Append(FILE_PATH_LITERAL("Move_To_Subdir"));
1607   FilePath file_name_to =
1608       dir_name_to.Append(FILE_PATH_LITERAL("Move_Test_File.txt"));
1609 
1610   // Create the destination directory.
1611   CreateDirectory(dir_name_exists);
1612   ASSERT_TRUE(PathExists(dir_name_exists));
1613 
1614   EXPECT_TRUE(Move(dir_name_from, dir_name_to));
1615 
1616   // Check everything has been moved.
1617   EXPECT_FALSE(PathExists(dir_name_from));
1618   EXPECT_FALSE(PathExists(file_name_from));
1619   EXPECT_TRUE(PathExists(dir_name_to));
1620   EXPECT_TRUE(PathExists(file_name_to));
1621 }
1622 
TEST_F(FileUtilTest,CopyDirectoryRecursivelyNew)1623 TEST_F(FileUtilTest, CopyDirectoryRecursivelyNew) {
1624   // Create a directory.
1625   FilePath dir_name_from =
1626       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
1627   CreateDirectory(dir_name_from);
1628   ASSERT_TRUE(PathExists(dir_name_from));
1629 
1630   // Create a file under the directory.
1631   FilePath file_name_from =
1632       dir_name_from.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1633   CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
1634   ASSERT_TRUE(PathExists(file_name_from));
1635 
1636   // Create a subdirectory.
1637   FilePath subdir_name_from =
1638       dir_name_from.Append(FILE_PATH_LITERAL("Subdir"));
1639   CreateDirectory(subdir_name_from);
1640   ASSERT_TRUE(PathExists(subdir_name_from));
1641 
1642   // Create a file under the subdirectory.
1643   FilePath file_name2_from =
1644       subdir_name_from.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1645   CreateTextFile(file_name2_from, L"Gooooooooooooooooooooogle");
1646   ASSERT_TRUE(PathExists(file_name2_from));
1647 
1648   // Copy the directory recursively.
1649   FilePath dir_name_to =
1650       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_To_Subdir"));
1651   FilePath file_name_to =
1652       dir_name_to.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1653   FilePath subdir_name_to =
1654       dir_name_to.Append(FILE_PATH_LITERAL("Subdir"));
1655   FilePath file_name2_to =
1656       subdir_name_to.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1657 
1658   ASSERT_FALSE(PathExists(dir_name_to));
1659 
1660   EXPECT_TRUE(CopyDirectory(dir_name_from, dir_name_to, true));
1661 
1662   // Check everything has been copied.
1663   EXPECT_TRUE(PathExists(dir_name_from));
1664   EXPECT_TRUE(PathExists(file_name_from));
1665   EXPECT_TRUE(PathExists(subdir_name_from));
1666   EXPECT_TRUE(PathExists(file_name2_from));
1667   EXPECT_TRUE(PathExists(dir_name_to));
1668   EXPECT_TRUE(PathExists(file_name_to));
1669   EXPECT_TRUE(PathExists(subdir_name_to));
1670   EXPECT_TRUE(PathExists(file_name2_to));
1671 }
1672 
TEST_F(FileUtilTest,CopyDirectoryRecursivelyExists)1673 TEST_F(FileUtilTest, CopyDirectoryRecursivelyExists) {
1674   // Create a directory.
1675   FilePath dir_name_from =
1676       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
1677   CreateDirectory(dir_name_from);
1678   ASSERT_TRUE(PathExists(dir_name_from));
1679 
1680   // Create a file under the directory.
1681   FilePath file_name_from =
1682       dir_name_from.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1683   CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
1684   ASSERT_TRUE(PathExists(file_name_from));
1685 
1686   // Create a subdirectory.
1687   FilePath subdir_name_from =
1688       dir_name_from.Append(FILE_PATH_LITERAL("Subdir"));
1689   CreateDirectory(subdir_name_from);
1690   ASSERT_TRUE(PathExists(subdir_name_from));
1691 
1692   // Create a file under the subdirectory.
1693   FilePath file_name2_from =
1694       subdir_name_from.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1695   CreateTextFile(file_name2_from, L"Gooooooooooooooooooooogle");
1696   ASSERT_TRUE(PathExists(file_name2_from));
1697 
1698   // Copy the directory recursively.
1699   FilePath dir_name_exists =
1700       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Destination"));
1701 
1702   FilePath dir_name_to =
1703       dir_name_exists.Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
1704   FilePath file_name_to =
1705       dir_name_to.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1706   FilePath subdir_name_to =
1707       dir_name_to.Append(FILE_PATH_LITERAL("Subdir"));
1708   FilePath file_name2_to =
1709       subdir_name_to.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1710 
1711   // Create the destination directory.
1712   CreateDirectory(dir_name_exists);
1713   ASSERT_TRUE(PathExists(dir_name_exists));
1714 
1715   EXPECT_TRUE(CopyDirectory(dir_name_from, dir_name_exists, true));
1716 
1717   // Check everything has been copied.
1718   EXPECT_TRUE(PathExists(dir_name_from));
1719   EXPECT_TRUE(PathExists(file_name_from));
1720   EXPECT_TRUE(PathExists(subdir_name_from));
1721   EXPECT_TRUE(PathExists(file_name2_from));
1722   EXPECT_TRUE(PathExists(dir_name_to));
1723   EXPECT_TRUE(PathExists(file_name_to));
1724   EXPECT_TRUE(PathExists(subdir_name_to));
1725   EXPECT_TRUE(PathExists(file_name2_to));
1726 }
1727 
TEST_F(FileUtilTest,CopyDirectoryNew)1728 TEST_F(FileUtilTest, CopyDirectoryNew) {
1729   // Create a directory.
1730   FilePath dir_name_from =
1731       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
1732   CreateDirectory(dir_name_from);
1733   ASSERT_TRUE(PathExists(dir_name_from));
1734 
1735   // Create a file under the directory.
1736   FilePath file_name_from =
1737       dir_name_from.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1738   CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
1739   ASSERT_TRUE(PathExists(file_name_from));
1740 
1741   // Create a subdirectory.
1742   FilePath subdir_name_from =
1743       dir_name_from.Append(FILE_PATH_LITERAL("Subdir"));
1744   CreateDirectory(subdir_name_from);
1745   ASSERT_TRUE(PathExists(subdir_name_from));
1746 
1747   // Create a file under the subdirectory.
1748   FilePath file_name2_from =
1749       subdir_name_from.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1750   CreateTextFile(file_name2_from, L"Gooooooooooooooooooooogle");
1751   ASSERT_TRUE(PathExists(file_name2_from));
1752 
1753   // Copy the directory not recursively.
1754   FilePath dir_name_to =
1755       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_To_Subdir"));
1756   FilePath file_name_to =
1757       dir_name_to.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1758   FilePath subdir_name_to =
1759       dir_name_to.Append(FILE_PATH_LITERAL("Subdir"));
1760 
1761   ASSERT_FALSE(PathExists(dir_name_to));
1762 
1763   EXPECT_TRUE(CopyDirectory(dir_name_from, dir_name_to, false));
1764 
1765   // Check everything has been copied.
1766   EXPECT_TRUE(PathExists(dir_name_from));
1767   EXPECT_TRUE(PathExists(file_name_from));
1768   EXPECT_TRUE(PathExists(subdir_name_from));
1769   EXPECT_TRUE(PathExists(file_name2_from));
1770   EXPECT_TRUE(PathExists(dir_name_to));
1771   EXPECT_TRUE(PathExists(file_name_to));
1772   EXPECT_FALSE(PathExists(subdir_name_to));
1773 }
1774 
TEST_F(FileUtilTest,CopyDirectoryExists)1775 TEST_F(FileUtilTest, CopyDirectoryExists) {
1776   // Create a directory.
1777   FilePath dir_name_from =
1778       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
1779   CreateDirectory(dir_name_from);
1780   ASSERT_TRUE(PathExists(dir_name_from));
1781 
1782   // Create a file under the directory.
1783   FilePath file_name_from =
1784       dir_name_from.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1785   CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
1786   ASSERT_TRUE(PathExists(file_name_from));
1787 
1788   // Create a subdirectory.
1789   FilePath subdir_name_from =
1790       dir_name_from.Append(FILE_PATH_LITERAL("Subdir"));
1791   CreateDirectory(subdir_name_from);
1792   ASSERT_TRUE(PathExists(subdir_name_from));
1793 
1794   // Create a file under the subdirectory.
1795   FilePath file_name2_from =
1796       subdir_name_from.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1797   CreateTextFile(file_name2_from, L"Gooooooooooooooooooooogle");
1798   ASSERT_TRUE(PathExists(file_name2_from));
1799 
1800   // Copy the directory not recursively.
1801   FilePath dir_name_to =
1802       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_To_Subdir"));
1803   FilePath file_name_to =
1804       dir_name_to.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1805   FilePath subdir_name_to =
1806       dir_name_to.Append(FILE_PATH_LITERAL("Subdir"));
1807 
1808   // Create the destination directory.
1809   CreateDirectory(dir_name_to);
1810   ASSERT_TRUE(PathExists(dir_name_to));
1811 
1812   EXPECT_TRUE(CopyDirectory(dir_name_from, dir_name_to, false));
1813 
1814   // Check everything has been copied.
1815   EXPECT_TRUE(PathExists(dir_name_from));
1816   EXPECT_TRUE(PathExists(file_name_from));
1817   EXPECT_TRUE(PathExists(subdir_name_from));
1818   EXPECT_TRUE(PathExists(file_name2_from));
1819   EXPECT_TRUE(PathExists(dir_name_to));
1820   EXPECT_TRUE(PathExists(file_name_to));
1821   EXPECT_FALSE(PathExists(subdir_name_to));
1822 }
1823 
TEST_F(FileUtilTest,CopyFileWithCopyDirectoryRecursiveToNew)1824 TEST_F(FileUtilTest, CopyFileWithCopyDirectoryRecursiveToNew) {
1825   // Create a file
1826   FilePath file_name_from =
1827       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1828   CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
1829   ASSERT_TRUE(PathExists(file_name_from));
1830 
1831   // The destination name
1832   FilePath file_name_to = temp_dir_.GetPath().Append(
1833       FILE_PATH_LITERAL("Copy_Test_File_Destination.txt"));
1834   ASSERT_FALSE(PathExists(file_name_to));
1835 
1836   EXPECT_TRUE(CopyDirectory(file_name_from, file_name_to, true));
1837 
1838   // Check the has been copied
1839   EXPECT_TRUE(PathExists(file_name_to));
1840 }
1841 
TEST_F(FileUtilTest,CopyFileWithCopyDirectoryRecursiveToExisting)1842 TEST_F(FileUtilTest, CopyFileWithCopyDirectoryRecursiveToExisting) {
1843   // Create a file
1844   FilePath file_name_from =
1845       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1846   CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
1847   ASSERT_TRUE(PathExists(file_name_from));
1848 
1849   // The destination name
1850   FilePath file_name_to = temp_dir_.GetPath().Append(
1851       FILE_PATH_LITERAL("Copy_Test_File_Destination.txt"));
1852   CreateTextFile(file_name_to, L"Old file content");
1853   ASSERT_TRUE(PathExists(file_name_to));
1854 
1855   EXPECT_TRUE(CopyDirectory(file_name_from, file_name_to, true));
1856 
1857   // Check the has been copied
1858   EXPECT_TRUE(PathExists(file_name_to));
1859   EXPECT_TRUE(L"Gooooooooooooooooooooogle" == ReadTextFile(file_name_to));
1860 }
1861 
TEST_F(FileUtilTest,CopyFileWithCopyDirectoryRecursiveToExistingDirectory)1862 TEST_F(FileUtilTest, CopyFileWithCopyDirectoryRecursiveToExistingDirectory) {
1863   // Create a file
1864   FilePath file_name_from =
1865       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1866   CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
1867   ASSERT_TRUE(PathExists(file_name_from));
1868 
1869   // The destination
1870   FilePath dir_name_to =
1871       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Destination"));
1872   CreateDirectory(dir_name_to);
1873   ASSERT_TRUE(PathExists(dir_name_to));
1874   FilePath file_name_to =
1875       dir_name_to.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1876 
1877   EXPECT_TRUE(CopyDirectory(file_name_from, dir_name_to, true));
1878 
1879   // Check the has been copied
1880   EXPECT_TRUE(PathExists(file_name_to));
1881 }
1882 
TEST_F(FileUtilTest,CopyFileFailureWithCopyDirectoryExcl)1883 TEST_F(FileUtilTest, CopyFileFailureWithCopyDirectoryExcl) {
1884   // Create a file
1885   FilePath file_name_from =
1886       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1887   CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
1888   ASSERT_TRUE(PathExists(file_name_from));
1889 
1890   // Make a destination file.
1891   FilePath file_name_to = temp_dir_.GetPath().Append(
1892       FILE_PATH_LITERAL("Copy_Test_File_Destination.txt"));
1893   CreateTextFile(file_name_to, L"Old file content");
1894   ASSERT_TRUE(PathExists(file_name_to));
1895 
1896   // Overwriting the destination should fail.
1897   EXPECT_FALSE(CopyDirectoryExcl(file_name_from, file_name_to, true));
1898   EXPECT_EQ(L"Old file content", ReadTextFile(file_name_to));
1899 }
1900 
TEST_F(FileUtilTest,CopyDirectoryWithTrailingSeparators)1901 TEST_F(FileUtilTest, CopyDirectoryWithTrailingSeparators) {
1902   // Create a directory.
1903   FilePath dir_name_from =
1904       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
1905   CreateDirectory(dir_name_from);
1906   ASSERT_TRUE(PathExists(dir_name_from));
1907 
1908   // Create a file under the directory.
1909   FilePath file_name_from =
1910       dir_name_from.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1911   CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
1912   ASSERT_TRUE(PathExists(file_name_from));
1913 
1914   // Copy the directory recursively.
1915   FilePath dir_name_to =
1916       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_To_Subdir"));
1917   FilePath file_name_to =
1918       dir_name_to.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1919 
1920   // Create from path with trailing separators.
1921 #if defined(OS_WIN)
1922   FilePath from_path =
1923       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_From_Subdir\\\\\\"));
1924 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
1925   FilePath from_path =
1926       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_From_Subdir///"));
1927 #endif
1928 
1929   EXPECT_TRUE(CopyDirectory(from_path, dir_name_to, true));
1930 
1931   // Check everything has been copied.
1932   EXPECT_TRUE(PathExists(dir_name_from));
1933   EXPECT_TRUE(PathExists(file_name_from));
1934   EXPECT_TRUE(PathExists(dir_name_to));
1935   EXPECT_TRUE(PathExists(file_name_to));
1936 }
1937 
1938 #if defined(OS_POSIX)
TEST_F(FileUtilTest,CopyDirectoryWithNonRegularFiles)1939 TEST_F(FileUtilTest, CopyDirectoryWithNonRegularFiles) {
1940   // Create a directory.
1941   FilePath dir_name_from =
1942       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
1943   ASSERT_TRUE(CreateDirectory(dir_name_from));
1944   ASSERT_TRUE(PathExists(dir_name_from));
1945 
1946   // Create a file under the directory.
1947   FilePath file_name_from =
1948       dir_name_from.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1949   CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
1950   ASSERT_TRUE(PathExists(file_name_from));
1951 
1952   // Create a symbolic link under the directory pointing to that file.
1953   FilePath symlink_name_from =
1954       dir_name_from.Append(FILE_PATH_LITERAL("Symlink"));
1955   ASSERT_TRUE(CreateSymbolicLink(file_name_from, symlink_name_from));
1956   ASSERT_TRUE(PathExists(symlink_name_from));
1957 
1958   // Create a fifo under the directory.
1959   FilePath fifo_name_from =
1960       dir_name_from.Append(FILE_PATH_LITERAL("Fifo"));
1961   ASSERT_EQ(0, mkfifo(fifo_name_from.value().c_str(), 0644));
1962   ASSERT_TRUE(PathExists(fifo_name_from));
1963 
1964   // Copy the directory.
1965   FilePath dir_name_to =
1966       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_To_Subdir"));
1967   FilePath file_name_to =
1968       dir_name_to.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1969   FilePath symlink_name_to =
1970       dir_name_to.Append(FILE_PATH_LITERAL("Symlink"));
1971   FilePath fifo_name_to =
1972       dir_name_to.Append(FILE_PATH_LITERAL("Fifo"));
1973 
1974   ASSERT_FALSE(PathExists(dir_name_to));
1975 
1976   EXPECT_TRUE(CopyDirectory(dir_name_from, dir_name_to, false));
1977 
1978   // Check that only directories and regular files are copied.
1979   EXPECT_TRUE(PathExists(dir_name_from));
1980   EXPECT_TRUE(PathExists(file_name_from));
1981   EXPECT_TRUE(PathExists(symlink_name_from));
1982   EXPECT_TRUE(PathExists(fifo_name_from));
1983   EXPECT_TRUE(PathExists(dir_name_to));
1984   EXPECT_TRUE(PathExists(file_name_to));
1985   EXPECT_FALSE(PathExists(symlink_name_to));
1986   EXPECT_FALSE(PathExists(fifo_name_to));
1987 }
1988 
TEST_F(FileUtilTest,CopyDirectoryExclFileOverSymlink)1989 TEST_F(FileUtilTest, CopyDirectoryExclFileOverSymlink) {
1990   // Create a directory.
1991   FilePath dir_name_from =
1992       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
1993   ASSERT_TRUE(CreateDirectory(dir_name_from));
1994   ASSERT_TRUE(PathExists(dir_name_from));
1995 
1996   // Create a file under the directory.
1997   FilePath file_name_from =
1998       dir_name_from.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1999   CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
2000   ASSERT_TRUE(PathExists(file_name_from));
2001 
2002   // Create a destination directory with a symlink of the same name.
2003   FilePath dir_name_to =
2004       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_To_Subdir"));
2005   ASSERT_TRUE(CreateDirectory(dir_name_to));
2006   ASSERT_TRUE(PathExists(dir_name_to));
2007 
2008   FilePath symlink_target =
2009       dir_name_to.Append(FILE_PATH_LITERAL("Symlink_Target.txt"));
2010   CreateTextFile(symlink_target, L"asdf");
2011   ASSERT_TRUE(PathExists(symlink_target));
2012 
2013   FilePath symlink_name_to =
2014       dir_name_to.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
2015   ASSERT_TRUE(CreateSymbolicLink(symlink_target, symlink_name_to));
2016   ASSERT_TRUE(PathExists(symlink_name_to));
2017 
2018   // Check that copying fails.
2019   EXPECT_FALSE(CopyDirectoryExcl(dir_name_from, dir_name_to, false));
2020 }
2021 
TEST_F(FileUtilTest,CopyDirectoryExclDirectoryOverSymlink)2022 TEST_F(FileUtilTest, CopyDirectoryExclDirectoryOverSymlink) {
2023   // Create a directory.
2024   FilePath dir_name_from =
2025       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
2026   ASSERT_TRUE(CreateDirectory(dir_name_from));
2027   ASSERT_TRUE(PathExists(dir_name_from));
2028 
2029   // Create a subdirectory.
2030   FilePath subdir_name_from = dir_name_from.Append(FILE_PATH_LITERAL("Subsub"));
2031   CreateDirectory(subdir_name_from);
2032   ASSERT_TRUE(PathExists(subdir_name_from));
2033 
2034   // Create a destination directory with a symlink of the same name.
2035   FilePath dir_name_to =
2036       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_To_Subdir"));
2037   ASSERT_TRUE(CreateDirectory(dir_name_to));
2038   ASSERT_TRUE(PathExists(dir_name_to));
2039 
2040   FilePath symlink_target = dir_name_to.Append(FILE_PATH_LITERAL("Subsub"));
2041   CreateTextFile(symlink_target, L"asdf");
2042   ASSERT_TRUE(PathExists(symlink_target));
2043 
2044   FilePath symlink_name_to =
2045       dir_name_to.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
2046   ASSERT_TRUE(CreateSymbolicLink(symlink_target, symlink_name_to));
2047   ASSERT_TRUE(PathExists(symlink_name_to));
2048 
2049   // Check that copying fails.
2050   EXPECT_FALSE(CopyDirectoryExcl(dir_name_from, dir_name_to, false));
2051 }
2052 
TEST_F(FileUtilTest,CopyDirectoryExclFileOverDanglingSymlink)2053 TEST_F(FileUtilTest, CopyDirectoryExclFileOverDanglingSymlink) {
2054   // Create a directory.
2055   FilePath dir_name_from =
2056       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
2057   ASSERT_TRUE(CreateDirectory(dir_name_from));
2058   ASSERT_TRUE(PathExists(dir_name_from));
2059 
2060   // Create a file under the directory.
2061   FilePath file_name_from =
2062       dir_name_from.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
2063   CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
2064   ASSERT_TRUE(PathExists(file_name_from));
2065 
2066   // Create a destination directory with a dangling symlink of the same name.
2067   FilePath dir_name_to =
2068       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_To_Subdir"));
2069   ASSERT_TRUE(CreateDirectory(dir_name_to));
2070   ASSERT_TRUE(PathExists(dir_name_to));
2071 
2072   FilePath symlink_target =
2073       dir_name_to.Append(FILE_PATH_LITERAL("Symlink_Target.txt"));
2074   CreateTextFile(symlink_target, L"asdf");
2075   ASSERT_TRUE(PathExists(symlink_target));
2076 
2077   FilePath symlink_name_to =
2078       dir_name_to.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
2079   ASSERT_TRUE(CreateSymbolicLink(symlink_target, symlink_name_to));
2080   ASSERT_TRUE(PathExists(symlink_name_to));
2081   ASSERT_TRUE(DeleteFile(symlink_target, false));
2082 
2083   // Check that copying fails and that no file was created for the symlink's
2084   // referent.
2085   EXPECT_FALSE(CopyDirectoryExcl(dir_name_from, dir_name_to, false));
2086   EXPECT_FALSE(PathExists(symlink_target));
2087 }
2088 
TEST_F(FileUtilTest,CopyDirectoryExclDirectoryOverDanglingSymlink)2089 TEST_F(FileUtilTest, CopyDirectoryExclDirectoryOverDanglingSymlink) {
2090   // Create a directory.
2091   FilePath dir_name_from =
2092       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
2093   ASSERT_TRUE(CreateDirectory(dir_name_from));
2094   ASSERT_TRUE(PathExists(dir_name_from));
2095 
2096   // Create a subdirectory.
2097   FilePath subdir_name_from = dir_name_from.Append(FILE_PATH_LITERAL("Subsub"));
2098   CreateDirectory(subdir_name_from);
2099   ASSERT_TRUE(PathExists(subdir_name_from));
2100 
2101   // Create a destination directory with a dangling symlink of the same name.
2102   FilePath dir_name_to =
2103       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_To_Subdir"));
2104   ASSERT_TRUE(CreateDirectory(dir_name_to));
2105   ASSERT_TRUE(PathExists(dir_name_to));
2106 
2107   FilePath symlink_target =
2108       dir_name_to.Append(FILE_PATH_LITERAL("Symlink_Target.txt"));
2109   CreateTextFile(symlink_target, L"asdf");
2110   ASSERT_TRUE(PathExists(symlink_target));
2111 
2112   FilePath symlink_name_to =
2113       dir_name_to.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
2114   ASSERT_TRUE(CreateSymbolicLink(symlink_target, symlink_name_to));
2115   ASSERT_TRUE(PathExists(symlink_name_to));
2116   ASSERT_TRUE(DeleteFile(symlink_target, false));
2117 
2118   // Check that copying fails and that no directory was created for the
2119   // symlink's referent.
2120   EXPECT_FALSE(CopyDirectoryExcl(dir_name_from, dir_name_to, false));
2121   EXPECT_FALSE(PathExists(symlink_target));
2122 }
2123 
TEST_F(FileUtilTest,CopyDirectoryExclFileOverFifo)2124 TEST_F(FileUtilTest, CopyDirectoryExclFileOverFifo) {
2125   // Create a directory.
2126   FilePath dir_name_from =
2127       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
2128   ASSERT_TRUE(CreateDirectory(dir_name_from));
2129   ASSERT_TRUE(PathExists(dir_name_from));
2130 
2131   // Create a file under the directory.
2132   FilePath file_name_from =
2133       dir_name_from.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
2134   CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
2135   ASSERT_TRUE(PathExists(file_name_from));
2136 
2137   // Create a destination directory with a fifo of the same name.
2138   FilePath dir_name_to =
2139       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_To_Subdir"));
2140   ASSERT_TRUE(CreateDirectory(dir_name_to));
2141   ASSERT_TRUE(PathExists(dir_name_to));
2142 
2143   FilePath fifo_name_to =
2144       dir_name_to.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
2145   ASSERT_EQ(0, mkfifo(fifo_name_to.value().c_str(), 0644));
2146   ASSERT_TRUE(PathExists(fifo_name_to));
2147 
2148   // Check that copying fails.
2149   EXPECT_FALSE(CopyDirectoryExcl(dir_name_from, dir_name_to, false));
2150 }
2151 #endif  // defined(OS_POSIX)
2152 
TEST_F(FileUtilTest,CopyFile)2153 TEST_F(FileUtilTest, CopyFile) {
2154   // Create a directory
2155   FilePath dir_name_from =
2156       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
2157   ASSERT_TRUE(CreateDirectory(dir_name_from));
2158   ASSERT_TRUE(DirectoryExists(dir_name_from));
2159 
2160   // Create a file under the directory
2161   FilePath file_name_from =
2162       dir_name_from.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
2163   const std::wstring file_contents(L"Gooooooooooooooooooooogle");
2164   CreateTextFile(file_name_from, file_contents);
2165   ASSERT_TRUE(PathExists(file_name_from));
2166 
2167   // Copy the file.
2168   FilePath dest_file = dir_name_from.Append(FILE_PATH_LITERAL("DestFile.txt"));
2169   ASSERT_TRUE(CopyFile(file_name_from, dest_file));
2170 
2171   // Try to copy the file to another location using '..' in the path.
2172   FilePath dest_file2(dir_name_from);
2173   dest_file2 = dest_file2.AppendASCII("..");
2174   dest_file2 = dest_file2.AppendASCII("DestFile.txt");
2175   ASSERT_FALSE(CopyFile(file_name_from, dest_file2));
2176 
2177   FilePath dest_file2_test(dir_name_from);
2178   dest_file2_test = dest_file2_test.DirName();
2179   dest_file2_test = dest_file2_test.AppendASCII("DestFile.txt");
2180 
2181   // Check expected copy results.
2182   EXPECT_TRUE(PathExists(file_name_from));
2183   EXPECT_TRUE(PathExists(dest_file));
2184   EXPECT_EQ(file_contents, ReadTextFile(dest_file));
2185   EXPECT_FALSE(PathExists(dest_file2_test));
2186   EXPECT_FALSE(PathExists(dest_file2));
2187 
2188   // Change |file_name_from| contents.
2189   const std::wstring new_file_contents(L"Moogle");
2190   CreateTextFile(file_name_from, new_file_contents);
2191   ASSERT_TRUE(PathExists(file_name_from));
2192   EXPECT_EQ(new_file_contents, ReadTextFile(file_name_from));
2193 
2194   // Overwrite |dest_file|.
2195   ASSERT_TRUE(CopyFile(file_name_from, dest_file));
2196   EXPECT_TRUE(PathExists(dest_file));
2197   EXPECT_EQ(new_file_contents, ReadTextFile(dest_file));
2198 
2199   // Create another directory.
2200   FilePath dest_dir = temp_dir_.GetPath().Append(FPL("dest_dir"));
2201   ASSERT_TRUE(CreateDirectory(dest_dir));
2202   EXPECT_TRUE(DirectoryExists(dest_dir));
2203   EXPECT_TRUE(IsDirectoryEmpty(dest_dir));
2204 
2205   // Make sure CopyFile() cannot overwrite a directory.
2206   ASSERT_FALSE(CopyFile(file_name_from, dest_dir));
2207   EXPECT_TRUE(DirectoryExists(dest_dir));
2208   EXPECT_TRUE(IsDirectoryEmpty(dest_dir));
2209 }
2210 
2211 // file_util winds up using autoreleased objects on the Mac, so this needs
2212 // to be a PlatformTest.
2213 typedef PlatformTest ReadOnlyFileUtilTest;
2214 
TEST_F(ReadOnlyFileUtilTest,ContentsEqual)2215 TEST_F(ReadOnlyFileUtilTest, ContentsEqual) {
2216   FilePath data_dir;
2217   ASSERT_TRUE(PathService::Get(DIR_TEST_DATA, &data_dir));
2218   data_dir = data_dir.AppendASCII("file_util");
2219   ASSERT_TRUE(PathExists(data_dir));
2220 
2221   FilePath original_file =
2222       data_dir.Append(FILE_PATH_LITERAL("original.txt"));
2223   FilePath same_file =
2224       data_dir.Append(FILE_PATH_LITERAL("same.txt"));
2225   FilePath same_length_file =
2226       data_dir.Append(FILE_PATH_LITERAL("same_length.txt"));
2227   FilePath different_file =
2228       data_dir.Append(FILE_PATH_LITERAL("different.txt"));
2229   FilePath different_first_file =
2230       data_dir.Append(FILE_PATH_LITERAL("different_first.txt"));
2231   FilePath different_last_file =
2232       data_dir.Append(FILE_PATH_LITERAL("different_last.txt"));
2233   FilePath empty1_file =
2234       data_dir.Append(FILE_PATH_LITERAL("empty1.txt"));
2235   FilePath empty2_file =
2236       data_dir.Append(FILE_PATH_LITERAL("empty2.txt"));
2237   FilePath shortened_file =
2238       data_dir.Append(FILE_PATH_LITERAL("shortened.txt"));
2239   FilePath binary_file =
2240       data_dir.Append(FILE_PATH_LITERAL("binary_file.bin"));
2241   FilePath binary_file_same =
2242       data_dir.Append(FILE_PATH_LITERAL("binary_file_same.bin"));
2243   FilePath binary_file_diff =
2244       data_dir.Append(FILE_PATH_LITERAL("binary_file_diff.bin"));
2245 
2246   EXPECT_TRUE(ContentsEqual(original_file, original_file));
2247   EXPECT_TRUE(ContentsEqual(original_file, same_file));
2248   EXPECT_FALSE(ContentsEqual(original_file, same_length_file));
2249   EXPECT_FALSE(ContentsEqual(original_file, different_file));
2250   EXPECT_FALSE(ContentsEqual(FilePath(FILE_PATH_LITERAL("bogusname")),
2251                              FilePath(FILE_PATH_LITERAL("bogusname"))));
2252   EXPECT_FALSE(ContentsEqual(original_file, different_first_file));
2253   EXPECT_FALSE(ContentsEqual(original_file, different_last_file));
2254   EXPECT_TRUE(ContentsEqual(empty1_file, empty2_file));
2255   EXPECT_FALSE(ContentsEqual(original_file, shortened_file));
2256   EXPECT_FALSE(ContentsEqual(shortened_file, original_file));
2257   EXPECT_TRUE(ContentsEqual(binary_file, binary_file_same));
2258   EXPECT_FALSE(ContentsEqual(binary_file, binary_file_diff));
2259 }
2260 
TEST_F(ReadOnlyFileUtilTest,TextContentsEqual)2261 TEST_F(ReadOnlyFileUtilTest, TextContentsEqual) {
2262   FilePath data_dir;
2263   ASSERT_TRUE(PathService::Get(DIR_TEST_DATA, &data_dir));
2264   data_dir = data_dir.AppendASCII("file_util");
2265   ASSERT_TRUE(PathExists(data_dir));
2266 
2267   FilePath original_file =
2268       data_dir.Append(FILE_PATH_LITERAL("original.txt"));
2269   FilePath same_file =
2270       data_dir.Append(FILE_PATH_LITERAL("same.txt"));
2271   FilePath crlf_file =
2272       data_dir.Append(FILE_PATH_LITERAL("crlf.txt"));
2273   FilePath shortened_file =
2274       data_dir.Append(FILE_PATH_LITERAL("shortened.txt"));
2275   FilePath different_file =
2276       data_dir.Append(FILE_PATH_LITERAL("different.txt"));
2277   FilePath different_first_file =
2278       data_dir.Append(FILE_PATH_LITERAL("different_first.txt"));
2279   FilePath different_last_file =
2280       data_dir.Append(FILE_PATH_LITERAL("different_last.txt"));
2281   FilePath first1_file =
2282       data_dir.Append(FILE_PATH_LITERAL("first1.txt"));
2283   FilePath first2_file =
2284       data_dir.Append(FILE_PATH_LITERAL("first2.txt"));
2285   FilePath empty1_file =
2286       data_dir.Append(FILE_PATH_LITERAL("empty1.txt"));
2287   FilePath empty2_file =
2288       data_dir.Append(FILE_PATH_LITERAL("empty2.txt"));
2289   FilePath blank_line_file =
2290       data_dir.Append(FILE_PATH_LITERAL("blank_line.txt"));
2291   FilePath blank_line_crlf_file =
2292       data_dir.Append(FILE_PATH_LITERAL("blank_line_crlf.txt"));
2293 
2294   EXPECT_TRUE(TextContentsEqual(original_file, same_file));
2295   EXPECT_TRUE(TextContentsEqual(original_file, crlf_file));
2296   EXPECT_FALSE(TextContentsEqual(original_file, shortened_file));
2297   EXPECT_FALSE(TextContentsEqual(original_file, different_file));
2298   EXPECT_FALSE(TextContentsEqual(original_file, different_first_file));
2299   EXPECT_FALSE(TextContentsEqual(original_file, different_last_file));
2300   EXPECT_FALSE(TextContentsEqual(first1_file, first2_file));
2301   EXPECT_TRUE(TextContentsEqual(empty1_file, empty2_file));
2302   EXPECT_FALSE(TextContentsEqual(original_file, empty1_file));
2303   EXPECT_TRUE(TextContentsEqual(blank_line_file, blank_line_crlf_file));
2304 }
2305 
2306 // We don't need equivalent functionality outside of Windows.
2307 #if defined(OS_WIN)
TEST_F(FileUtilTest,CopyAndDeleteDirectoryTest)2308 TEST_F(FileUtilTest, CopyAndDeleteDirectoryTest) {
2309   // Create a directory
2310   FilePath dir_name_from = temp_dir_.GetPath().Append(
2311       FILE_PATH_LITERAL("CopyAndDelete_From_Subdir"));
2312   CreateDirectory(dir_name_from);
2313   ASSERT_TRUE(PathExists(dir_name_from));
2314 
2315   // Create a file under the directory
2316   FilePath file_name_from =
2317       dir_name_from.Append(FILE_PATH_LITERAL("CopyAndDelete_Test_File.txt"));
2318   CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
2319   ASSERT_TRUE(PathExists(file_name_from));
2320 
2321   // Move the directory by using CopyAndDeleteDirectory
2322   FilePath dir_name_to =
2323       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("CopyAndDelete_To_Subdir"));
2324   FilePath file_name_to =
2325       dir_name_to.Append(FILE_PATH_LITERAL("CopyAndDelete_Test_File.txt"));
2326 
2327   ASSERT_FALSE(PathExists(dir_name_to));
2328 
2329   EXPECT_TRUE(internal::CopyAndDeleteDirectory(dir_name_from,
2330                                                      dir_name_to));
2331 
2332   // Check everything has been moved.
2333   EXPECT_FALSE(PathExists(dir_name_from));
2334   EXPECT_FALSE(PathExists(file_name_from));
2335   EXPECT_TRUE(PathExists(dir_name_to));
2336   EXPECT_TRUE(PathExists(file_name_to));
2337 }
2338 
TEST_F(FileUtilTest,GetTempDirTest)2339 TEST_F(FileUtilTest, GetTempDirTest) {
2340   static const TCHAR* kTmpKey = _T("TMP");
2341   static const TCHAR* kTmpValues[] = {
2342     _T(""), _T("C:"), _T("C:\\"), _T("C:\\tmp"), _T("C:\\tmp\\")
2343   };
2344   // Save the original $TMP.
2345   size_t original_tmp_size;
2346   TCHAR* original_tmp;
2347   ASSERT_EQ(0, ::_tdupenv_s(&original_tmp, &original_tmp_size, kTmpKey));
2348   // original_tmp may be NULL.
2349 
2350   for (unsigned int i = 0; i < arraysize(kTmpValues); ++i) {
2351     FilePath path;
2352     ::_tputenv_s(kTmpKey, kTmpValues[i]);
2353     GetTempDir(&path);
2354     EXPECT_TRUE(path.IsAbsolute()) << "$TMP=" << kTmpValues[i] <<
2355         " result=" << path.value();
2356   }
2357 
2358   // Restore the original $TMP.
2359   if (original_tmp) {
2360     ::_tputenv_s(kTmpKey, original_tmp);
2361     free(original_tmp);
2362   } else {
2363     ::_tputenv_s(kTmpKey, _T(""));
2364   }
2365 }
2366 #endif  // OS_WIN
2367 
2368 // Test that files opened by OpenFile are not set up for inheritance into child
2369 // procs.
TEST_F(FileUtilTest,OpenFileNoInheritance)2370 TEST_F(FileUtilTest, OpenFileNoInheritance) {
2371   FilePath file_path(temp_dir_.GetPath().Append(FPL("a_file")));
2372 
2373   for (const char* mode : {"wb", "r,ccs=UTF-8"}) {
2374     SCOPED_TRACE(mode);
2375     ASSERT_NO_FATAL_FAILURE(CreateTextFile(file_path, L"Geepers"));
2376     FILE* file = OpenFile(file_path, mode);
2377     ASSERT_NE(nullptr, file);
2378     {
2379       ScopedClosureRunner file_closer(Bind(IgnoreResult(&CloseFile), file));
2380       bool is_inheritable = true;
2381       ASSERT_NO_FATAL_FAILURE(GetIsInheritable(file, &is_inheritable));
2382       EXPECT_FALSE(is_inheritable);
2383     }
2384     ASSERT_TRUE(DeleteFile(file_path, false));
2385   }
2386 }
2387 
TEST_F(FileUtilTest,CreateTemporaryFileTest)2388 TEST_F(FileUtilTest, CreateTemporaryFileTest) {
2389   FilePath temp_files[3];
2390   for (int i = 0; i < 3; i++) {
2391     ASSERT_TRUE(CreateTemporaryFile(&(temp_files[i])));
2392     EXPECT_TRUE(PathExists(temp_files[i]));
2393     EXPECT_FALSE(DirectoryExists(temp_files[i]));
2394   }
2395   for (int i = 0; i < 3; i++)
2396     EXPECT_FALSE(temp_files[i] == temp_files[(i+1)%3]);
2397   for (int i = 0; i < 3; i++)
2398     EXPECT_TRUE(DeleteFile(temp_files[i], false));
2399 }
2400 
TEST_F(FileUtilTest,CreateAndOpenTemporaryFileTest)2401 TEST_F(FileUtilTest, CreateAndOpenTemporaryFileTest) {
2402   FilePath names[3];
2403   FILE* fps[3];
2404   int i;
2405 
2406   // Create; make sure they are open and exist.
2407   for (i = 0; i < 3; ++i) {
2408     fps[i] = CreateAndOpenTemporaryFile(&(names[i]));
2409     ASSERT_TRUE(fps[i]);
2410     EXPECT_TRUE(PathExists(names[i]));
2411   }
2412 
2413   // Make sure all names are unique.
2414   for (i = 0; i < 3; ++i) {
2415     EXPECT_FALSE(names[i] == names[(i+1)%3]);
2416   }
2417 
2418   // Close and delete.
2419   for (i = 0; i < 3; ++i) {
2420     EXPECT_TRUE(CloseFile(fps[i]));
2421     EXPECT_TRUE(DeleteFile(names[i], false));
2422   }
2423 }
2424 
2425 #if defined(OS_FUCHSIA)
2426 // TODO(crbug.com/851747): Re-enable when the Fuchsia-side fix for fdopen has
2427 // been rolled into Chromium.
2428 #define MAYBE_FileToFILE DISABLED_FileToFILE
2429 #else
2430 #define MAYBE_FileToFILE FileToFILE
2431 #endif
TEST_F(FileUtilTest,MAYBE_FileToFILE)2432 TEST_F(FileUtilTest, MAYBE_FileToFILE) {
2433   File file;
2434   FILE* stream = FileToFILE(std::move(file), "w");
2435   EXPECT_FALSE(stream);
2436 
2437   FilePath file_name = temp_dir_.GetPath().Append(FPL("The file.txt"));
2438   file = File(file_name, File::FLAG_CREATE | File::FLAG_WRITE);
2439   EXPECT_TRUE(file.IsValid());
2440 
2441   stream = FileToFILE(std::move(file), "w");
2442   EXPECT_TRUE(stream);
2443   EXPECT_FALSE(file.IsValid());
2444   EXPECT_TRUE(CloseFile(stream));
2445 }
2446 
TEST_F(FileUtilTest,CreateNewTempDirectoryTest)2447 TEST_F(FileUtilTest, CreateNewTempDirectoryTest) {
2448   FilePath temp_dir;
2449   ASSERT_TRUE(CreateNewTempDirectory(FilePath::StringType(), &temp_dir));
2450   EXPECT_TRUE(PathExists(temp_dir));
2451   EXPECT_TRUE(DeleteFile(temp_dir, false));
2452 }
2453 
TEST_F(FileUtilTest,CreateNewTemporaryDirInDirTest)2454 TEST_F(FileUtilTest, CreateNewTemporaryDirInDirTest) {
2455   FilePath new_dir;
2456   ASSERT_TRUE(CreateTemporaryDirInDir(
2457       temp_dir_.GetPath(), FILE_PATH_LITERAL("CreateNewTemporaryDirInDirTest"),
2458       &new_dir));
2459   EXPECT_TRUE(PathExists(new_dir));
2460   EXPECT_TRUE(temp_dir_.GetPath().IsParent(new_dir));
2461   EXPECT_TRUE(DeleteFile(new_dir, false));
2462 }
2463 
2464 #if defined(OS_POSIX) || defined(OS_FUCHSIA)
TEST_F(FileUtilTest,GetShmemTempDirTest)2465 TEST_F(FileUtilTest, GetShmemTempDirTest) {
2466   FilePath dir;
2467   EXPECT_TRUE(GetShmemTempDir(false, &dir));
2468   EXPECT_TRUE(DirectoryExists(dir));
2469 }
2470 #endif
2471 
TEST_F(FileUtilTest,GetHomeDirTest)2472 TEST_F(FileUtilTest, GetHomeDirTest) {
2473 #if !defined(OS_ANDROID)  // Not implemented on Android.
2474   // We don't actually know what the home directory is supposed to be without
2475   // calling some OS functions which would just duplicate the implementation.
2476   // So here we just test that it returns something "reasonable".
2477   FilePath home = GetHomeDir();
2478   ASSERT_FALSE(home.empty());
2479   ASSERT_TRUE(home.IsAbsolute());
2480 #endif
2481 }
2482 
TEST_F(FileUtilTest,CreateDirectoryTest)2483 TEST_F(FileUtilTest, CreateDirectoryTest) {
2484   FilePath test_root =
2485       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("create_directory_test"));
2486 #if defined(OS_WIN)
2487   FilePath test_path =
2488       test_root.Append(FILE_PATH_LITERAL("dir\\tree\\likely\\doesnt\\exist\\"));
2489 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
2490   FilePath test_path =
2491       test_root.Append(FILE_PATH_LITERAL("dir/tree/likely/doesnt/exist/"));
2492 #endif
2493 
2494   EXPECT_FALSE(PathExists(test_path));
2495   EXPECT_TRUE(CreateDirectory(test_path));
2496   EXPECT_TRUE(PathExists(test_path));
2497   // CreateDirectory returns true if the DirectoryExists returns true.
2498   EXPECT_TRUE(CreateDirectory(test_path));
2499 
2500   // Doesn't work to create it on top of a non-dir
2501   test_path = test_path.Append(FILE_PATH_LITERAL("foobar.txt"));
2502   EXPECT_FALSE(PathExists(test_path));
2503   CreateTextFile(test_path, L"test file");
2504   EXPECT_TRUE(PathExists(test_path));
2505   EXPECT_FALSE(CreateDirectory(test_path));
2506 
2507   EXPECT_TRUE(DeleteFile(test_root, true));
2508   EXPECT_FALSE(PathExists(test_root));
2509   EXPECT_FALSE(PathExists(test_path));
2510 
2511   // Verify assumptions made by the Windows implementation:
2512   // 1. The current directory always exists.
2513   // 2. The root directory always exists.
2514   ASSERT_TRUE(DirectoryExists(FilePath(FilePath::kCurrentDirectory)));
2515   FilePath top_level = test_root;
2516   while (top_level != top_level.DirName()) {
2517     top_level = top_level.DirName();
2518   }
2519   ASSERT_TRUE(DirectoryExists(top_level));
2520 
2521   // Given these assumptions hold, it should be safe to
2522   // test that "creating" these directories succeeds.
2523   EXPECT_TRUE(CreateDirectory(
2524       FilePath(FilePath::kCurrentDirectory)));
2525   EXPECT_TRUE(CreateDirectory(top_level));
2526 
2527 #if defined(OS_WIN)
2528   FilePath invalid_drive(FILE_PATH_LITERAL("o:\\"));
2529   FilePath invalid_path =
2530       invalid_drive.Append(FILE_PATH_LITERAL("some\\inaccessible\\dir"));
2531   if (!PathExists(invalid_drive)) {
2532     EXPECT_FALSE(CreateDirectory(invalid_path));
2533   }
2534 #endif
2535 }
2536 
TEST_F(FileUtilTest,DetectDirectoryTest)2537 TEST_F(FileUtilTest, DetectDirectoryTest) {
2538   // Check a directory
2539   FilePath test_root =
2540       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("detect_directory_test"));
2541   EXPECT_FALSE(PathExists(test_root));
2542   EXPECT_TRUE(CreateDirectory(test_root));
2543   EXPECT_TRUE(PathExists(test_root));
2544   EXPECT_TRUE(DirectoryExists(test_root));
2545   // Check a file
2546   FilePath test_path =
2547       test_root.Append(FILE_PATH_LITERAL("foobar.txt"));
2548   EXPECT_FALSE(PathExists(test_path));
2549   CreateTextFile(test_path, L"test file");
2550   EXPECT_TRUE(PathExists(test_path));
2551   EXPECT_FALSE(DirectoryExists(test_path));
2552   EXPECT_TRUE(DeleteFile(test_path, false));
2553 
2554   EXPECT_TRUE(DeleteFile(test_root, true));
2555 }
2556 
TEST_F(FileUtilTest,FileEnumeratorTest)2557 TEST_F(FileUtilTest, FileEnumeratorTest) {
2558   // Test an empty directory.
2559   FileEnumerator f0(temp_dir_.GetPath(), true, FILES_AND_DIRECTORIES);
2560   EXPECT_EQ(FPL(""), f0.Next().value());
2561   EXPECT_EQ(FPL(""), f0.Next().value());
2562 
2563   // Test an empty directory, non-recursively, including "..".
2564   FileEnumerator f0_dotdot(
2565       temp_dir_.GetPath(), false,
2566       FILES_AND_DIRECTORIES | FileEnumerator::INCLUDE_DOT_DOT);
2567   EXPECT_EQ(temp_dir_.GetPath().Append(FPL("..")).value(),
2568             f0_dotdot.Next().value());
2569   EXPECT_EQ(FPL(""), f0_dotdot.Next().value());
2570 
2571   // create the directories
2572   FilePath dir1 = temp_dir_.GetPath().Append(FPL("dir1"));
2573   EXPECT_TRUE(CreateDirectory(dir1));
2574   FilePath dir2 = temp_dir_.GetPath().Append(FPL("dir2"));
2575   EXPECT_TRUE(CreateDirectory(dir2));
2576   FilePath dir2inner = dir2.Append(FPL("inner"));
2577   EXPECT_TRUE(CreateDirectory(dir2inner));
2578 
2579   // create the files
2580   FilePath dir2file = dir2.Append(FPL("dir2file.txt"));
2581   CreateTextFile(dir2file, std::wstring());
2582   FilePath dir2innerfile = dir2inner.Append(FPL("innerfile.txt"));
2583   CreateTextFile(dir2innerfile, std::wstring());
2584   FilePath file1 = temp_dir_.GetPath().Append(FPL("file1.txt"));
2585   CreateTextFile(file1, std::wstring());
2586   FilePath file2_rel = dir2.Append(FilePath::kParentDirectory)
2587       .Append(FPL("file2.txt"));
2588   CreateTextFile(file2_rel, std::wstring());
2589   FilePath file2_abs = temp_dir_.GetPath().Append(FPL("file2.txt"));
2590 
2591   // Only enumerate files.
2592   FileEnumerator f1(temp_dir_.GetPath(), true, FileEnumerator::FILES);
2593   FindResultCollector c1(&f1);
2594   EXPECT_TRUE(c1.HasFile(file1));
2595   EXPECT_TRUE(c1.HasFile(file2_abs));
2596   EXPECT_TRUE(c1.HasFile(dir2file));
2597   EXPECT_TRUE(c1.HasFile(dir2innerfile));
2598   EXPECT_EQ(4, c1.size());
2599 
2600   // Only enumerate directories.
2601   FileEnumerator f2(temp_dir_.GetPath(), true, FileEnumerator::DIRECTORIES);
2602   FindResultCollector c2(&f2);
2603   EXPECT_TRUE(c2.HasFile(dir1));
2604   EXPECT_TRUE(c2.HasFile(dir2));
2605   EXPECT_TRUE(c2.HasFile(dir2inner));
2606   EXPECT_EQ(3, c2.size());
2607 
2608   // Only enumerate directories non-recursively.
2609   FileEnumerator f2_non_recursive(temp_dir_.GetPath(), false,
2610                                   FileEnumerator::DIRECTORIES);
2611   FindResultCollector c2_non_recursive(&f2_non_recursive);
2612   EXPECT_TRUE(c2_non_recursive.HasFile(dir1));
2613   EXPECT_TRUE(c2_non_recursive.HasFile(dir2));
2614   EXPECT_EQ(2, c2_non_recursive.size());
2615 
2616   // Only enumerate directories, non-recursively, including "..".
2617   FileEnumerator f2_dotdot(
2618       temp_dir_.GetPath(), false,
2619       FileEnumerator::DIRECTORIES | FileEnumerator::INCLUDE_DOT_DOT);
2620   FindResultCollector c2_dotdot(&f2_dotdot);
2621   EXPECT_TRUE(c2_dotdot.HasFile(dir1));
2622   EXPECT_TRUE(c2_dotdot.HasFile(dir2));
2623   EXPECT_TRUE(c2_dotdot.HasFile(temp_dir_.GetPath().Append(FPL(".."))));
2624   EXPECT_EQ(3, c2_dotdot.size());
2625 
2626   // Enumerate files and directories.
2627   FileEnumerator f3(temp_dir_.GetPath(), true, FILES_AND_DIRECTORIES);
2628   FindResultCollector c3(&f3);
2629   EXPECT_TRUE(c3.HasFile(dir1));
2630   EXPECT_TRUE(c3.HasFile(dir2));
2631   EXPECT_TRUE(c3.HasFile(file1));
2632   EXPECT_TRUE(c3.HasFile(file2_abs));
2633   EXPECT_TRUE(c3.HasFile(dir2file));
2634   EXPECT_TRUE(c3.HasFile(dir2inner));
2635   EXPECT_TRUE(c3.HasFile(dir2innerfile));
2636   EXPECT_EQ(7, c3.size());
2637 
2638   // Non-recursive operation.
2639   FileEnumerator f4(temp_dir_.GetPath(), false, FILES_AND_DIRECTORIES);
2640   FindResultCollector c4(&f4);
2641   EXPECT_TRUE(c4.HasFile(dir2));
2642   EXPECT_TRUE(c4.HasFile(dir2));
2643   EXPECT_TRUE(c4.HasFile(file1));
2644   EXPECT_TRUE(c4.HasFile(file2_abs));
2645   EXPECT_EQ(4, c4.size());
2646 
2647   // Enumerate with a pattern.
2648   FileEnumerator f5(temp_dir_.GetPath(), true, FILES_AND_DIRECTORIES,
2649                     FPL("dir*"));
2650   FindResultCollector c5(&f5);
2651   EXPECT_TRUE(c5.HasFile(dir1));
2652   EXPECT_TRUE(c5.HasFile(dir2));
2653   EXPECT_TRUE(c5.HasFile(dir2file));
2654   EXPECT_TRUE(c5.HasFile(dir2inner));
2655   EXPECT_TRUE(c5.HasFile(dir2innerfile));
2656   EXPECT_EQ(5, c5.size());
2657 
2658 #if defined(OS_WIN)
2659   {
2660     // Make dir1 point to dir2.
2661     ReparsePoint reparse_point(dir1, dir2);
2662     EXPECT_TRUE(reparse_point.IsValid());
2663 
2664     // There can be a delay for the enumeration code to see the change on
2665     // the file system so skip this test for XP.
2666     // Enumerate the reparse point.
2667     FileEnumerator f6(dir1, true, FILES_AND_DIRECTORIES);
2668     FindResultCollector c6(&f6);
2669     FilePath inner2 = dir1.Append(FPL("inner"));
2670     EXPECT_TRUE(c6.HasFile(inner2));
2671     EXPECT_TRUE(c6.HasFile(inner2.Append(FPL("innerfile.txt"))));
2672     EXPECT_TRUE(c6.HasFile(dir1.Append(FPL("dir2file.txt"))));
2673     EXPECT_EQ(3, c6.size());
2674 
2675     // No changes for non recursive operation.
2676     FileEnumerator f7(temp_dir_.GetPath(), false, FILES_AND_DIRECTORIES);
2677     FindResultCollector c7(&f7);
2678     EXPECT_TRUE(c7.HasFile(dir2));
2679     EXPECT_TRUE(c7.HasFile(dir2));
2680     EXPECT_TRUE(c7.HasFile(file1));
2681     EXPECT_TRUE(c7.HasFile(file2_abs));
2682     EXPECT_EQ(4, c7.size());
2683 
2684     // Should not enumerate inside dir1 when using recursion.
2685     FileEnumerator f8(temp_dir_.GetPath(), true, FILES_AND_DIRECTORIES);
2686     FindResultCollector c8(&f8);
2687     EXPECT_TRUE(c8.HasFile(dir1));
2688     EXPECT_TRUE(c8.HasFile(dir2));
2689     EXPECT_TRUE(c8.HasFile(file1));
2690     EXPECT_TRUE(c8.HasFile(file2_abs));
2691     EXPECT_TRUE(c8.HasFile(dir2file));
2692     EXPECT_TRUE(c8.HasFile(dir2inner));
2693     EXPECT_TRUE(c8.HasFile(dir2innerfile));
2694     EXPECT_EQ(7, c8.size());
2695   }
2696 #endif
2697 
2698   // Make sure the destructor closes the find handle while in the middle of a
2699   // query to allow TearDown to delete the directory.
2700   FileEnumerator f9(temp_dir_.GetPath(), true, FILES_AND_DIRECTORIES);
2701   EXPECT_FALSE(f9.Next().value().empty());  // Should have found something
2702                                             // (we don't care what).
2703 }
2704 
TEST_F(FileUtilTest,AppendToFile)2705 TEST_F(FileUtilTest, AppendToFile) {
2706   FilePath data_dir =
2707       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("FilePathTest"));
2708 
2709   // Create a fresh, empty copy of this directory.
2710   if (PathExists(data_dir)) {
2711     ASSERT_TRUE(DeleteFile(data_dir, true));
2712   }
2713   ASSERT_TRUE(CreateDirectory(data_dir));
2714 
2715   // Create a fresh, empty copy of this directory.
2716   if (PathExists(data_dir)) {
2717     ASSERT_TRUE(DeleteFile(data_dir, true));
2718   }
2719   ASSERT_TRUE(CreateDirectory(data_dir));
2720   FilePath foobar(data_dir.Append(FILE_PATH_LITERAL("foobar.txt")));
2721 
2722   std::string data("hello");
2723   EXPECT_FALSE(AppendToFile(foobar, data.c_str(), data.size()));
2724   EXPECT_EQ(static_cast<int>(data.length()),
2725             WriteFile(foobar, data.c_str(), data.length()));
2726   EXPECT_TRUE(AppendToFile(foobar, data.c_str(), data.size()));
2727 
2728   const std::wstring read_content = ReadTextFile(foobar);
2729   EXPECT_EQ(L"hellohello", read_content);
2730 }
2731 
TEST_F(FileUtilTest,ReadFile)2732 TEST_F(FileUtilTest, ReadFile) {
2733   // Create a test file to be read.
2734   const std::string kTestData("The quick brown fox jumps over the lazy dog.");
2735   FilePath file_path =
2736       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("ReadFileTest"));
2737 
2738   ASSERT_EQ(static_cast<int>(kTestData.size()),
2739             WriteFile(file_path, kTestData.data(), kTestData.size()));
2740 
2741   // Make buffers with various size.
2742   std::vector<char> small_buffer(kTestData.size() / 2);
2743   std::vector<char> exact_buffer(kTestData.size());
2744   std::vector<char> large_buffer(kTestData.size() * 2);
2745 
2746   // Read the file with smaller buffer.
2747   int bytes_read_small = ReadFile(
2748       file_path, &small_buffer[0], static_cast<int>(small_buffer.size()));
2749   EXPECT_EQ(static_cast<int>(small_buffer.size()), bytes_read_small);
2750   EXPECT_EQ(
2751       std::string(kTestData.begin(), kTestData.begin() + small_buffer.size()),
2752       std::string(small_buffer.begin(), small_buffer.end()));
2753 
2754   // Read the file with buffer which have exactly same size.
2755   int bytes_read_exact = ReadFile(
2756       file_path, &exact_buffer[0], static_cast<int>(exact_buffer.size()));
2757   EXPECT_EQ(static_cast<int>(kTestData.size()), bytes_read_exact);
2758   EXPECT_EQ(kTestData, std::string(exact_buffer.begin(), exact_buffer.end()));
2759 
2760   // Read the file with larger buffer.
2761   int bytes_read_large = ReadFile(
2762       file_path, &large_buffer[0], static_cast<int>(large_buffer.size()));
2763   EXPECT_EQ(static_cast<int>(kTestData.size()), bytes_read_large);
2764   EXPECT_EQ(kTestData, std::string(large_buffer.begin(),
2765                                    large_buffer.begin() + kTestData.size()));
2766 
2767   // Make sure the return value is -1 if the file doesn't exist.
2768   FilePath file_path_not_exist =
2769       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("ReadFileNotExistTest"));
2770   EXPECT_EQ(-1,
2771             ReadFile(file_path_not_exist,
2772                      &exact_buffer[0],
2773                      static_cast<int>(exact_buffer.size())));
2774 }
2775 
TEST_F(FileUtilTest,ReadFileToString)2776 TEST_F(FileUtilTest, ReadFileToString) {
2777   const char kTestData[] = "0123";
2778   std::string data;
2779 
2780   FilePath file_path =
2781       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("ReadFileToStringTest"));
2782   FilePath file_path_dangerous =
2783       temp_dir_.GetPath()
2784           .Append(FILE_PATH_LITERAL(".."))
2785           .Append(temp_dir_.GetPath().BaseName())
2786           .Append(FILE_PATH_LITERAL("ReadFileToStringTest"));
2787 
2788   // Create test file.
2789   ASSERT_EQ(static_cast<int>(strlen(kTestData)),
2790             WriteFile(file_path, kTestData, strlen(kTestData)));
2791 
2792   EXPECT_TRUE(ReadFileToString(file_path, &data));
2793   EXPECT_EQ(kTestData, data);
2794 
2795   data = "temp";
2796   EXPECT_FALSE(ReadFileToStringWithMaxSize(file_path, &data, 0));
2797   EXPECT_EQ(0u, data.length());
2798 
2799   data = "temp";
2800   EXPECT_FALSE(ReadFileToStringWithMaxSize(file_path, &data, 2));
2801   EXPECT_EQ("01", data);
2802 
2803   data = "temp";
2804   EXPECT_FALSE(ReadFileToStringWithMaxSize(file_path, &data, 3));
2805   EXPECT_EQ("012", data);
2806 
2807   data = "temp";
2808   EXPECT_TRUE(ReadFileToStringWithMaxSize(file_path, &data, 4));
2809   EXPECT_EQ("0123", data);
2810 
2811   data = "temp";
2812   EXPECT_TRUE(ReadFileToStringWithMaxSize(file_path, &data, 6));
2813   EXPECT_EQ("0123", data);
2814 
2815   EXPECT_TRUE(ReadFileToStringWithMaxSize(file_path, nullptr, 6));
2816 
2817   EXPECT_TRUE(ReadFileToString(file_path, nullptr));
2818 
2819   data = "temp";
2820   EXPECT_FALSE(ReadFileToString(file_path_dangerous, &data));
2821   EXPECT_EQ(0u, data.length());
2822 
2823   // Delete test file.
2824   EXPECT_TRUE(DeleteFile(file_path, false));
2825 
2826   data = "temp";
2827   EXPECT_FALSE(ReadFileToString(file_path, &data));
2828   EXPECT_EQ(0u, data.length());
2829 
2830   data = "temp";
2831   EXPECT_FALSE(ReadFileToStringWithMaxSize(file_path, &data, 6));
2832   EXPECT_EQ(0u, data.length());
2833 }
2834 
2835 #if !defined(OS_WIN)
TEST_F(FileUtilTest,ReadFileToStringWithUnknownFileSize)2836 TEST_F(FileUtilTest, ReadFileToStringWithUnknownFileSize) {
2837   FilePath file_path("/dev/zero");
2838   std::string data = "temp";
2839 
2840   EXPECT_FALSE(ReadFileToStringWithMaxSize(file_path, &data, 0));
2841   EXPECT_EQ(0u, data.length());
2842 
2843   data = "temp";
2844   EXPECT_FALSE(ReadFileToStringWithMaxSize(file_path, &data, 2));
2845   EXPECT_EQ(std::string(2, '\0'), data);
2846 
2847   EXPECT_FALSE(ReadFileToStringWithMaxSize(file_path, nullptr, 6));
2848 
2849   // Read more than buffer size.
2850   data = "temp";
2851   EXPECT_FALSE(ReadFileToStringWithMaxSize(file_path, &data, kLargeFileSize));
2852   EXPECT_EQ(kLargeFileSize, data.length());
2853   EXPECT_EQ(std::string(kLargeFileSize, '\0'), data);
2854 
2855   EXPECT_FALSE(ReadFileToStringWithMaxSize(file_path, nullptr, kLargeFileSize));
2856 }
2857 #endif  // !defined(OS_WIN)
2858 
2859 #if !defined(OS_WIN) && !defined(OS_NACL) && !defined(OS_FUCHSIA) && \
2860     !defined(OS_IOS)
2861 #define ChildMain WriteToPipeChildMain
2862 #define ChildMainString "WriteToPipeChildMain"
2863 
MULTIPROCESS_TEST_MAIN(ChildMain)2864 MULTIPROCESS_TEST_MAIN(ChildMain) {
2865   const char kTestData[] = "0123";
2866   base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
2867   const FilePath pipe_path = command_line->GetSwitchValuePath("pipe-path");
2868 
2869   int fd = open(pipe_path.value().c_str(), O_WRONLY);
2870   CHECK_NE(-1, fd);
2871   size_t written = 0;
2872   while (written < strlen(kTestData)) {
2873     ssize_t res = write(fd, kTestData + written, strlen(kTestData) - written);
2874     if (res == -1)
2875       break;
2876     written += res;
2877   }
2878   CHECK_EQ(strlen(kTestData), written);
2879   CHECK_EQ(0, close(fd));
2880   return 0;
2881 }
2882 
2883 #define MoreThanBufferSizeChildMain WriteToPipeMoreThanBufferSizeChildMain
2884 #define MoreThanBufferSizeChildMainString \
2885   "WriteToPipeMoreThanBufferSizeChildMain"
2886 
MULTIPROCESS_TEST_MAIN(MoreThanBufferSizeChildMain)2887 MULTIPROCESS_TEST_MAIN(MoreThanBufferSizeChildMain) {
2888   std::string data(kLargeFileSize, 'c');
2889   base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
2890   const FilePath pipe_path = command_line->GetSwitchValuePath("pipe-path");
2891 
2892   int fd = open(pipe_path.value().c_str(), O_WRONLY);
2893   CHECK_NE(-1, fd);
2894 
2895   size_t written = 0;
2896   while (written < data.size()) {
2897     ssize_t res = write(fd, data.c_str() + written, data.size() - written);
2898     if (res == -1) {
2899       // We are unable to write because reading process has already read
2900       // requested number of bytes and closed pipe.
2901       break;
2902     }
2903     written += res;
2904   }
2905   CHECK_EQ(0, close(fd));
2906   return 0;
2907 }
2908 
TEST_F(FileUtilTest,ReadFileToStringWithNamedPipe)2909 TEST_F(FileUtilTest, ReadFileToStringWithNamedPipe) {
2910   FilePath pipe_path =
2911       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("test_pipe"));
2912   ASSERT_EQ(0, mkfifo(pipe_path.value().c_str(), 0600));
2913 
2914   base::CommandLine child_command_line(
2915       base::GetMultiProcessTestChildBaseCommandLine());
2916   child_command_line.AppendSwitchPath("pipe-path", pipe_path);
2917 
2918   {
2919     base::Process child_process = base::SpawnMultiProcessTestChild(
2920         ChildMainString, child_command_line, base::LaunchOptions());
2921     ASSERT_TRUE(child_process.IsValid());
2922 
2923     std::string data = "temp";
2924     EXPECT_FALSE(ReadFileToStringWithMaxSize(pipe_path, &data, 2));
2925     EXPECT_EQ("01", data);
2926 
2927     int rv = -1;
2928     ASSERT_TRUE(WaitForMultiprocessTestChildExit(
2929         child_process, TestTimeouts::action_timeout(), &rv));
2930     ASSERT_EQ(0, rv);
2931   }
2932   {
2933     base::Process child_process = base::SpawnMultiProcessTestChild(
2934         ChildMainString, child_command_line, base::LaunchOptions());
2935     ASSERT_TRUE(child_process.IsValid());
2936 
2937     std::string data = "temp";
2938     EXPECT_TRUE(ReadFileToStringWithMaxSize(pipe_path, &data, 6));
2939     EXPECT_EQ("0123", data);
2940 
2941     int rv = -1;
2942     ASSERT_TRUE(WaitForMultiprocessTestChildExit(
2943         child_process, TestTimeouts::action_timeout(), &rv));
2944     ASSERT_EQ(0, rv);
2945   }
2946   {
2947     base::Process child_process = base::SpawnMultiProcessTestChild(
2948         MoreThanBufferSizeChildMainString, child_command_line,
2949         base::LaunchOptions());
2950     ASSERT_TRUE(child_process.IsValid());
2951 
2952     std::string data = "temp";
2953     EXPECT_FALSE(ReadFileToStringWithMaxSize(pipe_path, &data, 6));
2954     EXPECT_EQ("cccccc", data);
2955 
2956     int rv = -1;
2957     ASSERT_TRUE(WaitForMultiprocessTestChildExit(
2958         child_process, TestTimeouts::action_timeout(), &rv));
2959     ASSERT_EQ(0, rv);
2960   }
2961   {
2962     base::Process child_process = base::SpawnMultiProcessTestChild(
2963         MoreThanBufferSizeChildMainString, child_command_line,
2964         base::LaunchOptions());
2965     ASSERT_TRUE(child_process.IsValid());
2966 
2967     std::string data = "temp";
2968     EXPECT_FALSE(
2969         ReadFileToStringWithMaxSize(pipe_path, &data, kLargeFileSize - 1));
2970     EXPECT_EQ(std::string(kLargeFileSize - 1, 'c'), data);
2971 
2972     int rv = -1;
2973     ASSERT_TRUE(WaitForMultiprocessTestChildExit(
2974         child_process, TestTimeouts::action_timeout(), &rv));
2975     ASSERT_EQ(0, rv);
2976   }
2977   {
2978     base::Process child_process = base::SpawnMultiProcessTestChild(
2979         MoreThanBufferSizeChildMainString, child_command_line,
2980         base::LaunchOptions());
2981     ASSERT_TRUE(child_process.IsValid());
2982 
2983     std::string data = "temp";
2984     EXPECT_TRUE(ReadFileToStringWithMaxSize(pipe_path, &data, kLargeFileSize));
2985     EXPECT_EQ(std::string(kLargeFileSize, 'c'), data);
2986 
2987     int rv = -1;
2988     ASSERT_TRUE(WaitForMultiprocessTestChildExit(
2989         child_process, TestTimeouts::action_timeout(), &rv));
2990     ASSERT_EQ(0, rv);
2991   }
2992   {
2993     base::Process child_process = base::SpawnMultiProcessTestChild(
2994         MoreThanBufferSizeChildMainString, child_command_line,
2995         base::LaunchOptions());
2996     ASSERT_TRUE(child_process.IsValid());
2997 
2998     std::string data = "temp";
2999     EXPECT_TRUE(
3000         ReadFileToStringWithMaxSize(pipe_path, &data, kLargeFileSize * 5));
3001     EXPECT_EQ(std::string(kLargeFileSize, 'c'), data);
3002 
3003     int rv = -1;
3004     ASSERT_TRUE(WaitForMultiprocessTestChildExit(
3005         child_process, TestTimeouts::action_timeout(), &rv));
3006     ASSERT_EQ(0, rv);
3007   }
3008 
3009   ASSERT_EQ(0, unlink(pipe_path.value().c_str()));
3010 }
3011 #endif  // !defined(OS_WIN) && !defined(OS_NACL) && !defined(OS_FUCHSIA) &&
3012         // !defined(OS_IOS)
3013 
3014 #if defined(OS_WIN)
3015 #define ChildMain WriteToPipeChildMain
3016 #define ChildMainString "WriteToPipeChildMain"
3017 
MULTIPROCESS_TEST_MAIN(ChildMain)3018 MULTIPROCESS_TEST_MAIN(ChildMain) {
3019   const char kTestData[] = "0123";
3020   base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
3021   const FilePath pipe_path = command_line->GetSwitchValuePath("pipe-path");
3022   std::string switch_string = command_line->GetSwitchValueASCII("sync_event");
3023   EXPECT_FALSE(switch_string.empty());
3024   unsigned int switch_uint = 0;
3025   EXPECT_TRUE(StringToUint(switch_string, &switch_uint));
3026   win::ScopedHandle sync_event(win::Uint32ToHandle(switch_uint));
3027 
3028   HANDLE ph = CreateNamedPipe(pipe_path.value().c_str(), PIPE_ACCESS_OUTBOUND,
3029                               PIPE_WAIT, 1, 0, 0, 0, NULL);
3030   EXPECT_NE(ph, INVALID_HANDLE_VALUE);
3031   EXPECT_TRUE(SetEvent(sync_event.Get()));
3032   EXPECT_TRUE(ConnectNamedPipe(ph, NULL));
3033 
3034   DWORD written;
3035   EXPECT_TRUE(::WriteFile(ph, kTestData, strlen(kTestData), &written, NULL));
3036   EXPECT_EQ(strlen(kTestData), written);
3037   CloseHandle(ph);
3038   return 0;
3039 }
3040 
3041 #define MoreThanBufferSizeChildMain WriteToPipeMoreThanBufferSizeChildMain
3042 #define MoreThanBufferSizeChildMainString \
3043   "WriteToPipeMoreThanBufferSizeChildMain"
3044 
MULTIPROCESS_TEST_MAIN(MoreThanBufferSizeChildMain)3045 MULTIPROCESS_TEST_MAIN(MoreThanBufferSizeChildMain) {
3046   std::string data(kLargeFileSize, 'c');
3047   base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
3048   const FilePath pipe_path = command_line->GetSwitchValuePath("pipe-path");
3049   std::string switch_string = command_line->GetSwitchValueASCII("sync_event");
3050   EXPECT_FALSE(switch_string.empty());
3051   unsigned int switch_uint = 0;
3052   EXPECT_TRUE(StringToUint(switch_string, &switch_uint));
3053   win::ScopedHandle sync_event(win::Uint32ToHandle(switch_uint));
3054 
3055   HANDLE ph = CreateNamedPipe(pipe_path.value().c_str(), PIPE_ACCESS_OUTBOUND,
3056                               PIPE_WAIT, 1, data.size(), data.size(), 0, NULL);
3057   EXPECT_NE(ph, INVALID_HANDLE_VALUE);
3058   EXPECT_TRUE(SetEvent(sync_event.Get()));
3059   EXPECT_TRUE(ConnectNamedPipe(ph, NULL));
3060 
3061   DWORD written;
3062   EXPECT_TRUE(::WriteFile(ph, data.c_str(), data.size(), &written, NULL));
3063   EXPECT_EQ(data.size(), written);
3064   CloseHandle(ph);
3065   return 0;
3066 }
3067 
TEST_F(FileUtilTest,ReadFileToStringWithNamedPipe)3068 TEST_F(FileUtilTest, ReadFileToStringWithNamedPipe) {
3069   FilePath pipe_path(FILE_PATH_LITERAL("\\\\.\\pipe\\test_pipe"));
3070   win::ScopedHandle sync_event(CreateEvent(0, false, false, nullptr));
3071 
3072   base::CommandLine child_command_line(
3073       base::GetMultiProcessTestChildBaseCommandLine());
3074   child_command_line.AppendSwitchPath("pipe-path", pipe_path);
3075   child_command_line.AppendSwitchASCII(
3076       "sync_event", UintToString(win::HandleToUint32(sync_event.Get())));
3077 
3078   base::LaunchOptions options;
3079   options.handles_to_inherit.push_back(sync_event.Get());
3080 
3081   {
3082     base::Process child_process = base::SpawnMultiProcessTestChild(
3083         ChildMainString, child_command_line, options);
3084     ASSERT_TRUE(child_process.IsValid());
3085     // Wait for pipe creation in child process.
3086     EXPECT_EQ(WAIT_OBJECT_0, WaitForSingleObject(sync_event.Get(), INFINITE));
3087 
3088     std::string data = "temp";
3089     EXPECT_FALSE(ReadFileToStringWithMaxSize(pipe_path, &data, 2));
3090     EXPECT_EQ("01", data);
3091 
3092     int rv = -1;
3093     ASSERT_TRUE(WaitForMultiprocessTestChildExit(
3094         child_process, TestTimeouts::action_timeout(), &rv));
3095     ASSERT_EQ(0, rv);
3096   }
3097   {
3098     base::Process child_process = base::SpawnMultiProcessTestChild(
3099         ChildMainString, child_command_line, options);
3100     ASSERT_TRUE(child_process.IsValid());
3101     // Wait for pipe creation in child process.
3102     EXPECT_EQ(WAIT_OBJECT_0, WaitForSingleObject(sync_event.Get(), INFINITE));
3103 
3104     std::string data = "temp";
3105     EXPECT_TRUE(ReadFileToStringWithMaxSize(pipe_path, &data, 6));
3106     EXPECT_EQ("0123", data);
3107 
3108     int rv = -1;
3109     ASSERT_TRUE(WaitForMultiprocessTestChildExit(
3110         child_process, TestTimeouts::action_timeout(), &rv));
3111     ASSERT_EQ(0, rv);
3112   }
3113   {
3114     base::Process child_process = base::SpawnMultiProcessTestChild(
3115         MoreThanBufferSizeChildMainString, child_command_line, options);
3116     ASSERT_TRUE(child_process.IsValid());
3117     // Wait for pipe creation in child process.
3118     EXPECT_EQ(WAIT_OBJECT_0, WaitForSingleObject(sync_event.Get(), INFINITE));
3119 
3120     std::string data = "temp";
3121     EXPECT_FALSE(ReadFileToStringWithMaxSize(pipe_path, &data, 6));
3122     EXPECT_EQ("cccccc", data);
3123 
3124     int rv = -1;
3125     ASSERT_TRUE(WaitForMultiprocessTestChildExit(
3126         child_process, TestTimeouts::action_timeout(), &rv));
3127     ASSERT_EQ(0, rv);
3128   }
3129   {
3130     base::Process child_process = base::SpawnMultiProcessTestChild(
3131         MoreThanBufferSizeChildMainString, child_command_line, options);
3132     ASSERT_TRUE(child_process.IsValid());
3133     // Wait for pipe creation in child process.
3134     EXPECT_EQ(WAIT_OBJECT_0, WaitForSingleObject(sync_event.Get(), INFINITE));
3135 
3136     std::string data = "temp";
3137     EXPECT_FALSE(
3138         ReadFileToStringWithMaxSize(pipe_path, &data, kLargeFileSize - 1));
3139     EXPECT_EQ(std::string(kLargeFileSize - 1, 'c'), data);
3140 
3141     int rv = -1;
3142     ASSERT_TRUE(WaitForMultiprocessTestChildExit(
3143         child_process, TestTimeouts::action_timeout(), &rv));
3144     ASSERT_EQ(0, rv);
3145   }
3146   {
3147     base::Process child_process = base::SpawnMultiProcessTestChild(
3148         MoreThanBufferSizeChildMainString, child_command_line, options);
3149     ASSERT_TRUE(child_process.IsValid());
3150     // Wait for pipe creation in child process.
3151     EXPECT_EQ(WAIT_OBJECT_0, WaitForSingleObject(sync_event.Get(), INFINITE));
3152 
3153     std::string data = "temp";
3154     EXPECT_TRUE(ReadFileToStringWithMaxSize(pipe_path, &data, kLargeFileSize));
3155     EXPECT_EQ(std::string(kLargeFileSize, 'c'), data);
3156 
3157     int rv = -1;
3158     ASSERT_TRUE(WaitForMultiprocessTestChildExit(
3159         child_process, TestTimeouts::action_timeout(), &rv));
3160     ASSERT_EQ(0, rv);
3161   }
3162   {
3163     base::Process child_process = base::SpawnMultiProcessTestChild(
3164         MoreThanBufferSizeChildMainString, child_command_line, options);
3165     ASSERT_TRUE(child_process.IsValid());
3166     // Wait for pipe creation in child process.
3167     EXPECT_EQ(WAIT_OBJECT_0, WaitForSingleObject(sync_event.Get(), INFINITE));
3168 
3169     std::string data = "temp";
3170     EXPECT_TRUE(
3171         ReadFileToStringWithMaxSize(pipe_path, &data, kLargeFileSize * 5));
3172     EXPECT_EQ(std::string(kLargeFileSize, 'c'), data);
3173 
3174     int rv = -1;
3175     ASSERT_TRUE(WaitForMultiprocessTestChildExit(
3176         child_process, TestTimeouts::action_timeout(), &rv));
3177     ASSERT_EQ(0, rv);
3178   }
3179 }
3180 #endif  // defined(OS_WIN)
3181 
3182 #if defined(OS_POSIX) && !defined(OS_MACOSX)
TEST_F(FileUtilTest,ReadFileToStringWithProcFileSystem)3183 TEST_F(FileUtilTest, ReadFileToStringWithProcFileSystem) {
3184   FilePath file_path("/proc/cpuinfo");
3185   std::string data = "temp";
3186 
3187   EXPECT_FALSE(ReadFileToStringWithMaxSize(file_path, &data, 0));
3188   EXPECT_EQ(0u, data.length());
3189 
3190   data = "temp";
3191   EXPECT_FALSE(ReadFileToStringWithMaxSize(file_path, &data, 2));
3192   EXPECT_TRUE(EqualsCaseInsensitiveASCII("pr", data));
3193 
3194   data = "temp";
3195   EXPECT_FALSE(ReadFileToStringWithMaxSize(file_path, &data, 4));
3196   EXPECT_TRUE(EqualsCaseInsensitiveASCII("proc", data));
3197 
3198   EXPECT_FALSE(ReadFileToStringWithMaxSize(file_path, nullptr, 4));
3199 }
3200 #endif  // defined(OS_POSIX) && !defined(OS_MACOSX)
3201 
TEST_F(FileUtilTest,ReadFileToStringWithLargeFile)3202 TEST_F(FileUtilTest, ReadFileToStringWithLargeFile) {
3203   std::string data(kLargeFileSize, 'c');
3204 
3205   FilePath file_path =
3206       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("ReadFileToStringTest"));
3207 
3208   // Create test file.
3209   ASSERT_EQ(static_cast<int>(kLargeFileSize),
3210             WriteFile(file_path, data.c_str(), kLargeFileSize));
3211 
3212   std::string actual_data = "temp";
3213   EXPECT_TRUE(ReadFileToString(file_path, &actual_data));
3214   EXPECT_EQ(data, actual_data);
3215 
3216   actual_data = "temp";
3217   EXPECT_FALSE(ReadFileToStringWithMaxSize(file_path, &actual_data, 0));
3218   EXPECT_EQ(0u, actual_data.length());
3219 
3220   // Read more than buffer size.
3221   actual_data = "temp";
3222   EXPECT_FALSE(
3223       ReadFileToStringWithMaxSize(file_path, &actual_data, kLargeFileSize - 1));
3224   EXPECT_EQ(std::string(kLargeFileSize - 1, 'c'), actual_data);
3225 }
3226 
TEST_F(FileUtilTest,TouchFile)3227 TEST_F(FileUtilTest, TouchFile) {
3228   FilePath data_dir =
3229       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("FilePathTest"));
3230 
3231   // Create a fresh, empty copy of this directory.
3232   if (PathExists(data_dir)) {
3233     ASSERT_TRUE(DeleteFile(data_dir, true));
3234   }
3235   ASSERT_TRUE(CreateDirectory(data_dir));
3236 
3237   FilePath foobar(data_dir.Append(FILE_PATH_LITERAL("foobar.txt")));
3238   std::string data("hello");
3239   ASSERT_EQ(static_cast<int>(data.length()),
3240             WriteFile(foobar, data.c_str(), data.length()));
3241 
3242   Time access_time;
3243   // This timestamp is divisible by one day (in local timezone),
3244   // to make it work on FAT too.
3245   ASSERT_TRUE(Time::FromString("Wed, 16 Nov 1994, 00:00:00",
3246                                &access_time));
3247 
3248   Time modification_time;
3249   // Note that this timestamp is divisible by two (seconds) - FAT stores
3250   // modification times with 2s resolution.
3251   ASSERT_TRUE(Time::FromString("Tue, 15 Nov 1994, 12:45:26 GMT",
3252               &modification_time));
3253 
3254   ASSERT_TRUE(TouchFile(foobar, access_time, modification_time));
3255   File::Info file_info;
3256   ASSERT_TRUE(GetFileInfo(foobar, &file_info));
3257 #if !defined(OS_FUCHSIA)
3258   // Access time is not supported on Fuchsia, see https://crbug.com/735233.
3259   EXPECT_EQ(access_time.ToInternalValue(),
3260             file_info.last_accessed.ToInternalValue());
3261 #endif
3262   EXPECT_EQ(modification_time.ToInternalValue(),
3263             file_info.last_modified.ToInternalValue());
3264 }
3265 
TEST_F(FileUtilTest,IsDirectoryEmpty)3266 TEST_F(FileUtilTest, IsDirectoryEmpty) {
3267   FilePath empty_dir =
3268       temp_dir_.GetPath().Append(FILE_PATH_LITERAL("EmptyDir"));
3269 
3270   ASSERT_FALSE(PathExists(empty_dir));
3271 
3272   ASSERT_TRUE(CreateDirectory(empty_dir));
3273 
3274   EXPECT_TRUE(IsDirectoryEmpty(empty_dir));
3275 
3276   FilePath foo(empty_dir.Append(FILE_PATH_LITERAL("foo.txt")));
3277   std::string bar("baz");
3278   ASSERT_EQ(static_cast<int>(bar.length()),
3279             WriteFile(foo, bar.c_str(), bar.length()));
3280 
3281   EXPECT_FALSE(IsDirectoryEmpty(empty_dir));
3282 }
3283 
3284 #if defined(OS_POSIX) || defined(OS_FUCHSIA)
3285 
TEST_F(FileUtilTest,SetNonBlocking)3286 TEST_F(FileUtilTest, SetNonBlocking) {
3287   const int kInvalidFd = 99999;
3288   EXPECT_FALSE(SetNonBlocking(kInvalidFd));
3289 
3290   base::FilePath path;
3291   ASSERT_TRUE(PathService::Get(base::DIR_TEST_DATA, &path));
3292   path = path.Append(FPL("file_util")).Append(FPL("original.txt"));
3293   ScopedFD fd(open(path.value().c_str(), O_RDONLY));
3294   ASSERT_GE(fd.get(), 0);
3295   EXPECT_TRUE(SetNonBlocking(fd.get()));
3296 }
3297 
TEST_F(FileUtilTest,SetCloseOnExec)3298 TEST_F(FileUtilTest, SetCloseOnExec) {
3299   const int kInvalidFd = 99999;
3300   EXPECT_FALSE(SetCloseOnExec(kInvalidFd));
3301 
3302   base::FilePath path;
3303   ASSERT_TRUE(PathService::Get(base::DIR_TEST_DATA, &path));
3304   path = path.Append(FPL("file_util")).Append(FPL("original.txt"));
3305   ScopedFD fd(open(path.value().c_str(), O_RDONLY));
3306   ASSERT_GE(fd.get(), 0);
3307   EXPECT_TRUE(SetCloseOnExec(fd.get()));
3308 }
3309 
3310 #endif
3311 
3312 #if defined(OS_POSIX)
3313 
3314 // Testing VerifyPathControlledByAdmin() is hard, because there is no
3315 // way a test can make a file owned by root, or change file paths
3316 // at the root of the file system.  VerifyPathControlledByAdmin()
3317 // is implemented as a call to VerifyPathControlledByUser, which gives
3318 // us the ability to test with paths under the test's temp directory,
3319 // using a user id we control.
3320 // Pull tests of VerifyPathControlledByUserTest() into a separate test class
3321 // with a common SetUp() method.
3322 class VerifyPathControlledByUserTest : public FileUtilTest {
3323  protected:
SetUp()3324   void SetUp() override {
3325     FileUtilTest::SetUp();
3326 
3327     // Create a basic structure used by each test.
3328     // base_dir_
3329     //  |-> sub_dir_
3330     //       |-> text_file_
3331 
3332     base_dir_ = temp_dir_.GetPath().AppendASCII("base_dir");
3333     ASSERT_TRUE(CreateDirectory(base_dir_));
3334 
3335     sub_dir_ = base_dir_.AppendASCII("sub_dir");
3336     ASSERT_TRUE(CreateDirectory(sub_dir_));
3337 
3338     text_file_ = sub_dir_.AppendASCII("file.txt");
3339     CreateTextFile(text_file_, L"This text file has some text in it.");
3340 
3341     // Get the user and group files are created with from |base_dir_|.
3342     struct stat stat_buf;
3343     ASSERT_EQ(0, stat(base_dir_.value().c_str(), &stat_buf));
3344     uid_ = stat_buf.st_uid;
3345     ok_gids_.insert(stat_buf.st_gid);
3346     bad_gids_.insert(stat_buf.st_gid + 1);
3347 
3348     ASSERT_EQ(uid_, getuid());  // This process should be the owner.
3349 
3350     // To ensure that umask settings do not cause the initial state
3351     // of permissions to be different from what we expect, explicitly
3352     // set permissions on the directories we create.
3353     // Make all files and directories non-world-writable.
3354 
3355     // Users and group can read, write, traverse
3356     int enabled_permissions =
3357         FILE_PERMISSION_USER_MASK | FILE_PERMISSION_GROUP_MASK;
3358     // Other users can't read, write, traverse
3359     int disabled_permissions = FILE_PERMISSION_OTHERS_MASK;
3360 
3361     ASSERT_NO_FATAL_FAILURE(
3362         ChangePosixFilePermissions(
3363             base_dir_, enabled_permissions, disabled_permissions));
3364     ASSERT_NO_FATAL_FAILURE(
3365         ChangePosixFilePermissions(
3366             sub_dir_, enabled_permissions, disabled_permissions));
3367   }
3368 
3369   FilePath base_dir_;
3370   FilePath sub_dir_;
3371   FilePath text_file_;
3372   uid_t uid_;
3373 
3374   std::set<gid_t> ok_gids_;
3375   std::set<gid_t> bad_gids_;
3376 };
3377 
TEST_F(VerifyPathControlledByUserTest,BadPaths)3378 TEST_F(VerifyPathControlledByUserTest, BadPaths) {
3379   // File does not exist.
3380   FilePath does_not_exist = base_dir_.AppendASCII("does")
3381                                      .AppendASCII("not")
3382                                      .AppendASCII("exist");
3383   EXPECT_FALSE(
3384       VerifyPathControlledByUser(base_dir_, does_not_exist, uid_, ok_gids_));
3385 
3386   // |base| not a subpath of |path|.
3387   EXPECT_FALSE(VerifyPathControlledByUser(sub_dir_, base_dir_, uid_, ok_gids_));
3388 
3389   // An empty base path will fail to be a prefix for any path.
3390   FilePath empty;
3391   EXPECT_FALSE(VerifyPathControlledByUser(empty, base_dir_, uid_, ok_gids_));
3392 
3393   // Finding that a bad call fails proves nothing unless a good call succeeds.
3394   EXPECT_TRUE(VerifyPathControlledByUser(base_dir_, sub_dir_, uid_, ok_gids_));
3395 }
3396 
TEST_F(VerifyPathControlledByUserTest,Symlinks)3397 TEST_F(VerifyPathControlledByUserTest, Symlinks) {
3398   // Symlinks in the path should cause failure.
3399 
3400   // Symlink to the file at the end of the path.
3401   FilePath file_link =  base_dir_.AppendASCII("file_link");
3402   ASSERT_TRUE(CreateSymbolicLink(text_file_, file_link))
3403       << "Failed to create symlink.";
3404 
3405   EXPECT_FALSE(
3406       VerifyPathControlledByUser(base_dir_, file_link, uid_, ok_gids_));
3407   EXPECT_FALSE(
3408       VerifyPathControlledByUser(file_link, file_link, uid_, ok_gids_));
3409 
3410   // Symlink from one directory to another within the path.
3411   FilePath link_to_sub_dir =  base_dir_.AppendASCII("link_to_sub_dir");
3412   ASSERT_TRUE(CreateSymbolicLink(sub_dir_, link_to_sub_dir))
3413     << "Failed to create symlink.";
3414 
3415   FilePath file_path_with_link = link_to_sub_dir.AppendASCII("file.txt");
3416   ASSERT_TRUE(PathExists(file_path_with_link));
3417 
3418   EXPECT_FALSE(VerifyPathControlledByUser(base_dir_, file_path_with_link, uid_,
3419                                           ok_gids_));
3420 
3421   EXPECT_FALSE(VerifyPathControlledByUser(link_to_sub_dir, file_path_with_link,
3422                                           uid_, ok_gids_));
3423 
3424   // Symlinks in parents of base path are allowed.
3425   EXPECT_TRUE(VerifyPathControlledByUser(file_path_with_link,
3426                                          file_path_with_link, uid_, ok_gids_));
3427 }
3428 
TEST_F(VerifyPathControlledByUserTest,OwnershipChecks)3429 TEST_F(VerifyPathControlledByUserTest, OwnershipChecks) {
3430   // Get a uid that is not the uid of files we create.
3431   uid_t bad_uid = uid_ + 1;
3432 
3433   // Make all files and directories non-world-writable.
3434   ASSERT_NO_FATAL_FAILURE(
3435       ChangePosixFilePermissions(base_dir_, 0u, S_IWOTH));
3436   ASSERT_NO_FATAL_FAILURE(
3437       ChangePosixFilePermissions(sub_dir_, 0u, S_IWOTH));
3438   ASSERT_NO_FATAL_FAILURE(
3439       ChangePosixFilePermissions(text_file_, 0u, S_IWOTH));
3440 
3441   // We control these paths.
3442   EXPECT_TRUE(VerifyPathControlledByUser(base_dir_, sub_dir_, uid_, ok_gids_));
3443   EXPECT_TRUE(
3444       VerifyPathControlledByUser(base_dir_, text_file_, uid_, ok_gids_));
3445   EXPECT_TRUE(VerifyPathControlledByUser(sub_dir_, text_file_, uid_, ok_gids_));
3446 
3447   // Another user does not control these paths.
3448   EXPECT_FALSE(
3449       VerifyPathControlledByUser(base_dir_, sub_dir_, bad_uid, ok_gids_));
3450   EXPECT_FALSE(
3451       VerifyPathControlledByUser(base_dir_, text_file_, bad_uid, ok_gids_));
3452   EXPECT_FALSE(
3453       VerifyPathControlledByUser(sub_dir_, text_file_, bad_uid, ok_gids_));
3454 
3455   // Another group does not control the paths.
3456   EXPECT_FALSE(
3457       VerifyPathControlledByUser(base_dir_, sub_dir_, uid_, bad_gids_));
3458   EXPECT_FALSE(
3459       VerifyPathControlledByUser(base_dir_, text_file_, uid_, bad_gids_));
3460   EXPECT_FALSE(
3461       VerifyPathControlledByUser(sub_dir_, text_file_, uid_, bad_gids_));
3462 }
3463 
TEST_F(VerifyPathControlledByUserTest,GroupWriteTest)3464 TEST_F(VerifyPathControlledByUserTest, GroupWriteTest) {
3465   // Make all files and directories writable only by their owner.
3466   ASSERT_NO_FATAL_FAILURE(
3467       ChangePosixFilePermissions(base_dir_, 0u, S_IWOTH|S_IWGRP));
3468   ASSERT_NO_FATAL_FAILURE(
3469       ChangePosixFilePermissions(sub_dir_, 0u, S_IWOTH|S_IWGRP));
3470   ASSERT_NO_FATAL_FAILURE(
3471       ChangePosixFilePermissions(text_file_, 0u, S_IWOTH|S_IWGRP));
3472 
3473   // Any group is okay because the path is not group-writable.
3474   EXPECT_TRUE(VerifyPathControlledByUser(base_dir_, sub_dir_, uid_, ok_gids_));
3475   EXPECT_TRUE(
3476       VerifyPathControlledByUser(base_dir_, text_file_, uid_, ok_gids_));
3477   EXPECT_TRUE(VerifyPathControlledByUser(sub_dir_, text_file_, uid_, ok_gids_));
3478 
3479   EXPECT_TRUE(VerifyPathControlledByUser(base_dir_, sub_dir_, uid_, bad_gids_));
3480   EXPECT_TRUE(
3481       VerifyPathControlledByUser(base_dir_, text_file_, uid_, bad_gids_));
3482   EXPECT_TRUE(
3483       VerifyPathControlledByUser(sub_dir_, text_file_, uid_, bad_gids_));
3484 
3485   // No group is okay, because we don't check the group
3486   // if no group can write.
3487   std::set<gid_t> no_gids;  // Empty set of gids.
3488   EXPECT_TRUE(VerifyPathControlledByUser(base_dir_, sub_dir_, uid_, no_gids));
3489   EXPECT_TRUE(VerifyPathControlledByUser(base_dir_, text_file_, uid_, no_gids));
3490   EXPECT_TRUE(VerifyPathControlledByUser(sub_dir_, text_file_, uid_, no_gids));
3491 
3492   // Make all files and directories writable by their group.
3493   ASSERT_NO_FATAL_FAILURE(ChangePosixFilePermissions(base_dir_, S_IWGRP, 0u));
3494   ASSERT_NO_FATAL_FAILURE(ChangePosixFilePermissions(sub_dir_, S_IWGRP, 0u));
3495   ASSERT_NO_FATAL_FAILURE(ChangePosixFilePermissions(text_file_, S_IWGRP, 0u));
3496 
3497   // Now |ok_gids_| works, but |bad_gids_| fails.
3498   EXPECT_TRUE(VerifyPathControlledByUser(base_dir_, sub_dir_, uid_, ok_gids_));
3499   EXPECT_TRUE(
3500       VerifyPathControlledByUser(base_dir_, text_file_, uid_, ok_gids_));
3501   EXPECT_TRUE(VerifyPathControlledByUser(sub_dir_, text_file_, uid_, ok_gids_));
3502 
3503   EXPECT_FALSE(
3504       VerifyPathControlledByUser(base_dir_, sub_dir_, uid_, bad_gids_));
3505   EXPECT_FALSE(
3506       VerifyPathControlledByUser(base_dir_, text_file_, uid_, bad_gids_));
3507   EXPECT_FALSE(
3508       VerifyPathControlledByUser(sub_dir_, text_file_, uid_, bad_gids_));
3509 
3510   // Because any group in the group set is allowed,
3511   // the union of good and bad gids passes.
3512 
3513   std::set<gid_t> multiple_gids;
3514   std::set_union(
3515       ok_gids_.begin(), ok_gids_.end(),
3516       bad_gids_.begin(), bad_gids_.end(),
3517       std::inserter(multiple_gids, multiple_gids.begin()));
3518 
3519   EXPECT_TRUE(
3520       VerifyPathControlledByUser(base_dir_, sub_dir_, uid_, multiple_gids));
3521   EXPECT_TRUE(
3522       VerifyPathControlledByUser(base_dir_, text_file_, uid_, multiple_gids));
3523   EXPECT_TRUE(
3524       VerifyPathControlledByUser(sub_dir_, text_file_, uid_, multiple_gids));
3525 }
3526 
TEST_F(VerifyPathControlledByUserTest,WriteBitChecks)3527 TEST_F(VerifyPathControlledByUserTest, WriteBitChecks) {
3528   // Make all files and directories non-world-writable.
3529   ASSERT_NO_FATAL_FAILURE(
3530       ChangePosixFilePermissions(base_dir_, 0u, S_IWOTH));
3531   ASSERT_NO_FATAL_FAILURE(
3532       ChangePosixFilePermissions(sub_dir_, 0u, S_IWOTH));
3533   ASSERT_NO_FATAL_FAILURE(
3534       ChangePosixFilePermissions(text_file_, 0u, S_IWOTH));
3535 
3536   // Initialy, we control all parts of the path.
3537   EXPECT_TRUE(VerifyPathControlledByUser(base_dir_, sub_dir_, uid_, ok_gids_));
3538   EXPECT_TRUE(
3539       VerifyPathControlledByUser(base_dir_, text_file_, uid_, ok_gids_));
3540   EXPECT_TRUE(VerifyPathControlledByUser(sub_dir_, text_file_, uid_, ok_gids_));
3541 
3542   // Make base_dir_ world-writable.
3543   ASSERT_NO_FATAL_FAILURE(
3544       ChangePosixFilePermissions(base_dir_, S_IWOTH, 0u));
3545   EXPECT_FALSE(VerifyPathControlledByUser(base_dir_, sub_dir_, uid_, ok_gids_));
3546   EXPECT_FALSE(
3547       VerifyPathControlledByUser(base_dir_, text_file_, uid_, ok_gids_));
3548   EXPECT_TRUE(VerifyPathControlledByUser(sub_dir_, text_file_, uid_, ok_gids_));
3549 
3550   // Make sub_dir_ world writable.
3551   ASSERT_NO_FATAL_FAILURE(
3552       ChangePosixFilePermissions(sub_dir_, S_IWOTH, 0u));
3553   EXPECT_FALSE(VerifyPathControlledByUser(base_dir_, sub_dir_, uid_, ok_gids_));
3554   EXPECT_FALSE(
3555       VerifyPathControlledByUser(base_dir_, text_file_, uid_, ok_gids_));
3556   EXPECT_FALSE(
3557       VerifyPathControlledByUser(sub_dir_, text_file_, uid_, ok_gids_));
3558 
3559   // Make text_file_ world writable.
3560   ASSERT_NO_FATAL_FAILURE(
3561       ChangePosixFilePermissions(text_file_, S_IWOTH, 0u));
3562   EXPECT_FALSE(VerifyPathControlledByUser(base_dir_, sub_dir_, uid_, ok_gids_));
3563   EXPECT_FALSE(
3564       VerifyPathControlledByUser(base_dir_, text_file_, uid_, ok_gids_));
3565   EXPECT_FALSE(
3566       VerifyPathControlledByUser(sub_dir_, text_file_, uid_, ok_gids_));
3567 
3568   // Make sub_dir_ non-world writable.
3569   ASSERT_NO_FATAL_FAILURE(
3570       ChangePosixFilePermissions(sub_dir_, 0u, S_IWOTH));
3571   EXPECT_FALSE(VerifyPathControlledByUser(base_dir_, sub_dir_, uid_, ok_gids_));
3572   EXPECT_FALSE(
3573       VerifyPathControlledByUser(base_dir_, text_file_, uid_, ok_gids_));
3574   EXPECT_FALSE(
3575       VerifyPathControlledByUser(sub_dir_, text_file_, uid_, ok_gids_));
3576 
3577   // Make base_dir_ non-world-writable.
3578   ASSERT_NO_FATAL_FAILURE(
3579       ChangePosixFilePermissions(base_dir_, 0u, S_IWOTH));
3580   EXPECT_TRUE(VerifyPathControlledByUser(base_dir_, sub_dir_, uid_, ok_gids_));
3581   EXPECT_FALSE(
3582       VerifyPathControlledByUser(base_dir_, text_file_, uid_, ok_gids_));
3583   EXPECT_FALSE(
3584       VerifyPathControlledByUser(sub_dir_, text_file_, uid_, ok_gids_));
3585 
3586   // Back to the initial state: Nothing is writable, so every path
3587   // should pass.
3588   ASSERT_NO_FATAL_FAILURE(
3589       ChangePosixFilePermissions(text_file_, 0u, S_IWOTH));
3590   EXPECT_TRUE(VerifyPathControlledByUser(base_dir_, sub_dir_, uid_, ok_gids_));
3591   EXPECT_TRUE(
3592       VerifyPathControlledByUser(base_dir_, text_file_, uid_, ok_gids_));
3593   EXPECT_TRUE(VerifyPathControlledByUser(sub_dir_, text_file_, uid_, ok_gids_));
3594 }
3595 
3596 #endif  // defined(OS_POSIX)
3597 
3598 #if defined(OS_ANDROID)
TEST_F(FileUtilTest,ValidContentUriTest)3599 TEST_F(FileUtilTest, ValidContentUriTest) {
3600   // Get the test image path.
3601   FilePath data_dir;
3602   ASSERT_TRUE(PathService::Get(DIR_TEST_DATA, &data_dir));
3603   data_dir = data_dir.AppendASCII("file_util");
3604   ASSERT_TRUE(PathExists(data_dir));
3605   FilePath image_file = data_dir.Append(FILE_PATH_LITERAL("red.png"));
3606   int64_t image_size;
3607   GetFileSize(image_file, &image_size);
3608   ASSERT_GT(image_size, 0);
3609 
3610   // Insert the image into MediaStore. MediaStore will do some conversions, and
3611   // return the content URI.
3612   FilePath path = InsertImageIntoMediaStore(image_file);
3613   EXPECT_TRUE(path.IsContentUri());
3614   EXPECT_TRUE(PathExists(path));
3615   // The file size may not equal to the input image as MediaStore may convert
3616   // the image.
3617   int64_t content_uri_size;
3618   GetFileSize(path, &content_uri_size);
3619   EXPECT_EQ(image_size, content_uri_size);
3620 
3621   // We should be able to read the file.
3622   File file = OpenContentUriForRead(path);
3623   EXPECT_TRUE(file.IsValid());
3624   auto buffer = std::make_unique<char[]>(image_size);
3625   EXPECT_TRUE(file.ReadAtCurrentPos(buffer.get(), image_size));
3626 }
3627 
TEST_F(FileUtilTest,NonExistentContentUriTest)3628 TEST_F(FileUtilTest, NonExistentContentUriTest) {
3629   FilePath path("content://foo.bar");
3630   EXPECT_TRUE(path.IsContentUri());
3631   EXPECT_FALSE(PathExists(path));
3632   // Size should be smaller than 0.
3633   int64_t size;
3634   EXPECT_FALSE(GetFileSize(path, &size));
3635 
3636   // We should not be able to read the file.
3637   File file = OpenContentUriForRead(path);
3638   EXPECT_FALSE(file.IsValid());
3639 }
3640 #endif
3641 
3642 // Test that temp files obtained racily are all unique (no interference between
3643 // threads). Mimics file operations in DoLaunchChildTestProcess() to rule out
3644 // thread-safety issues @ https://crbug.com/826408#c17.
3645 #if defined(OS_FUCHSIA)
3646 // TODO(crbug.com/844416): Too slow to run on infra due to QEMU overloads.
3647 #define MAYBE_MultiThreadedTempFiles DISABLED_MultiThreadedTempFiles
3648 #else
3649 #define MAYBE_MultiThreadedTempFiles MultiThreadedTempFiles
3650 #endif
TEST(FileUtilMultiThreadedTest,MAYBE_MultiThreadedTempFiles)3651 TEST(FileUtilMultiThreadedTest, MAYBE_MultiThreadedTempFiles) {
3652   constexpr int kNumThreads = 64;
3653   constexpr int kNumWritesPerThread = 32;
3654 
3655   std::unique_ptr<Thread> threads[kNumThreads];
3656   for (auto& thread : threads) {
3657     thread = std::make_unique<Thread>("test worker");
3658     thread->Start();
3659   }
3660 
3661   // Wait until all threads are started for max parallelism.
3662   for (auto& thread : threads)
3663     thread->WaitUntilThreadStarted();
3664 
3665   const RepeatingClosure open_write_close_read = BindRepeating([]() {
3666     FilePath output_filename;
3667     ScopedFILE output_file(CreateAndOpenTemporaryFile(&output_filename));
3668     EXPECT_TRUE(output_file);
3669 
3670     const std::string content = GenerateGUID();
3671 #if defined(OS_WIN)
3672     HANDLE handle =
3673         reinterpret_cast<HANDLE>(_get_osfhandle(_fileno(output_file.get())));
3674     DWORD bytes_written = 0;
3675     ::WriteFile(handle, content.c_str(), content.length(), &bytes_written,
3676                 NULL);
3677 #else
3678     size_t bytes_written =
3679         ::write(::fileno(output_file.get()), content.c_str(), content.length());
3680 #endif
3681     EXPECT_EQ(content.length(), bytes_written);
3682     ::fflush(output_file.get());
3683     output_file.reset();
3684 
3685     std::string output_file_contents;
3686     EXPECT_TRUE(ReadFileToString(output_filename, &output_file_contents))
3687         << output_filename;
3688 
3689     EXPECT_EQ(content, output_file_contents);
3690 
3691     DeleteFile(output_filename, false);
3692   });
3693 
3694   // Post tasks to each thread in a round-robin fashion to ensure as much
3695   // parallelism as possible.
3696   for (int i = 0; i < kNumWritesPerThread; ++i) {
3697     for (auto& thread : threads) {
3698       thread->task_runner()->PostTask(FROM_HERE, open_write_close_read);
3699     }
3700   }
3701 
3702   for (auto& thread : threads)
3703     thread->Stop();
3704 }
3705 
3706 #if defined(OS_POSIX) || defined(OS_FUCHSIA)
3707 
TEST(ScopedFD,ScopedFDDoesClose)3708 TEST(ScopedFD, ScopedFDDoesClose) {
3709   int fds[2];
3710   char c = 0;
3711   ASSERT_EQ(0, pipe(fds));
3712   const int write_end = fds[1];
3713   ScopedFD read_end_closer(fds[0]);
3714   {
3715     ScopedFD write_end_closer(fds[1]);
3716   }
3717   // This is the only thread. This file descriptor should no longer be valid.
3718   int ret = close(write_end);
3719   EXPECT_EQ(-1, ret);
3720   EXPECT_EQ(EBADF, errno);
3721   // Make sure read(2) won't block.
3722   ASSERT_EQ(0, fcntl(fds[0], F_SETFL, O_NONBLOCK));
3723   // Reading the pipe should EOF.
3724   EXPECT_EQ(0, read(fds[0], &c, 1));
3725 }
3726 
3727 #if defined(GTEST_HAS_DEATH_TEST)
CloseWithScopedFD(int fd)3728 void CloseWithScopedFD(int fd) {
3729   ScopedFD fd_closer(fd);
3730 }
3731 #endif
3732 
TEST(ScopedFD,ScopedFDCrashesOnCloseFailure)3733 TEST(ScopedFD, ScopedFDCrashesOnCloseFailure) {
3734   int fds[2];
3735   ASSERT_EQ(0, pipe(fds));
3736   ScopedFD read_end_closer(fds[0]);
3737   EXPECT_EQ(0, IGNORE_EINTR(close(fds[1])));
3738 #if defined(GTEST_HAS_DEATH_TEST)
3739   // This is the only thread. This file descriptor should no longer be valid.
3740   // Trying to close it should crash. This is important for security.
3741   EXPECT_DEATH(CloseWithScopedFD(fds[1]), "");
3742 #endif
3743 }
3744 
3745 #endif  // defined(OS_POSIX) || defined(OS_FUCHSIA)
3746 
3747 }  // namespace
3748 
3749 }  // namespace base
3750