forked from chromium/chromium
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile_util_unittest.cc
4214 lines (3524 loc) · 150 KB
/
file_util_unittest.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/files/file_util.h"
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <algorithm>
#include <fstream>
#include <initializer_list>
#include <memory>
#include <set>
#include <utility>
#include <vector>
#include "base/base_paths.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/callback_helpers.h"
#include "base/command_line.h"
#include "base/environment.h"
#include "base/files/file.h"
#include "base/files/file_enumerator.h"
#include "base/files/file_path.h"
#include "base/files/scoped_file.h"
#include "base/files/scoped_temp_dir.h"
#include "base/guid.h"
#include "base/path_service.h"
#include "base/stl_util.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/multiprocess_test.h"
#include "base/test/scoped_environment_variable_override.h"
#include "base/test/test_file_util.h"
#include "base/test/test_timeouts.h"
#include "base/threading/platform_thread.h"
#include "base/threading/thread.h"
#include "base/time/time.h"
#include "build/build_config.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/multiprocess_func_list.h"
#include "testing/platform_test.h"
#if defined(OS_WIN)
#include <shellapi.h>
#include <shlobj.h>
#include <tchar.h>
#include <windows.h>
#include <winioctl.h>
#include "base/strings/string_number_conversions.h"
#include "base/win/scoped_handle.h"
#include "base/win/win_util.h"
#endif
#if defined(OS_POSIX) || defined(OS_FUCHSIA)
#include <errno.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <unistd.h>
#endif
#if defined(OS_LINUX)
#include <linux/fs.h>
#endif
#if defined(OS_ANDROID)
#include "base/android/content_uri_utils.h"
#endif
// This macro helps avoid wrapped lines in the test structs.
#define FPL(x) FILE_PATH_LITERAL(x)
namespace base {
namespace {
const size_t kLargeFileSize = (1 << 16) + 3;
// To test that NormalizeFilePath() deals with NTFS reparse points correctly,
// we need functions to create and delete reparse points.
#if defined(OS_WIN)
typedef struct _REPARSE_DATA_BUFFER {
ULONG ReparseTag;
USHORT ReparseDataLength;
USHORT Reserved;
union {
struct {
USHORT SubstituteNameOffset;
USHORT SubstituteNameLength;
USHORT PrintNameOffset;
USHORT PrintNameLength;
ULONG Flags;
WCHAR PathBuffer[1];
} SymbolicLinkReparseBuffer;
struct {
USHORT SubstituteNameOffset;
USHORT SubstituteNameLength;
USHORT PrintNameOffset;
USHORT PrintNameLength;
WCHAR PathBuffer[1];
} MountPointReparseBuffer;
struct {
UCHAR DataBuffer[1];
} GenericReparseBuffer;
};
} REPARSE_DATA_BUFFER, *PREPARSE_DATA_BUFFER;
// Sets a reparse point. |source| will now point to |target|. Returns true if
// the call succeeds, false otherwise.
bool SetReparsePoint(HANDLE source, const FilePath& target_path) {
std::wstring kPathPrefix = FILE_PATH_LITERAL("\\??\\");
std::wstring target_str;
// The juction will not work if the target path does not start with \??\ .
if (kPathPrefix != target_path.value().substr(0, kPathPrefix.size()))
target_str += kPathPrefix;
target_str += target_path.value();
const wchar_t* target = target_str.c_str();
USHORT size_target = static_cast<USHORT>(wcslen(target)) * sizeof(target[0]);
char buffer[2000] = {0};
DWORD returned;
REPARSE_DATA_BUFFER* data = reinterpret_cast<REPARSE_DATA_BUFFER*>(buffer);
data->ReparseTag = 0xa0000003;
memcpy(data->MountPointReparseBuffer.PathBuffer, target, size_target + 2);
data->MountPointReparseBuffer.SubstituteNameLength = size_target;
data->MountPointReparseBuffer.PrintNameOffset = size_target + 2;
data->ReparseDataLength = size_target + 4 + 8;
int data_size = data->ReparseDataLength + 8;
if (!DeviceIoControl(source, FSCTL_SET_REPARSE_POINT, &buffer, data_size,
NULL, 0, &returned, NULL)) {
return false;
}
return true;
}
// Delete the reparse point referenced by |source|. Returns true if the call
// succeeds, false otherwise.
bool DeleteReparsePoint(HANDLE source) {
DWORD returned;
REPARSE_DATA_BUFFER data = {0};
data.ReparseTag = 0xa0000003;
if (!DeviceIoControl(source, FSCTL_DELETE_REPARSE_POINT, &data, 8, NULL, 0,
&returned, NULL)) {
return false;
}
return true;
}
// Method that wraps the win32 GetShortPathName API. Returns an empty path on
// error.
FilePath MakeShortFilePath(const FilePath& input) {
DWORD path_short_len = ::GetShortPathName(input.value().c_str(), nullptr, 0);
if (path_short_len == 0UL)
return FilePath();
std::wstring path_short_str;
path_short_len = ::GetShortPathName(
input.value().c_str(), WriteInto(&path_short_str, path_short_len),
path_short_len);
if (path_short_len == 0UL)
return FilePath();
return FilePath(path_short_str);
}
// Manages a reparse point for a test.
class ReparsePoint {
public:
// Creates a reparse point from |source| (an empty directory) to |target|.
ReparsePoint(const FilePath& source, const FilePath& target) {
dir_.Set(
::CreateFile(source.value().c_str(), GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
NULL, OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS, // Needed to open a directory.
NULL));
created_ = dir_.IsValid() && SetReparsePoint(dir_.Get(), target);
}
~ReparsePoint() {
if (created_)
DeleteReparsePoint(dir_.Get());
}
bool IsValid() { return created_; }
private:
win::ScopedHandle dir_;
bool created_;
DISALLOW_COPY_AND_ASSIGN(ReparsePoint);
};
#endif
// Fuchsia doesn't support file permissions.
#if !defined(OS_FUCHSIA)
#if defined(OS_POSIX)
// Provide a simple way to change the permissions bits on |path| in tests.
// ASSERT failures will return, but not stop the test. Caller should wrap
// calls to this function in ASSERT_NO_FATAL_FAILURE().
void ChangePosixFilePermissions(const FilePath& path,
int mode_bits_to_set,
int mode_bits_to_clear) {
ASSERT_FALSE(mode_bits_to_set & mode_bits_to_clear)
<< "Can't set and clear the same bits.";
int mode = 0;
ASSERT_TRUE(GetPosixFilePermissions(path, &mode));
mode |= mode_bits_to_set;
mode &= ~mode_bits_to_clear;
ASSERT_TRUE(SetPosixFilePermissions(path, mode));
}
#endif // defined(OS_POSIX)
// Sets the source file to read-only.
void SetReadOnly(const FilePath& path, bool read_only) {
#if defined(OS_WIN)
// On Windows, it involves setting/removing the 'readonly' bit.
DWORD attrs = GetFileAttributes(path.value().c_str());
ASSERT_NE(INVALID_FILE_ATTRIBUTES, attrs);
ASSERT_TRUE(SetFileAttributes(
path.value().c_str(), read_only ? (attrs | FILE_ATTRIBUTE_READONLY)
: (attrs & ~FILE_ATTRIBUTE_READONLY)));
DWORD expected =
read_only
? ((attrs & (FILE_ATTRIBUTE_ARCHIVE | FILE_ATTRIBUTE_DIRECTORY)) |
FILE_ATTRIBUTE_READONLY)
: (attrs & (FILE_ATTRIBUTE_ARCHIVE | FILE_ATTRIBUTE_DIRECTORY));
// Ignore FILE_ATTRIBUTE_NOT_CONTENT_INDEXED and FILE_ATTRIBUTE_COMPRESSED
// if present. These flags are set by the operating system, depending on
// local configurations, such as compressing the file system. Not filtering
// out these flags could cause tests to fail even though they should pass.
attrs = GetFileAttributes(path.value().c_str()) &
~(FILE_ATTRIBUTE_NOT_CONTENT_INDEXED | FILE_ATTRIBUTE_COMPRESSED);
ASSERT_EQ(expected, attrs);
#else
// On all other platforms, it involves removing/setting the write bit.
mode_t mode = read_only ? S_IRUSR : (S_IRUSR | S_IWUSR);
EXPECT_TRUE(SetPosixFilePermissions(
path, DirectoryExists(path) ? (mode | S_IXUSR) : mode));
#endif // defined(OS_WIN)
}
bool IsReadOnly(const FilePath& path) {
#if defined(OS_WIN)
DWORD attrs = GetFileAttributes(path.value().c_str());
EXPECT_NE(INVALID_FILE_ATTRIBUTES, attrs);
return attrs & FILE_ATTRIBUTE_READONLY;
#else
int mode = 0;
EXPECT_TRUE(GetPosixFilePermissions(path, &mode));
return !(mode & S_IWUSR);
#endif // defined(OS_WIN)
}
#endif // defined(OS_FUCHSIA)
const wchar_t bogus_content[] = L"I'm cannon fodder.";
const int FILES_AND_DIRECTORIES =
FileEnumerator::FILES | FileEnumerator::DIRECTORIES;
// file_util winds up using autoreleased objects on the Mac, so this needs
// to be a PlatformTest
class FileUtilTest : public PlatformTest {
protected:
void SetUp() override {
PlatformTest::SetUp();
ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
}
ScopedTempDir temp_dir_;
};
// Collects all the results from the given file enumerator, and provides an
// interface to query whether a given file is present.
class FindResultCollector {
public:
explicit FindResultCollector(FileEnumerator* enumerator) {
FilePath cur_file;
while (!(cur_file = enumerator->Next()).value().empty()) {
FilePath::StringType path = cur_file.value();
// The file should not be returned twice.
EXPECT_TRUE(files_.end() == files_.find(path))
<< "Same file returned twice";
// Save for later.
files_.insert(path);
}
}
// Returns true if the enumerator found the file.
bool HasFile(const FilePath& file) const {
return files_.find(file.value()) != files_.end();
}
int size() {
return static_cast<int>(files_.size());
}
private:
std::set<FilePath::StringType> files_;
};
// Simple function to dump some text into a new file.
void CreateTextFile(const FilePath& filename,
const std::wstring& contents) {
std::wofstream file;
#if defined(OS_WIN)
file.open(filename.value().c_str());
#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
file.open(filename.value());
#endif // OS_WIN
ASSERT_TRUE(file.is_open());
file << contents;
file.close();
}
// Simple function to take out some text from a file.
std::wstring ReadTextFile(const FilePath& filename) {
wchar_t contents[64];
std::wifstream file;
#if defined(OS_WIN)
file.open(filename.value().c_str());
#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
file.open(filename.value());
#endif // OS_WIN
EXPECT_TRUE(file.is_open());
file.getline(contents, size(contents));
file.close();
return std::wstring(contents);
}
// Sets |is_inheritable| to indicate whether or not |stream| is set up to be
// inerhited into child processes (i.e., HANDLE_FLAG_INHERIT is set on the
// underlying handle on Windows, or FD_CLOEXEC is not set on the underlying file
// descriptor on POSIX). Calls to this function must be wrapped with
// ASSERT_NO_FATAL_FAILURE to properly abort tests in case of fatal failure.
void GetIsInheritable(FILE* stream, bool* is_inheritable) {
#if defined(OS_WIN)
HANDLE handle = reinterpret_cast<HANDLE>(_get_osfhandle(_fileno(stream)));
ASSERT_NE(INVALID_HANDLE_VALUE, handle);
DWORD info = 0;
ASSERT_EQ(TRUE, ::GetHandleInformation(handle, &info));
*is_inheritable = ((info & HANDLE_FLAG_INHERIT) != 0);
#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
int fd = fileno(stream);
ASSERT_NE(-1, fd);
int flags = fcntl(fd, F_GETFD, 0);
ASSERT_NE(-1, flags);
*is_inheritable = ((flags & FD_CLOEXEC) == 0);
#else
#error Not implemented
#endif
}
TEST_F(FileUtilTest, FileAndDirectorySize) {
// Create three files of 20, 30 and 3 chars (utf8). ComputeDirectorySize
// should return 53 bytes.
FilePath file_01 = temp_dir_.GetPath().Append(FPL("The file 01.txt"));
CreateTextFile(file_01, L"12345678901234567890");
int64_t size_f1 = 0;
ASSERT_TRUE(GetFileSize(file_01, &size_f1));
EXPECT_EQ(20ll, size_f1);
FilePath subdir_path = temp_dir_.GetPath().Append(FPL("Level2"));
CreateDirectory(subdir_path);
FilePath file_02 = subdir_path.Append(FPL("The file 02.txt"));
CreateTextFile(file_02, L"123456789012345678901234567890");
int64_t size_f2 = 0;
ASSERT_TRUE(GetFileSize(file_02, &size_f2));
EXPECT_EQ(30ll, size_f2);
FilePath subsubdir_path = subdir_path.Append(FPL("Level3"));
CreateDirectory(subsubdir_path);
FilePath file_03 = subsubdir_path.Append(FPL("The file 03.txt"));
CreateTextFile(file_03, L"123");
int64_t computed_size = ComputeDirectorySize(temp_dir_.GetPath());
EXPECT_EQ(size_f1 + size_f2 + 3, computed_size);
}
TEST_F(FileUtilTest, NormalizeFilePathBasic) {
// Create a directory under the test dir. Because we create it,
// we know it is not a link.
FilePath file_a_path = temp_dir_.GetPath().Append(FPL("file_a"));
FilePath dir_path = temp_dir_.GetPath().Append(FPL("dir"));
FilePath file_b_path = dir_path.Append(FPL("file_b"));
CreateDirectory(dir_path);
FilePath normalized_file_a_path, normalized_file_b_path;
ASSERT_FALSE(PathExists(file_a_path));
ASSERT_FALSE(NormalizeFilePath(file_a_path, &normalized_file_a_path))
<< "NormalizeFilePath() should fail on nonexistent paths.";
CreateTextFile(file_a_path, bogus_content);
ASSERT_TRUE(PathExists(file_a_path));
ASSERT_TRUE(NormalizeFilePath(file_a_path, &normalized_file_a_path));
CreateTextFile(file_b_path, bogus_content);
ASSERT_TRUE(PathExists(file_b_path));
ASSERT_TRUE(NormalizeFilePath(file_b_path, &normalized_file_b_path));
// Because this test created |dir_path|, we know it is not a link
// or junction. So, the real path of the directory holding file a
// must be the parent of the path holding file b.
ASSERT_TRUE(normalized_file_a_path.DirName()
.IsParent(normalized_file_b_path.DirName()));
}
#if defined(OS_WIN)
TEST_F(FileUtilTest, NormalizeFileEmptyFile) {
// Create a directory under the test dir. Because we create it,
// we know it is not a link.
const wchar_t empty_content[] = L"";
FilePath file_a_path = temp_dir_.GetPath().Append(FPL("file_empty_a"));
FilePath dir_path = temp_dir_.GetPath().Append(FPL("dir"));
FilePath file_b_path = dir_path.Append(FPL("file_empty_b"));
ASSERT_TRUE(CreateDirectory(dir_path));
FilePath normalized_file_a_path, normalized_file_b_path;
ASSERT_FALSE(PathExists(file_a_path));
EXPECT_FALSE(NormalizeFilePath(file_a_path, &normalized_file_a_path))
<< "NormalizeFilePath() should fail on nonexistent paths.";
CreateTextFile(file_a_path, empty_content);
ASSERT_TRUE(PathExists(file_a_path));
EXPECT_TRUE(NormalizeFilePath(file_a_path, &normalized_file_a_path));
CreateTextFile(file_b_path, empty_content);
ASSERT_TRUE(PathExists(file_b_path));
EXPECT_TRUE(NormalizeFilePath(file_b_path, &normalized_file_b_path));
// Because this test created |dir_path|, we know it is not a link
// or junction. So, the real path of the directory holding file a
// must be the parent of the path holding file b.
EXPECT_TRUE(normalized_file_a_path.DirName().IsParent(
normalized_file_b_path.DirName()));
}
TEST_F(FileUtilTest, NormalizeFilePathReparsePoints) {
// Build the following directory structure:
//
// temp_dir
// |-> base_a
// | |-> sub_a
// | |-> file.txt
// | |-> long_name___... (Very long name.)
// | |-> sub_long
// | |-> deep.txt
// |-> base_b
// |-> to_sub_a (reparse point to temp_dir\base_a\sub_a)
// |-> to_base_b (reparse point to temp_dir\base_b)
// |-> to_sub_long (reparse point to temp_dir\sub_a\long_name_\sub_long)
FilePath base_a = temp_dir_.GetPath().Append(FPL("base_a"));
#if defined(OS_WIN)
// TEMP can have a lower case drive letter.
std::wstring temp_base_a = base_a.value();
ASSERT_FALSE(temp_base_a.empty());
temp_base_a[0] = ToUpperASCII(char16{temp_base_a[0]});
base_a = FilePath(temp_base_a);
#endif
ASSERT_TRUE(CreateDirectory(base_a));
#if defined(OS_WIN)
// TEMP might be a short name which is not normalized.
base_a = MakeLongFilePath(base_a);
#endif
FilePath sub_a = base_a.Append(FPL("sub_a"));
ASSERT_TRUE(CreateDirectory(sub_a));
FilePath file_txt = sub_a.Append(FPL("file.txt"));
CreateTextFile(file_txt, bogus_content);
// Want a directory whose name is long enough to make the path to the file
// inside just under MAX_PATH chars. This will be used to test that when
// a junction expands to a path over MAX_PATH chars in length,
// NormalizeFilePath() fails without crashing.
FilePath sub_long_rel(FPL("sub_long"));
FilePath deep_txt(FPL("deep.txt"));
int target_length = MAX_PATH;
target_length -= (sub_a.value().length() + 1); // +1 for the sepperator '\'.
target_length -= (sub_long_rel.Append(deep_txt).value().length() + 1);
// Without making the path a bit shorter, CreateDirectory() fails.
// the resulting path is still long enough to hit the failing case in
// NormalizePath().
const int kCreateDirLimit = 4;
target_length -= kCreateDirLimit;
FilePath::StringType long_name_str = FPL("long_name_");
long_name_str.resize(target_length, '_');
FilePath long_name = sub_a.Append(FilePath(long_name_str));
FilePath deep_file = long_name.Append(sub_long_rel).Append(deep_txt);
ASSERT_EQ(static_cast<size_t>(MAX_PATH - kCreateDirLimit),
deep_file.value().length());
FilePath sub_long = deep_file.DirName();
ASSERT_TRUE(CreateDirectory(sub_long));
CreateTextFile(deep_file, bogus_content);
FilePath base_b = temp_dir_.GetPath().Append(FPL("base_b"));
ASSERT_TRUE(CreateDirectory(base_b));
#if defined(OS_WIN)
// TEMP might be a short name which is not normalized.
base_b = MakeLongFilePath(base_b);
#endif
FilePath to_sub_a = base_b.Append(FPL("to_sub_a"));
ASSERT_TRUE(CreateDirectory(to_sub_a));
FilePath normalized_path;
{
ReparsePoint reparse_to_sub_a(to_sub_a, sub_a);
ASSERT_TRUE(reparse_to_sub_a.IsValid());
FilePath to_base_b = base_b.Append(FPL("to_base_b"));
ASSERT_TRUE(CreateDirectory(to_base_b));
ReparsePoint reparse_to_base_b(to_base_b, base_b);
ASSERT_TRUE(reparse_to_base_b.IsValid());
FilePath to_sub_long = base_b.Append(FPL("to_sub_long"));
ASSERT_TRUE(CreateDirectory(to_sub_long));
ReparsePoint reparse_to_sub_long(to_sub_long, sub_long);
ASSERT_TRUE(reparse_to_sub_long.IsValid());
// Normalize a junction free path: base_a\sub_a\file.txt .
ASSERT_TRUE(NormalizeFilePath(file_txt, &normalized_path));
ASSERT_EQ(file_txt.value(), normalized_path.value());
// Check that the path base_b\to_sub_a\file.txt can be normalized to exclude
// the junction to_sub_a.
ASSERT_TRUE(NormalizeFilePath(to_sub_a.Append(FPL("file.txt")),
&normalized_path));
ASSERT_EQ(file_txt.value(), normalized_path.value());
// Check that the path base_b\to_base_b\to_base_b\to_sub_a\file.txt can be
// normalized to exclude junctions to_base_b and to_sub_a .
ASSERT_TRUE(NormalizeFilePath(base_b.Append(FPL("to_base_b"))
.Append(FPL("to_base_b"))
.Append(FPL("to_sub_a"))
.Append(FPL("file.txt")),
&normalized_path));
ASSERT_EQ(file_txt.value(), normalized_path.value());
// A long enough path will cause NormalizeFilePath() to fail. Make a long
// path using to_base_b many times, and check that paths long enough to fail
// do not cause a crash.
FilePath long_path = base_b;
const int kLengthLimit = MAX_PATH + 200;
while (long_path.value().length() <= kLengthLimit) {
long_path = long_path.Append(FPL("to_base_b"));
}
long_path = long_path.Append(FPL("to_sub_a"))
.Append(FPL("file.txt"));
ASSERT_FALSE(NormalizeFilePath(long_path, &normalized_path));
// Normalizing the junction to deep.txt should fail, because the expanded
// path to deep.txt is longer than MAX_PATH.
ASSERT_FALSE(NormalizeFilePath(to_sub_long.Append(deep_txt),
&normalized_path));
// Delete the reparse points, and see that NormalizeFilePath() fails
// to traverse them.
}
ASSERT_FALSE(NormalizeFilePath(to_sub_a.Append(FPL("file.txt")),
&normalized_path));
}
TEST_F(FileUtilTest, DevicePathToDriveLetter) {
// Get a drive letter.
std::wstring real_drive_letter = AsWString(
ToUpperASCII(AsStringPiece16(temp_dir_.GetPath().value().substr(0, 2))));
if (!isalpha(real_drive_letter[0]) || ':' != real_drive_letter[1]) {
LOG(ERROR) << "Can't get a drive letter to test with.";
return;
}
// Get the NT style path to that drive.
wchar_t device_path[MAX_PATH] = {'\0'};
ASSERT_TRUE(
::QueryDosDevice(real_drive_letter.c_str(), device_path, MAX_PATH));
FilePath actual_device_path(device_path);
FilePath win32_path;
// Run DevicePathToDriveLetterPath() on the NT style path we got from
// QueryDosDevice(). Expect the drive letter we started with.
ASSERT_TRUE(DevicePathToDriveLetterPath(actual_device_path, &win32_path));
ASSERT_EQ(real_drive_letter, win32_path.value());
// Add some directories to the path. Expect those extra path componenets
// to be preserved.
FilePath kRelativePath(FPL("dir1\\dir2\\file.txt"));
ASSERT_TRUE(DevicePathToDriveLetterPath(
actual_device_path.Append(kRelativePath),
&win32_path));
EXPECT_EQ(FilePath(real_drive_letter + FILE_PATH_LITERAL("\\"))
.Append(kRelativePath)
.value(),
win32_path.value());
// Deform the real path so that it is invalid by removing the last four
// characters. The way windows names devices that are hard disks
// (\Device\HardDiskVolume${NUMBER}) guarantees that the string is longer
// than three characters. The only way the truncated string could be a
// real drive is if more than 10^3 disks are mounted:
// \Device\HardDiskVolume10000 would be truncated to \Device\HardDiskVolume1
// Check that DevicePathToDriveLetterPath fails.
size_t path_length = actual_device_path.value().length();
size_t new_length = path_length - 4;
ASSERT_GT(new_length, 0u);
FilePath prefix_of_real_device_path(
actual_device_path.value().substr(0, new_length));
ASSERT_FALSE(DevicePathToDriveLetterPath(prefix_of_real_device_path,
&win32_path));
ASSERT_FALSE(DevicePathToDriveLetterPath(
prefix_of_real_device_path.Append(kRelativePath),
&win32_path));
// Deform the real path so that it is invalid by adding some characters. For
// example, if C: maps to \Device\HardDiskVolume8, then we simulate a
// request for the drive letter whose native path is
// \Device\HardDiskVolume812345 . We assume such a device does not exist,
// because drives are numbered in order and mounting 112345 hard disks will
// never happen.
const FilePath::StringType kExtraChars = FPL("12345");
FilePath real_device_path_plus_numbers(
actual_device_path.value() + kExtraChars);
ASSERT_FALSE(DevicePathToDriveLetterPath(
real_device_path_plus_numbers,
&win32_path));
ASSERT_FALSE(DevicePathToDriveLetterPath(
real_device_path_plus_numbers.Append(kRelativePath),
&win32_path));
}
TEST_F(FileUtilTest, CreateTemporaryFileInDirLongPathTest) {
// Test that CreateTemporaryFileInDir() creates a path and returns a long path
// if it is available. This test requires that:
// - the filesystem at |temp_dir_| supports long filenames.
// - the account has FILE_LIST_DIRECTORY permission for all ancestor
// directories of |temp_dir_|.
constexpr FilePath::CharType kLongDirName[] = FPL("A long path");
constexpr FilePath::CharType kTestSubDirName[] = FPL("test");
FilePath long_test_dir = temp_dir_.GetPath().Append(kLongDirName);
ASSERT_TRUE(CreateDirectory(long_test_dir));
// kLongDirName is not a 8.3 component. So ::GetShortPathName() should give us
// a different short name.
FilePath short_test_dir = MakeShortFilePath(long_test_dir);
ASSERT_FALSE(short_test_dir.empty());
ASSERT_NE(kLongDirName, short_test_dir.BaseName().value());
FilePath temp_file;
ASSERT_TRUE(CreateTemporaryFileInDir(short_test_dir, &temp_file));
EXPECT_EQ(kLongDirName, temp_file.DirName().BaseName().value());
EXPECT_TRUE(PathExists(temp_file));
// Create a subdirectory of |long_test_dir| and make |long_test_dir|
// unreadable. We should still be able to create a temp file in the
// subdirectory, but we won't be able to determine the long path for it. This
// mimics the environment that some users run where their user profiles reside
// in a location where the don't have full access to the higher level
// directories. (Note that this assumption is true for NTFS, but not for some
// network file systems. E.g. AFS).
FilePath access_test_dir = long_test_dir.Append(kTestSubDirName);
ASSERT_TRUE(CreateDirectory(access_test_dir));
FilePermissionRestorer long_test_dir_restorer(long_test_dir);
ASSERT_TRUE(MakeFileUnreadable(long_test_dir));
// Use the short form of the directory to create a temporary filename.
ASSERT_TRUE(CreateTemporaryFileInDir(
short_test_dir.Append(kTestSubDirName), &temp_file));
EXPECT_TRUE(PathExists(temp_file));
EXPECT_TRUE(short_test_dir.IsParent(temp_file.DirName()));
// Check that the long path can't be determined for |temp_file|.
// Helper method base::MakeLongFilePath returns an empty path on error.
FilePath temp_file_long = MakeLongFilePath(temp_file);
ASSERT_TRUE(temp_file_long.empty());
}
TEST_F(FileUtilTest, MakeLongFilePathTest) {
// Tests helper function base::MakeLongFilePath
// If a username isn't a valid 8.3 short file name (even just a
// lengthy name like "user with long name"), Windows will set the TMP and TEMP
// environment variables to be 8.3 paths. ::GetTempPath (called in
// base::GetTempDir) just uses the value specified by TMP or TEMP, and so can
// return a short path. So from the start need to use MakeLongFilePath
// to normalize the path for such test environments.
FilePath temp_dir_long = MakeLongFilePath(temp_dir_.GetPath());
ASSERT_FALSE(temp_dir_long.empty());
FilePath long_test_dir = temp_dir_long.Append(FPL("A long directory name"));
ASSERT_TRUE(CreateDirectory(long_test_dir));
// Directory name is not a 8.3 component. So ::GetShortPathName() should give
// us a different short name.
FilePath short_test_dir = MakeShortFilePath(long_test_dir);
ASSERT_FALSE(short_test_dir.empty());
EXPECT_NE(long_test_dir, short_test_dir);
EXPECT_EQ(long_test_dir, MakeLongFilePath(short_test_dir));
FilePath long_test_file = long_test_dir.Append(FPL("A long file name.1234"));
CreateTextFile(long_test_file, bogus_content);
ASSERT_TRUE(PathExists(long_test_file));
// File name is not a 8.3 component. So ::GetShortPathName() should give us
// a different short name.
FilePath short_test_file = MakeShortFilePath(long_test_file);
ASSERT_FALSE(short_test_file.empty());
EXPECT_NE(long_test_file, short_test_file);
EXPECT_EQ(long_test_file, MakeLongFilePath(short_test_file));
// MakeLongFilePath should return empty path if file does not exist.
EXPECT_TRUE(DeleteFile(short_test_file, false));
EXPECT_TRUE(MakeLongFilePath(short_test_file).empty());
// MakeLongFilePath should return empty path if directory does not exist.
EXPECT_TRUE(DeleteFile(short_test_dir, false));
EXPECT_TRUE(MakeLongFilePath(short_test_dir).empty());
}
TEST_F(FileUtilTest, CreateWinHardlinkTest) {
// Link to a different file name in a sub-directory of |temp_dir_|.
FilePath test_dir = temp_dir_.GetPath().Append(FPL("test"));
ASSERT_TRUE(CreateDirectory(test_dir));
FilePath temp_file;
ASSERT_TRUE(CreateTemporaryFileInDir(temp_dir_.GetPath(), &temp_file));
FilePath link_to_file = test_dir.Append(FPL("linked_name"));
EXPECT_TRUE(CreateWinHardLink(link_to_file, temp_file));
EXPECT_TRUE(PathExists(link_to_file));
// Link two directories. This should fail. Verify that failure is returned
// by CreateWinHardLink.
EXPECT_FALSE(CreateWinHardLink(temp_dir_.GetPath(), test_dir));
}
#endif // defined(OS_WIN)
#if defined(OS_POSIX)
TEST_F(FileUtilTest, CreateAndReadSymlinks) {
FilePath link_from = temp_dir_.GetPath().Append(FPL("from_file"));
FilePath link_to = temp_dir_.GetPath().Append(FPL("to_file"));
CreateTextFile(link_to, bogus_content);
ASSERT_TRUE(CreateSymbolicLink(link_to, link_from))
<< "Failed to create file symlink.";
// If we created the link properly, we should be able to read the contents
// through it.
EXPECT_EQ(bogus_content, ReadTextFile(link_from));
FilePath result;
ASSERT_TRUE(ReadSymbolicLink(link_from, &result));
EXPECT_EQ(link_to.value(), result.value());
// Link to a directory.
link_from = temp_dir_.GetPath().Append(FPL("from_dir"));
link_to = temp_dir_.GetPath().Append(FPL("to_dir"));
ASSERT_TRUE(CreateDirectory(link_to));
ASSERT_TRUE(CreateSymbolicLink(link_to, link_from))
<< "Failed to create directory symlink.";
// Test failures.
EXPECT_FALSE(CreateSymbolicLink(link_to, link_to));
EXPECT_FALSE(ReadSymbolicLink(link_to, &result));
FilePath missing = temp_dir_.GetPath().Append(FPL("missing"));
EXPECT_FALSE(ReadSymbolicLink(missing, &result));
}
// The following test of NormalizeFilePath() require that we create a symlink.
// This can not be done on Windows before Vista. On Vista, creating a symlink
// requires privilege "SeCreateSymbolicLinkPrivilege".
// TODO(skerner): Investigate the possibility of giving base_unittests the
// privileges required to create a symlink.
TEST_F(FileUtilTest, NormalizeFilePathSymlinks) {
// Link one file to another.
FilePath link_from = temp_dir_.GetPath().Append(FPL("from_file"));
FilePath link_to = temp_dir_.GetPath().Append(FPL("to_file"));
CreateTextFile(link_to, bogus_content);
ASSERT_TRUE(CreateSymbolicLink(link_to, link_from))
<< "Failed to create file symlink.";
// Check that NormalizeFilePath sees the link.
FilePath normalized_path;
ASSERT_TRUE(NormalizeFilePath(link_from, &normalized_path));
EXPECT_NE(link_from, link_to);
EXPECT_EQ(link_to.BaseName().value(), normalized_path.BaseName().value());
EXPECT_EQ(link_to.BaseName().value(), normalized_path.BaseName().value());
// Link to a directory.
link_from = temp_dir_.GetPath().Append(FPL("from_dir"));
link_to = temp_dir_.GetPath().Append(FPL("to_dir"));
ASSERT_TRUE(CreateDirectory(link_to));
ASSERT_TRUE(CreateSymbolicLink(link_to, link_from))
<< "Failed to create directory symlink.";
EXPECT_FALSE(NormalizeFilePath(link_from, &normalized_path))
<< "Links to directories should return false.";
// Test that a loop in the links causes NormalizeFilePath() to return false.
link_from = temp_dir_.GetPath().Append(FPL("link_a"));
link_to = temp_dir_.GetPath().Append(FPL("link_b"));
ASSERT_TRUE(CreateSymbolicLink(link_to, link_from))
<< "Failed to create loop symlink a.";
ASSERT_TRUE(CreateSymbolicLink(link_from, link_to))
<< "Failed to create loop symlink b.";
// Infinite loop!
EXPECT_FALSE(NormalizeFilePath(link_from, &normalized_path));
}
TEST_F(FileUtilTest, DeleteSymlinkToExistentFile) {
// Create a file.
FilePath file_name = temp_dir_.GetPath().Append(FPL("Test DeleteFile 2.txt"));
CreateTextFile(file_name, bogus_content);
ASSERT_TRUE(PathExists(file_name));
// Create a symlink to the file.
FilePath file_link = temp_dir_.GetPath().Append("file_link_2");
ASSERT_TRUE(CreateSymbolicLink(file_name, file_link))
<< "Failed to create symlink.";
// Delete the symbolic link.
EXPECT_TRUE(DeleteFile(file_link, false));
// Make sure original file is not deleted.
EXPECT_FALSE(PathExists(file_link));
EXPECT_TRUE(PathExists(file_name));
}
TEST_F(FileUtilTest, DeleteSymlinkToNonExistentFile) {
// Create a non-existent file path.
FilePath non_existent =
temp_dir_.GetPath().Append(FPL("Test DeleteFile 3.txt"));
EXPECT_FALSE(PathExists(non_existent));
// Create a symlink to the non-existent file.
FilePath file_link = temp_dir_.GetPath().Append("file_link_3");
ASSERT_TRUE(CreateSymbolicLink(non_existent, file_link))
<< "Failed to create symlink.";
// Make sure the symbolic link is exist.
EXPECT_TRUE(IsLink(file_link));
EXPECT_FALSE(PathExists(file_link));
// Delete the symbolic link.
EXPECT_TRUE(DeleteFile(file_link, false));
// Make sure the symbolic link is deleted.
EXPECT_FALSE(IsLink(file_link));
}
TEST_F(FileUtilTest, CopyFileFollowsSymlinks) {
FilePath link_from = temp_dir_.GetPath().Append(FPL("from_file"));
FilePath link_to = temp_dir_.GetPath().Append(FPL("to_file"));
CreateTextFile(link_to, bogus_content);
ASSERT_TRUE(CreateSymbolicLink(link_to, link_from));
// If we created the link properly, we should be able to read the contents
// through it.
EXPECT_EQ(bogus_content, ReadTextFile(link_from));
FilePath result;
ASSERT_TRUE(ReadSymbolicLink(link_from, &result));
EXPECT_EQ(link_to.value(), result.value());
// Create another file and copy it to |link_from|.
FilePath src_file = temp_dir_.GetPath().Append(FPL("src.txt"));
const std::wstring file_contents(L"Gooooooooooooooooooooogle");
CreateTextFile(src_file, file_contents);
ASSERT_TRUE(CopyFile(src_file, link_from));
// Make sure |link_from| is still a symlink, and |link_to| has been written to
// by CopyFile().
EXPECT_TRUE(IsLink(link_from));
EXPECT_EQ(file_contents, ReadTextFile(link_from));
EXPECT_EQ(file_contents, ReadTextFile(link_to));
}
TEST_F(FileUtilTest, ChangeFilePermissionsAndRead) {
// Create a file path.
FilePath file_name =
temp_dir_.GetPath().Append(FPL("Test Readable File.txt"));
EXPECT_FALSE(PathExists(file_name));
static constexpr char kData[] = "hello";
static constexpr int kDataSize = sizeof(kData) - 1;
char buffer[kDataSize];
// Write file.
EXPECT_TRUE(WriteFile(file_name, kData));
EXPECT_TRUE(PathExists(file_name));
// Make sure the file is readable.
int32_t mode = 0;
EXPECT_TRUE(GetPosixFilePermissions(file_name, &mode));
EXPECT_TRUE(mode & FILE_PERMISSION_READ_BY_USER);
// Get rid of the read permission.
EXPECT_TRUE(SetPosixFilePermissions(file_name, 0u));
EXPECT_TRUE(GetPosixFilePermissions(file_name, &mode));
EXPECT_FALSE(mode & FILE_PERMISSION_READ_BY_USER);
// Make sure the file can't be read.
EXPECT_EQ(-1, ReadFile(file_name, buffer, kDataSize));
// Give the read permission.
EXPECT_TRUE(SetPosixFilePermissions(file_name, FILE_PERMISSION_READ_BY_USER));
EXPECT_TRUE(GetPosixFilePermissions(file_name, &mode));
EXPECT_TRUE(mode & FILE_PERMISSION_READ_BY_USER);
// Make sure the file can be read.
EXPECT_EQ(kDataSize, ReadFile(file_name, buffer, kDataSize));
// Delete the file.
EXPECT_TRUE(DeleteFile(file_name, false));
EXPECT_FALSE(PathExists(file_name));
}
TEST_F(FileUtilTest, ChangeFilePermissionsAndWrite) {
// Create a file path.
FilePath file_name =
temp_dir_.GetPath().Append(FPL("Test Readable File.txt"));
EXPECT_FALSE(PathExists(file_name));
const std::string kData("hello");
// Write file.
EXPECT_TRUE(WriteFile(file_name, kData));
EXPECT_TRUE(PathExists(file_name));
// Make sure the file is writable.
int mode = 0;
EXPECT_TRUE(GetPosixFilePermissions(file_name, &mode));
EXPECT_TRUE(mode & FILE_PERMISSION_WRITE_BY_USER);
EXPECT_TRUE(PathIsWritable(file_name));
// Get rid of the write permission.
EXPECT_TRUE(SetPosixFilePermissions(file_name, 0u));
EXPECT_TRUE(GetPosixFilePermissions(file_name, &mode));
EXPECT_FALSE(mode & FILE_PERMISSION_WRITE_BY_USER);
// Make sure the file can't be write.
EXPECT_FALSE(WriteFile(file_name, kData));
EXPECT_FALSE(PathIsWritable(file_name));
// Give read permission.
EXPECT_TRUE(SetPosixFilePermissions(file_name,
FILE_PERMISSION_WRITE_BY_USER));
EXPECT_TRUE(GetPosixFilePermissions(file_name, &mode));
EXPECT_TRUE(mode & FILE_PERMISSION_WRITE_BY_USER);
// Make sure the file can be write.
EXPECT_TRUE(WriteFile(file_name, kData));
EXPECT_TRUE(PathIsWritable(file_name));
// Delete the file.
EXPECT_TRUE(DeleteFile(file_name, false));
EXPECT_FALSE(PathExists(file_name));
}
TEST_F(FileUtilTest, ChangeDirectoryPermissionsAndEnumerate) {
// Create a directory path.
FilePath subdir_path = temp_dir_.GetPath().Append(FPL("PermissionTest1"));
CreateDirectory(subdir_path);
ASSERT_TRUE(PathExists(subdir_path));
// Create a dummy file to enumerate.
FilePath file_name = subdir_path.Append(FPL("Test Readable File.txt"));
EXPECT_FALSE(PathExists(file_name));
const std::string kData("hello");
EXPECT_TRUE(WriteFile(file_name, kData));
EXPECT_TRUE(PathExists(file_name));