-
Notifications
You must be signed in to change notification settings - Fork 4.1k
/
tw.cc
1900 lines (1693 loc) · 61.6 KB
/
tw.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 2018 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Test wrapper implementation for Windows.
// Design:
// https://github.com/laszlocsomor/proposals/blob/win-test-runner/designs/2018-07-18-windows-native-test-runner.md
#include "tools/test/windows/tw.h"
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
#include <errno.h>
#include <limits.h> // INT_MAX
#include <lmcons.h> // UNLEN
#include <string.h>
#include <sys/types.h>
#include <wchar.h>
#include <algorithm>
#include <cstdio>
#include <fstream>
#include <functional>
#include <iomanip>
#include <memory>
#include <sstream>
#include <string>
#include <vector>
#include "src/main/cpp/util/file_platform.h"
#include "src/main/cpp/util/path_platform.h"
#include "src/main/cpp/util/strings.h"
#include "src/main/native/windows/file.h"
#include "src/main/native/windows/process.h"
#include "src/main/native/windows/util.h"
#include "src/tools/launcher/util/launcher_util.h"
#include "third_party/ijar/common.h"
#include "third_party/ijar/platform_utils.h"
#include "third_party/ijar/zip.h"
#include "tools/cpp/runfiles/runfiles.h"
namespace bazel {
namespace tools {
namespace test_wrapper {
namespace {
class Defer {
public:
explicit Defer(std::function<void()> f) : f_(f) {}
~Defer() { f_(); }
void DoNow() {
f_();
f_ = kEmpty;
}
private:
std::function<void()> f_;
static const std::function<void()> kEmpty;
};
const std::function<void()> Defer::kEmpty = []() {};
// Streams data from an input to two outputs.
// Inspired by tee(1) in the GNU coreutils.
class TeeImpl : Tee {
public:
// Creates a background thread to stream data from `input` to the two outputs.
// The thread terminates when ReadFile fails on the input (e.g. the input is
// the reading end of a pipe and the writing end is closed) or when WriteFile
// fails on one of the outputs (e.g. the same output handle is closed
// elsewhere).
static bool Create(bazel::windows::AutoHandle* input,
bazel::windows::AutoHandle* output1,
bazel::windows::AutoHandle* output2,
std::unique_ptr<Tee>* result);
private:
static DWORD WINAPI ThreadFunc(LPVOID lpParam);
TeeImpl(bazel::windows::AutoHandle* input,
bazel::windows::AutoHandle* output1,
bazel::windows::AutoHandle* output2)
: input_(input), output1_(output1), output2_(output2) {}
TeeImpl(const TeeImpl&) = delete;
TeeImpl& operator=(const TeeImpl&) = delete;
bool MainFunc() const;
bazel::windows::AutoHandle input_;
bazel::windows::AutoHandle output1_;
bazel::windows::AutoHandle output2_;
};
// Buffered input stream (based on a Windows HANDLE) with peek-ahead support.
//
// This class uses two consecutive "pages" where it buffers data from the
// underlying HANDLE (wrapped in an AutoHandle). Both pages are always loaded
// with data until there's no more data to read.
//
// The "active" page is the one where the read cursor is pointing. The other
// page is the next one to be read once the client moves the read cursor beyond
// the end of the active page.
//
// The client advances the read cursor with Advance(). When the cursor reaches
// the end of the active page, the other page becomes the active one (whose data
// is already buffered), and the old active page is loaded with new data from
// the underlying file.
class IFStreamImpl : IFStream {
public:
// Creates a new IFStream.
//
// If successful, then takes ownership of the HANDLE in 'handle', and returns
// a new IFStream pointer. Otherwise leaves 'handle' alone and returns
// nullptr.
static IFStream* Create(HANDLE handle, DWORD page_size = 0x100000 /* 1 MB */);
int Get() override;
DWORD Peek(DWORD n, uint8_t* out) const override;
private:
HANDLE handle_;
const std::unique_ptr<uint8_t[]> pages_;
const DWORD page_size_;
DWORD pos_, end_, next_size_;
IFStreamImpl(HANDLE handle, std::unique_ptr<uint8_t[]>&& pages, DWORD n,
DWORD page_size)
: handle_(handle),
pages_(std::move(pages)),
page_size_(page_size),
pos_(0),
end_(n < page_size ? n : page_size),
next_size_(n < page_size
? 0
: (n < page_size * 2 ? n - page_size : page_size)) {}
};
// A lightweight path abstraction that stores a Unicode Windows path.
//
// The class allows extracting the underlying path as a (immutable) string so
// it's easy to pass the path to WinAPI functions, but the class does not allow
// mutating the unterlying path so it's safe to pass around Path objects.
class Path {
public:
Path() {}
Path(const Path& other) : path_(other.path_) {}
Path(Path&& other) : path_(std::move(other.path_)) {}
Path& operator=(const Path& other) = delete;
const std::wstring& Get() const { return path_; }
bool Set(const std::wstring& path);
// Makes this path absolute.
// Returns true if the path was changed (i.e. was not absolute before).
// Returns false and has no effect if this path was empty or already absolute.
bool Absolutize(const Path& cwd);
Path Dirname() const;
private:
std::wstring path_;
};
struct UndeclaredOutputs {
Path root;
Path zip;
Path manifest;
Path annotations;
Path annotations_dir;
};
struct Duration {
static constexpr int kMax = INT_MAX;
int seconds;
bool FromString(const wchar_t* str);
};
void WriteStdout(const std::string& s) {
DWORD written;
WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), s.c_str(), s.size(), &written,
NULL);
}
void LogError(const int line) {
std::stringstream ss;
ss << "ERROR(" << __FILE__ << ":" << line << ")" << std::endl;
WriteStdout(ss.str());
}
void LogError(const int line, const std::string& msg) {
std::stringstream ss;
ss << "ERROR(" << __FILE__ << ":" << line << ") " << msg << std::endl;
WriteStdout(ss.str());
}
void LogError(const int line, const std::wstring& msg) {
std::string acp_msg;
if (blaze_util::WcsToAcp(msg, &acp_msg)) {
LogError(line, acp_msg);
}
}
void LogErrorWithValue(const int line, const std::string& msg, DWORD value) {
std::stringstream ss;
ss << "value: " << value << " (0x";
ss.setf(std::ios_base::hex, std::ios_base::basefield);
ss << std::setw(8) << std::setfill('0') << value << "): ";
ss.setf(std::ios_base::dec, std::ios_base::basefield);
ss << msg;
LogError(line, ss.str());
}
void LogErrorWithValue(const int line, const std::wstring& msg, DWORD value) {
std::string acp_msg;
if (blaze_util::WcsToAcp(msg, &acp_msg)) {
LogErrorWithValue(line, acp_msg, value);
}
}
void LogErrorWithArgAndValue(const int line, const std::string& msg,
const std::string& arg, DWORD value) {
std::stringstream ss;
ss << "value: " << value << " (0x";
ss.setf(std::ios_base::hex, std::ios_base::basefield);
ss << std::setw(8) << std::setfill('0') << value << "): argument: ";
ss.setf(std::ios_base::dec, std::ios_base::basefield);
ss << arg << ": " << msg;
LogError(line, ss.str());
}
void LogErrorWithArgAndValue(const int line, const std::string& msg,
const std::wstring& arg, DWORD value) {
std::string acp_arg;
if (blaze_util::WcsToAcp(arg, &acp_arg)) {
LogErrorWithArgAndValue(line, msg, acp_arg, value);
}
}
std::wstring AddUncPrefixMaybe(const Path& p) {
return bazel::windows::AddUncPrefixMaybe(p.Get());
}
std::wstring RemoveUncPrefixMaybe(const Path& p) {
return bazel::windows::RemoveUncPrefixMaybe(p.Get());
}
inline bool CreateDirectories(const Path& path) {
blaze_util::MakeDirectoriesW(AddUncPrefixMaybe(path), 0777);
return true;
}
inline bool ToInt(const wchar_t* s, int* result) {
return std::swscanf(s, L"%d", result) == 1;
}
bool WcsToAcp(const std::wstring& wcs, std::string* acp) {
uint32_t err;
if (!blaze_util::WcsToAcp(wcs, acp, &err)) {
LogErrorWithArgAndValue(__LINE__, "Failed to convert string", wcs, err);
return false;
}
return true;
}
// Converts a Windows-style path to a mixed (Unix-Windows) style.
// The path is mixed-style because it is a Windows path (begins with a drive
// letter) but uses forward slashes as directory separators.
// We must export envvars as mixed style path because some tools confuse the
// backslashes in Windows paths for Unix-style escape characters.
std::wstring AsMixedPath(const std::wstring& path) {
std::wstring value = path;
std::replace(value.begin(), value.end(), L'\\', L'/');
return value;
}
bool GetEnv(const wchar_t* name, std::wstring* result) {
static constexpr size_t kSmallBuf = MAX_PATH;
WCHAR value[kSmallBuf];
DWORD size = GetEnvironmentVariableW(name, value, kSmallBuf);
DWORD err = GetLastError();
if (size == 0 && err == ERROR_ENVVAR_NOT_FOUND) {
result->clear();
return true;
} else if (0 < size && size < kSmallBuf) {
*result = value;
return true;
} else if (size >= kSmallBuf) {
std::unique_ptr<WCHAR[]> value_big(new WCHAR[size]);
GetEnvironmentVariableW(name, value_big.get(), size);
*result = value_big.get();
return true;
} else {
LogErrorWithArgAndValue(__LINE__, "Failed to read envvar", name, err);
return false;
}
}
bool GetPathEnv(const wchar_t* name, Path* result) {
std::wstring value;
if (!GetEnv(name, &value)) {
LogError(__LINE__, name);
return false;
}
return result->Set(value);
}
bool GetIntEnv(const wchar_t* name, std::wstring* as_wstr, int* as_int) {
*as_int = 0;
if (!GetEnv(name, as_wstr) ||
(!as_wstr->empty() && !ToInt(as_wstr->c_str(), as_int))) {
LogError(__LINE__, name);
return false;
}
return true;
}
bool SetEnv(const wchar_t* name, const std::wstring& value) {
if (SetEnvironmentVariableW(name, value.c_str()) != 0) {
return true;
} else {
DWORD err = GetLastError();
LogErrorWithArgAndValue(__LINE__, "Failed to set envvar", name, err);
return false;
}
}
bool SetPathEnv(const wchar_t* name, const Path& path) {
return SetEnv(name, AsMixedPath(path.Get()));
}
bool UnsetEnv(const wchar_t* name) {
if (SetEnvironmentVariableW(name, NULL) != 0) {
return true;
} else {
DWORD err = GetLastError();
LogErrorWithArgAndValue(__LINE__, "Failed to unset envvar", name, err);
return false;
}
}
bool GetCwd(Path* result) {
static constexpr size_t kSmallBuf = MAX_PATH;
WCHAR value[kSmallBuf];
DWORD size = GetCurrentDirectoryW(kSmallBuf, value);
DWORD err = GetLastError();
if (size > 0 && size < kSmallBuf) {
return result->Set(value);
} else if (size >= kSmallBuf) {
std::unique_ptr<WCHAR[]> value_big(new WCHAR[size]);
GetCurrentDirectoryW(size, value_big.get());
return result->Set(value_big.get());
} else {
LogErrorWithValue(__LINE__, "Failed to get current directory", err);
return false;
}
}
// Set USER as required by the Bazel Test Encyclopedia.
bool ExportUserName() {
std::wstring value;
if (!GetEnv(L"USER", &value)) {
return false;
}
if (!value.empty()) {
// Respect the value passed by Bazel via --test_env.
return true;
}
WCHAR buffer[UNLEN + 1];
DWORD len = UNLEN + 1;
if (GetUserNameW(buffer, &len) == 0) {
DWORD err = GetLastError();
LogErrorWithValue(__LINE__, "Failed to query user name", err);
return false;
}
return SetEnv(L"USER", buffer);
}
// Set TEST_SRCDIR as required by the Bazel Test Encyclopedia.
bool ExportSrcPath(const Path& cwd, Path* result) {
if (!GetPathEnv(L"TEST_SRCDIR", result)) {
return false;
}
return !result->Absolutize(cwd) || SetPathEnv(L"TEST_SRCDIR", *result);
}
// Set TEST_TMPDIR as required by the Bazel Test Encyclopedia.
bool ExportTmpPath(const Path& cwd, Path* result) {
if (!GetPathEnv(L"TEST_TMPDIR", result) ||
(result->Absolutize(cwd) && !SetPathEnv(L"TEST_TMPDIR", *result))) {
return false;
}
// Create the test temp directory, which may not exist on the remote host when
// doing a remote build.
return CreateDirectories(*result);
}
// Set HOME as required by the Bazel Test Encyclopedia.
bool ExportHome(const Path& test_tmpdir) {
Path home;
if (!GetPathEnv(L"HOME", &home)) {
return false;
}
if (blaze_util::IsAbsolute(home.Get())) {
// Respect the user-defined HOME in case they set passed it with
// --test_env=HOME or --test_env=HOME=C:\\foo
return true;
} else {
// Set TEST_TMPDIR as required by the Bazel Test Encyclopedia.
return SetPathEnv(L"HOME", test_tmpdir);
}
}
bool ExportRunfiles(const Path& cwd, const Path& test_srcdir) {
Path runfiles_dir;
if (!GetPathEnv(L"RUNFILES_DIR", &runfiles_dir) ||
(runfiles_dir.Absolutize(cwd) &&
!SetPathEnv(L"RUNFILES_DIR", runfiles_dir))) {
return false;
}
// TODO(ulfjack): Standardize on RUNFILES_DIR and remove the
// {JAVA,PYTHON}_RUNFILES vars.
Path java_rf, py_rf;
if (!GetPathEnv(L"JAVA_RUNFILES", &java_rf) ||
(java_rf.Absolutize(cwd) && !SetPathEnv(L"JAVA_RUNFILES", java_rf)) ||
!GetPathEnv(L"PYTHON_RUNFILES", &py_rf) ||
(py_rf.Absolutize(cwd) && !SetPathEnv(L"PYTHON_RUNFILES", py_rf))) {
return false;
}
std::wstring mf_only_str;
int mf_only_value = 0;
if (!GetIntEnv(L"RUNFILES_MANIFEST_ONLY", &mf_only_str, &mf_only_value)) {
return false;
}
if (mf_only_value == 1) {
// If RUNFILES_MANIFEST_ONLY is set to 1 then test programs should use the
// manifest file to find their runfiles.
Path runfiles_mf;
if (!runfiles_mf.Set(test_srcdir.Get() + L"\\MANIFEST") ||
!SetPathEnv(L"RUNFILES_MANIFEST_FILE", runfiles_mf)) {
return false;
}
}
return true;
}
bool ExportShardStatusFile(const Path& cwd) {
Path status_file;
if (!GetPathEnv(L"TEST_SHARD_STATUS_FILE", &status_file) ||
(!status_file.Get().empty() && status_file.Absolutize(cwd) &&
!SetPathEnv(L"TEST_SHARD_STATUS_FILE", status_file))) {
return false;
}
return status_file.Get().empty() ||
// The test shard status file is only set for sharded tests.
CreateDirectories(status_file.Dirname());
}
bool ExportGtestVariables(const Path& test_tmpdir) {
// # Tell googletest about Bazel sharding.
std::wstring total_shards_str;
int total_shards_value = 0;
if (!GetIntEnv(L"TEST_TOTAL_SHARDS", &total_shards_str,
&total_shards_value)) {
return false;
}
if (total_shards_value > 0) {
std::wstring shard_index;
if (!GetEnv(L"TEST_SHARD_INDEX", &shard_index) ||
!SetEnv(L"GTEST_SHARD_INDEX", shard_index) ||
!SetEnv(L"GTEST_TOTAL_SHARDS", total_shards_str)) {
return false;
}
}
return SetPathEnv(L"GTEST_TMP_DIR", test_tmpdir);
}
bool ExportMiscEnvvars(const Path& cwd) {
for (const wchar_t* name :
{L"TEST_INFRASTRUCTURE_FAILURE_FILE", L"TEST_LOGSPLITTER_OUTPUT_FILE",
L"TEST_PREMATURE_EXIT_FILE", L"TEST_UNUSED_RUNFILES_LOG_FILE",
L"TEST_WARNINGS_OUTPUT_FILE"}) {
Path value;
if (!GetPathEnv(name, &value) ||
(value.Absolutize(cwd) && !SetPathEnv(name, value))) {
return false;
}
}
return true;
}
bool _GetFileListRelativeTo(const std::wstring& unc_root,
const std::wstring& subdir, int depth_limit,
std::vector<FileInfo>* result) {
const std::wstring full_subdir =
unc_root + (subdir.empty() ? L"" : (L"\\" + subdir)) + L"\\*";
WIN32_FIND_DATAW info;
HANDLE handle = FindFirstFileW(full_subdir.c_str(), &info);
if (handle == INVALID_HANDLE_VALUE) {
DWORD err = GetLastError();
if (err == ERROR_FILE_NOT_FOUND) {
// No files found, nothing to do.
return true;
}
LogErrorWithArgAndValue(__LINE__, "Failed to list directory contents",
full_subdir, err);
return false;
}
Defer close_handle([handle]() { FindClose(handle); });
static const std::wstring kDot(1, L'.');
static const std::wstring kDotDot(2, L'.');
std::vector<std::wstring> subdirectories;
while (true) {
if (kDot != info.cFileName && kDotDot != info.cFileName) {
std::wstring rel_path =
subdir.empty() ? info.cFileName : (subdir + L"\\" + info.cFileName);
if (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
if (depth_limit != 0) {
// depth_limit is negative ==> unlimited depth
// depth_limit is zero ==> do not recurse further
// depth_limit is positive ==> recurse further
subdirectories.push_back(rel_path);
}
result->push_back(FileInfo(rel_path));
} else {
if (info.nFileSizeHigh > 0 || info.nFileSizeLow > INT_MAX) {
// devtools_ijar::Stat::total_size is declared as `int`, so the file
// size limit is INT_MAX. Additionally we limit the files to be below
// 4 GiB, not only because int is typically 4 bytes long, but also
// because such huge files are unreasonably large as an undeclared
// output.
LogErrorWithArgAndValue(__LINE__, "File is too large to archive",
rel_path, 0);
return false;
}
result->push_back(FileInfo(rel_path,
// File size is already validated to be
// smaller than min(INT_MAX, 4 GiB)
static_cast<int>(info.nFileSizeLow)));
}
}
if (FindNextFileW(handle, &info) == 0) {
DWORD err = GetLastError();
if (err == ERROR_NO_MORE_FILES) {
break;
}
LogErrorWithArgAndValue(__LINE__,
"Failed to get next element in directory",
unc_root + L"\\" + subdir, err);
return false;
}
}
close_handle.DoNow();
if (depth_limit != 0) {
// depth_limit is negative ==> unlimited depth
// depth_limit is zero ==> do not recurse further
// depth_limit is positive ==> recurse further
for (const auto& s : subdirectories) {
if (!_GetFileListRelativeTo(
unc_root, s, depth_limit > 0 ? depth_limit - 1 : depth_limit,
result)) {
return false;
}
}
}
return true;
}
bool GetFileListRelativeTo(const Path& root, std::vector<FileInfo>* result,
int depth_limit = -1) {
if (!blaze_util::IsAbsolute(root.Get())) {
LogError(__LINE__, "Root should be absolute");
return false;
}
return _GetFileListRelativeTo(AddUncPrefixMaybe(root), std::wstring(),
depth_limit, result);
}
bool ToZipEntryPaths(const Path& root, const std::vector<FileInfo>& files,
ZipEntryPaths* result) {
std::string acp_root;
if (!WcsToAcp(AsMixedPath(RemoveUncPrefixMaybe(root)), &acp_root)) {
LogError(__LINE__,
std::wstring(L"Failed to convert path \"") + root.Get() + L"\"");
return false;
}
// Convert all UTF-16 paths to ANSI paths.
std::vector<std::string> acp_file_list;
acp_file_list.reserve(files.size());
for (const auto& e : files) {
std::string acp_path;
if (!WcsToAcp(AsMixedPath(e.RelativePath()), &acp_path)) {
LogError(__LINE__, std::wstring(L"Failed to convert path \"") +
e.RelativePath() + L"\"");
return false;
}
if (e.IsDirectory()) {
acp_path += "/";
}
acp_file_list.push_back(acp_path);
}
result->Create(acp_root, acp_file_list);
return true;
}
bool CreateZipBuilder(const Path& zip, const ZipEntryPaths& entry_paths,
std::unique_ptr<devtools_ijar::ZipBuilder>* result) {
const devtools_ijar::u8 estimated_size =
devtools_ijar::ZipBuilder::EstimateSize(entry_paths.AbsPathPtrs(),
entry_paths.EntryPathPtrs(),
entry_paths.Size());
if (estimated_size == 0) {
LogError(__LINE__, "Failed to estimate zip size");
return false;
}
std::string acp_zip;
if (!WcsToAcp(zip.Get(), &acp_zip)) {
LogError(__LINE__,
std::wstring(L"Failed to convert path \"") + zip.Get() + L"\"");
return false;
}
result->reset(
devtools_ijar::ZipBuilder::Create(acp_zip.c_str(), estimated_size));
if (result->get() == nullptr) {
LogErrorWithValue(__LINE__, "Failed to create zip builder", errno);
return false;
}
return true;
}
bool OpenFileForWriting(const Path& path, bazel::windows::AutoHandle* result) {
HANDLE h = CreateFileW(AddUncPrefixMaybe(path).c_str(), GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (h == INVALID_HANDLE_VALUE) {
DWORD err = GetLastError();
LogErrorWithArgAndValue(__LINE__, "Failed to open file", path.Get(), err);
return false;
}
*result = h;
return true;
}
bool OpenExistingFileForRead(const Path& abs_path,
bazel::windows::AutoHandle* result) {
HANDLE h = CreateFileW(AddUncPrefixMaybe(abs_path).c_str(), GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (h == INVALID_HANDLE_VALUE) {
DWORD err = GetLastError();
LogErrorWithArgAndValue(__LINE__, "Failed to open file", abs_path.Get(),
err);
return false;
}
*result = h;
return true;
}
bool CreateEmptyFile(const Path& path) {
bazel::windows::AutoHandle handle;
return OpenFileForWriting(path, &handle);
}
bool ReadFromFile(HANDLE handle, uint8_t* dest, DWORD max_read) {
if (max_read == 0) {
return true;
}
DWORD total_read = 0;
DWORD read = 0;
do {
if (!ReadFile(handle, dest + total_read, max_read - total_read, &read,
NULL)) {
DWORD err = GetLastError();
LogErrorWithValue(__LINE__, "Failed to read file", err);
return false;
}
total_read += read;
} while (read > 0 && total_read < max_read);
return true;
}
bool ReadCompleteFile(const Path& path, std::unique_ptr<uint8_t[]>* data,
DWORD* size) {
bazel::windows::AutoHandle handle;
if (!OpenExistingFileForRead(path, &handle)) {
LogError(__LINE__, path.Get());
return false;
}
LARGE_INTEGER file_size;
if (!GetFileSizeEx(handle, &file_size)) {
DWORD err = GetLastError();
LogErrorWithValue(__LINE__, path.Get(), err);
return false;
}
// `ReadCompleteFile` doesn't support files larger than 4GB because most files
// that this function will be reading (test outerr logs) are typically smaller
// than that. (A buffered file reader would allow supporting larger files, but
// that seems like overkill here.)
if (file_size.QuadPart > 0xFFFFFFFF) {
LogError(__LINE__, path.Get());
return false;
}
const DWORD file_size_dw = file_size.QuadPart;
*size = file_size_dw;
// Allocate a buffer large enough to hold the whole file.
data->reset(new uint8_t[file_size_dw]);
if (!data->get()) {
// Memory allocation failed.
LogErrorWithValue(__LINE__, path.Get(), file_size_dw);
return false;
}
return ReadFromFile(handle, data->get(), file_size_dw);
}
bool WriteToFile(HANDLE output, const void* buffer, const size_t size) {
// Write `size` many bytes to the output file.
DWORD total_written = 0;
while (total_written < size) {
DWORD written;
if (!WriteFile(output, static_cast<const uint8_t*>(buffer) + total_written,
size - total_written, &written, NULL)) {
DWORD err = GetLastError();
LogErrorWithValue(__LINE__, "Failed to write file", err);
return false;
}
total_written += written;
}
return true;
}
bool AppendFileTo(const Path& file, const size_t total_size, HANDLE output) {
bazel::windows::AutoHandle input;
if (!OpenExistingFileForRead(file, &input)) {
LogError(__LINE__,
std::wstring(L"Failed to open file \"") + file.Get() + L"\"");
return false;
}
const size_t buf_size = std::min<size_t>(total_size, /* 10 MB */ 10000000);
std::unique_ptr<uint8_t[]> buffer(new uint8_t[buf_size]);
while (true) {
// Read at most `buf_size` many bytes from the input file.
DWORD read = 0;
if (!ReadFile(input, buffer.get(), buf_size, &read, NULL)) {
DWORD err = GetLastError();
LogErrorWithArgAndValue(__LINE__, "Failed to read file", file.Get(), err);
return false;
}
if (read == 0) {
// Reached end of input file.
return true;
}
if (!WriteToFile(output, buffer.get(), read)) {
LogError(__LINE__,
std::wstring(L"Failed to append file \"") + file.Get() + L"\"");
return false;
}
}
return true;
}
// Returns the MIME type of the file name.
// If the MIME type is unknown or an error occurs, the method returns
// "application/octet-stream".
std::string GetMimeType(const std::string& filename) {
static constexpr char* kDefaultMimeType = "application/octet-stream";
std::string::size_type pos = filename.find_last_of('.');
if (pos == std::string::npos) {
return kDefaultMimeType;
}
char data[1000];
DWORD data_size = 1000 * sizeof(char);
if (RegGetValueA(HKEY_CLASSES_ROOT, filename.c_str() + pos, "Content Type",
RRF_RT_REG_SZ, NULL, data, &data_size) == ERROR_SUCCESS) {
return data;
}
// The file extension is unknown, or it does not have a "Content Type" value,
// or the value is too long. We don't care; just return the default.
return kDefaultMimeType;
}
bool CreateUndeclaredOutputsManifestContent(const std::vector<FileInfo>& files,
std::string* result) {
std::stringstream stm;
for (const auto& e : files) {
if (!e.IsDirectory()) {
// For each file, write a tab-separated line to the manifest with name
// (relative to TEST_UNDECLARED_OUTPUTS_DIR), size, and mime type.
// Example:
// foo.txt<TAB>9<TAB>text/plain
// bar/baz<TAB>2944<TAB>application/octet-stream
std::string acp_path;
if (!WcsToAcp(AsMixedPath(e.RelativePath()), &acp_path)) {
return false;
}
stm << acp_path << "\t" << e.Size() << "\t" << GetMimeType(acp_path)
<< "\n";
}
}
*result = stm.str();
return true;
}
bool CreateUndeclaredOutputsManifest(const std::vector<FileInfo>& files,
const Path& output) {
std::string content;
if (!CreateUndeclaredOutputsManifestContent(files, &content)) {
LogError(__LINE__,
std::wstring(L"Failed to create manifest content for file \"") +
output.Get() + L"\"");
return false;
}
bazel::windows::AutoHandle handle;
if (!OpenFileForWriting(output, &handle)) {
LogError(__LINE__, std::wstring(L"Failed to open file for writing \"") +
output.Get() + L"\"");
return false;
}
if (!WriteToFile(handle, content.c_str(), content.size())) {
LogError(__LINE__,
std::wstring(L"Failed to write file \"") + output.Get() + L"\"");
return false;
}
return true;
}
bool ExportXmlPath(const Path& cwd, Path* test_outerr, Path* xml_log) {
if (!GetPathEnv(L"XML_OUTPUT_FILE", xml_log)) {
LogError(__LINE__);
return false;
}
xml_log->Absolutize(cwd);
if (!test_outerr->Set(xml_log->Get() + L".log")) {
LogError(__LINE__);
return false;
}
std::wstring unix_result = AsMixedPath(xml_log->Get());
return SetEnv(L"XML_OUTPUT_FILE", unix_result) &&
// TODO(ulfjack): Update Gunit to accept XML_OUTPUT_FILE and drop the
// GUNIT_OUTPUT env variable.
SetEnv(L"GUNIT_OUTPUT", L"xml:" + unix_result) &&
CreateDirectories(xml_log->Dirname()) && CreateEmptyFile(*test_outerr);
}
devtools_ijar::u4 GetZipAttr(const FileInfo& info) {
// We use these hard-coded Unix permission masks because they are:
// - stable, so the zip file is deterministic
// - useful, because stat_to_zipattr expects a mode_t
static constexpr mode_t kDirectoryMode = 040750; // drwxr-x--- (directory)
static constexpr mode_t kFileMode = 0100640; // -rw-r----- (regular file)
devtools_ijar::Stat file_stat;
file_stat.total_size = info.Size();
file_stat.is_directory = info.IsDirectory();
file_stat.file_mode = info.IsDirectory() ? kDirectoryMode : kFileMode;
return devtools_ijar::stat_to_zipattr(file_stat);
}
bool GetZipEntryPtr(devtools_ijar::ZipBuilder* zip_builder,
const char* entry_name, const devtools_ijar::u4 attr,
devtools_ijar::u1** result) {
*result = zip_builder->NewFile(entry_name, attr);
if (*result == nullptr) {
LogError(__LINE__, std::string("Failed to add new zip entry for file \"") +
entry_name + "\": " + zip_builder->GetError());
return false;
}
return true;
}
bool CreateZip(const Path& root, const std::vector<FileInfo>& files,
const Path& abs_zip) {
bool restore_oem_api = false;
if (!AreFileApisANSI()) {
// devtools_ijar::ZipBuilder uses the ANSI file APIs so we must set the
// active code page to ANSI.
SetFileApisToANSI();
restore_oem_api = true;
}
Defer restore_file_apis([restore_oem_api]() {
if (restore_oem_api) {
SetFileApisToOEM();
}
});
ZipEntryPaths zip_entry_paths;
if (!ToZipEntryPaths(root, files, &zip_entry_paths)) {
LogError(__LINE__, "Failed to create zip entry paths");
return false;
}
std::unique_ptr<devtools_ijar::ZipBuilder> zip_builder;
if (!CreateZipBuilder(abs_zip, zip_entry_paths, &zip_builder)) {
LogError(__LINE__, "Failed to create zip builder");
return false;
}
for (size_t i = 0; i < files.size(); ++i) {
bazel::windows::AutoHandle handle;
Path path;
if (!path.Set(root.Get() + L"\\" + files[i].RelativePath()) ||
(!files[i].IsDirectory() && !OpenExistingFileForRead(path, &handle))) {
LogError(__LINE__,
std::wstring(L"Failed to open file \"") + path.Get() + L"\"");
return false;
}
devtools_ijar::u1* dest;
if (!GetZipEntryPtr(zip_builder.get(), zip_entry_paths.EntryPathPtrs()[i],
GetZipAttr(files[i]), &dest) ||
(!files[i].IsDirectory() &&
!ReadFromFile(handle, dest, files[i].Size()))) {
LogError(__LINE__, std::wstring(L"Failed to dump file \"") + path.Get() +
L"\" into zip");
return false;
}
if (zip_builder->FinishFile(files[i].Size(), /* compress */ false,
/* compute_crc */ true) == -1) {
LogError(__LINE__, std::wstring(L"Failed to finish writing file \"") +
path.Get() + L"\" to zip");
return false;
}
}
if (zip_builder->Finish() == -1) {
LogError(__LINE__, std::string("Failed to add file to zip: ") +
zip_builder->GetError());
return false;
}
return true;
}
bool GetAndUnexportUndeclaredOutputsEnvvars(const Path& cwd,
UndeclaredOutputs* result) {
// The test may only see TEST_UNDECLARED_OUTPUTS_DIR and
// TEST_UNDECLARED_OUTPUTS_ANNOTATIONS_DIR, so keep those but unexport others.
if (!GetPathEnv(L"TEST_UNDECLARED_OUTPUTS_ZIP", &(result->zip)) ||
!UnsetEnv(L"TEST_UNDECLARED_OUTPUTS_ZIP") ||
!GetPathEnv(L"TEST_UNDECLARED_OUTPUTS_MANIFEST", &(result->manifest)) ||
!UnsetEnv(L"TEST_UNDECLARED_OUTPUTS_MANIFEST") ||
!GetPathEnv(L"TEST_UNDECLARED_OUTPUTS_ANNOTATIONS",
&(result->annotations)) ||
!UnsetEnv(L"TEST_UNDECLARED_OUTPUTS_ANNOTATIONS") ||
!GetPathEnv(L"TEST_UNDECLARED_OUTPUTS_DIR", &(result->root)) ||
!GetPathEnv(L"TEST_UNDECLARED_OUTPUTS_ANNOTATIONS_DIR",
&(result->annotations_dir))) {
return false;
}
result->root.Absolutize(cwd);
result->annotations_dir.Absolutize(cwd);
result->zip.Absolutize(cwd);
result->manifest.Absolutize(cwd);
result->annotations.Absolutize(cwd);
return SetPathEnv(L"TEST_UNDECLARED_OUTPUTS_DIR", result->root) &&
SetPathEnv(L"TEST_UNDECLARED_OUTPUTS_ANNOTATIONS_DIR",
result->annotations_dir) &&