forked from KirillOsenkov/MSBuildStructuredLog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBuildEventArgsReader.cs
2133 lines (1834 loc) · 79 KB
/
BuildEventArgsReader.cs
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) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using DotUtils.StreamUtils;
using Microsoft.Build.BackEnd;
using Microsoft.Build.Framework;
using Microsoft.Build.Framework.Profiler;
using Microsoft.Build.Shared;
using StructuredLogger.BinaryLogger;
namespace Microsoft.Build.Logging.StructuredLogger
{
/// <summary>
/// Deserializes and returns BuildEventArgs-derived objects from a BinaryReader
/// </summary>
internal partial class BuildEventArgsReader : IBuildEventArgsReaderNotifications, IDisposable
{
private readonly BinaryReader _binaryReader;
// This is used to verify that events deserialization is not overreading expected size.
private readonly TransparentReadStream _readStream;
private readonly int _fileFormatVersion;
private long _recordNumber = 0;
private bool _skipUnknownEvents;
private bool _skipUnknownEventParts;
/// <summary>
/// A list of string records we've encountered so far. If it's a small string, it will be the string directly.
/// If it's a large string, it will be a pointer into a temporary page file where the string content will be
/// written out to. This is necessary so we don't keep all the strings in memory when reading large binlogs.
/// We will OOM otherwise.
/// </summary>
private readonly List<object> stringRecords = new List<object>();
/// <summary>
/// A list of dictionaries we've encountered so far. Dictionaries are referred to by their order in this list.
/// </summary>
/// <remarks>This is designed to not hold on to strings. We just store the string indices and
/// hydrate the dictionary on demand before returning.</remarks>
private readonly List<NameValueRecord> nameValueListRecords = new List<NameValueRecord>();
/// <summary>
/// A "page-file" for storing strings we've read so far. Keeping them in memory would OOM the 32-bit MSBuild
/// when reading large binlogs. This is a no-op in a 64-bit process.
/// </summary>
private readonly StringStorage stringStorage = new StringStorage();
/// <summary>
/// Initializes a new instance of <see cref="BuildEventArgsReader"/> using a <see cref="BinaryReader"/> instance.
/// </summary>
/// <param name="binaryReader">The <see cref="BinaryReader"/> to read <see cref="BuildEventArgs"/> from.</param>
/// <param name="fileFormatVersion">The file format version of the log file being read.</param>
public BuildEventArgsReader(BinaryReader binaryReader, int fileFormatVersion)
{
this._readStream = TransparentReadStream.EnsureTransparentReadStream(binaryReader.BaseStream);
// make sure the reader we're going to use wraps the transparent stream wrapper
this._binaryReader = binaryReader.BaseStream == _readStream
? binaryReader
: new BinaryReader(_readStream);
this._fileFormatVersion = fileFormatVersion;
}
/// <summary>
/// Directs whether the passed <see cref="BinaryReader"/> should be closed when this instance is disposed.
/// Defaults to "false".
/// </summary>
public bool CloseInput { private get; set; } = false;
public long Position => _readStream.Position;
/// <summary>
/// Indicates whether unknown BuildEvents should be silently skipped. Read returns null otherwise.
/// Parameter is supported only if the file format supports forward compatible reading (version is 18 or higher).
/// </summary>
public bool SkipUnknownEvents
{
set
{
if (value)
{
EnsureForwardCompatibleReadingSupported();
}
_skipUnknownEvents = value;
}
}
/// <summary>
/// Indicates whether unread parts of BuildEvents (probably added in newer format of particular BuildEvent)should be silently skipped. Exception thrown otherwise.
/// Parameter is supported only if the file format supports forward compatible reading (version is 18 or higher).
/// </summary>
public bool SkipUnknownEventParts
{
set
{
if (value)
{
EnsureForwardCompatibleReadingSupported();
}
_skipUnknownEventParts = value;
}
}
private void EnsureForwardCompatibleReadingSupported()
{
if (_fileFormatVersion < BinaryLogger.ForwardCompatibilityMinimalVersion)
{
throw new InvalidOperationException(
$"Forward compatible reading is not supported for file format version {_fileFormatVersion} (needs >= 18).");
}
}
/// <summary>
/// Receives recoverable errors during reading. See <see cref="IBuildEventArgsReaderNotifications.RecoverableReadError"/> for documentation on arguments.
/// Applicable mainly when <see cref="SkipUnknownEvents"/> or <see cref="SkipUnknownEventParts"/> is set to true."/>
/// </summary>
public event Action<BinaryLogReaderErrorEventArgs>? RecoverableReadError;
public void Dispose()
{
stringStorage.Dispose();
if (CloseInput)
{
_binaryReader.Dispose();
}
}
/// <inheritdoc cref="IBuildEventArgsReaderNotifications.StringReadDone"/>
public event Action<StringReadEventArgs>? StringReadDone;
internal int FileFormatVersion => _fileFormatVersion;
internal int MinimumReaderVersion { get; set; } = BinaryLogger.ForwardCompatibilityMinimalVersion;
/// <inheritdoc cref="IBinaryLogReplaySource.EmbeddedContentRead"/>
internal event Action<EmbeddedContentEventArgs>? EmbeddedContentRead;
/// <inheritdoc cref="IBuildEventArgsReaderNotifications.ArchiveFileEncountered"/>
public event Action<ArchiveFileEventArgs>? ArchiveFileEncountered;
/// <summary>
/// Raised when the log reader encounters a binary blob embedded in the stream.
/// The arguments include the blob kind and the byte buffer with the contents.
/// </summary>
public event Action<BinaryLogRecordKind, byte[]> OnBlobRead;
private SubStream? _lastSubStream;
internal readonly record struct RawRecord(BinaryLogRecordKind RecordKind, Stream Stream);
/// <summary>
/// Reads the next serialized log record from the <see cref="BinaryReader"/>.
/// </summary>
/// <returns>ArraySegment containing serialized BuildEventArgs record</returns>
internal RawRecord ReadRaw()
=> ReadRaw(decodeTextualRecords: true);
/// <summary>
/// Reads the next serialized log record from the <see cref="BinaryReader"/>.
/// </summary>
/// <returns>ArraySegment containing serialized BuildEventArgs record</returns>
internal RawRecord ReadRaw(bool decodeTextualRecords)
{
// This method is internal and condition is checked once before calling in loop,
// so avoiding it here on each call.
// But keeping it for documentation purposes - in case someone will try to call it and debug issues.
////if (_fileFormatVersion < 18)
////{
//// throw new InvalidOperationException(
//// $"Raw data reading is not supported for file format version {_fileFormatVersion} (needs >=18).");
////}
if (_lastSubStream?.IsAtEnd == false)
{
_lastSubStream.ReadToEnd();
}
BinaryLogRecordKind recordKind =
PreprocessRecordsTillNextEvent(decodeTextualRecords ? IsTextualDataRecord : (_ => false));
if (recordKind == BinaryLogRecordKind.EndOfFile)
{
return new(recordKind, Stream.Null);
}
int serializedEventLength = ReadInt32();
Stream stream = _binaryReader.BaseStream.Slice(serializedEventLength);
_lastSubStream = stream as SubStream;
_recordNumber += 1;
return new(recordKind, stream);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void CheckErrorsSubscribed()
{
if ((_skipUnknownEvents || _skipUnknownEventParts) && RecoverableReadError == null)
{
throw new InvalidOperationException(
ResourceUtilities.GetResourceString("Binlog_MissingRecoverableErrorSubscribeError"));
}
}
/// <summary>
/// Reads the next log record from the <see cref="BinaryReader"/>.
/// </summary>
/// <returns>
/// The next <see cref="BuildEventArgs"/>.
/// If there are no more records, returns <see langword="null"/>.
/// </returns>
public BuildEventArgs? Read()
{
CheckErrorsSubscribed();
BuildEventArgs? result = null;
while (result == null)
{
BinaryLogRecordKind recordKind = PreprocessRecordsTillNextEvent(IsAuxiliaryRecord);
if (recordKind == BinaryLogRecordKind.EndOfFile)
{
return null;
}
int serializedEventLength = 0;
if (_fileFormatVersion >= BinaryLogger.ForwardCompatibilityMinimalVersion)
{
serializedEventLength = ReadInt32(); // record length
_readStream.BytesCountAllowedToRead = serializedEventLength;
}
bool hasError = false;
try
{
result = ReadBuildEventArgs(recordKind);
}
catch (Exception e) when (
// We throw this on mismatches in metadata (name-value list, strings index).
e is InvalidDataException ||
// Thrown when BinaryReader is unable to deserialize binary data into expected type.
e is FormatException ||
// Thrown when we attempt to read more bytes than what is in the next event chunk.
(e is EndOfStreamException && _readStream.BytesCountAllowedToReadRemaining <= 0))
{
hasError = true;
int localSerializedEventLength = serializedEventLength;
Exception localException = e;
string ErrorFactory() =>
string.Format("BuildEvent record number {0} (serialized size: {1}) attempted to perform disallowed reads (details: {2}: {3}).",
_recordNumber, localSerializedEventLength, localException.GetType(), localException.Message) + (_skipUnknownEvents
? " Skipping the record."
: string.Empty);
HandleError(ErrorFactory, _skipUnknownEvents, ReaderErrorType.UnknownFormatOfEventData, recordKind, e);
}
if (result == null && !hasError)
{
int localSerializedEventLength = serializedEventLength;
BinaryLogRecordKind localRecordKind = recordKind;
string ErrorFactory() =>
string.Format("BuildEvent record number {0} (serialized size: {1}) is of unsupported type: {2}.",
_recordNumber, localSerializedEventLength, localRecordKind) + (_skipUnknownEvents
? " Skipping the record."
: string.Empty);
HandleError(ErrorFactory, _skipUnknownEvents, ReaderErrorType.UnknownEventType, recordKind);
}
if (_readStream.BytesCountAllowedToReadRemaining > 0)
{
int localSerializedEventLength = serializedEventLength;
string ErrorFactory() => string.Format(
"BuildEvent record number {0} was expected to read exactly {1} bytes from the stream, but read {2} instead.", _recordNumber, localSerializedEventLength,
localSerializedEventLength - _readStream.BytesCountAllowedToReadRemaining);
HandleError(ErrorFactory, _skipUnknownEventParts, ReaderErrorType.UnknownEventData, recordKind);
}
_recordNumber += 1;
}
return result;
void HandleError(FormatErrorMessage msgFactory, bool noThrow, ReaderErrorType readerErrorType, BinaryLogRecordKind recordKind, Exception? innerException = null)
{
if (noThrow)
{
RecoverableReadError?.Invoke(new BinaryLogReaderErrorEventArgs(readerErrorType, recordKind, msgFactory));
SkipBytes(_readStream.BytesCountAllowedToReadRemaining);
}
else
{
throw new InvalidDataException(msgFactory(), innerException);
}
}
}
private BuildEventArgs? ReadBuildEventArgs(BinaryLogRecordKind recordKind)
=> recordKind switch
{
BinaryLogRecordKind.BuildStarted => ReadBuildStartedEventArgs(),
BinaryLogRecordKind.BuildFinished => ReadBuildFinishedEventArgs(),
BinaryLogRecordKind.ProjectStarted => ReadProjectStartedEventArgs(),
BinaryLogRecordKind.ProjectFinished => ReadProjectFinishedEventArgs(),
BinaryLogRecordKind.TargetStarted => ReadTargetStartedEventArgs(),
BinaryLogRecordKind.TargetFinished => ReadTargetFinishedEventArgs(),
BinaryLogRecordKind.TaskStarted => ReadTaskStartedEventArgs(),
BinaryLogRecordKind.TaskFinished => ReadTaskFinishedEventArgs(),
BinaryLogRecordKind.Error => ReadBuildErrorEventArgs(),
BinaryLogRecordKind.Warning => ReadBuildWarningEventArgs(),
BinaryLogRecordKind.Message => ReadBuildMessageEventArgs(),
BinaryLogRecordKind.CriticalBuildMessage => ReadCriticalBuildMessageEventArgs(),
BinaryLogRecordKind.TaskCommandLine => ReadTaskCommandLineEventArgs(),
BinaryLogRecordKind.TaskParameter => ReadTaskParameterEventArgs(),
BinaryLogRecordKind.ProjectEvaluationStarted => ReadProjectEvaluationStartedEventArgs(),
BinaryLogRecordKind.ProjectEvaluationFinished => ReadProjectEvaluationFinishedEventArgs(),
BinaryLogRecordKind.ProjectImported => ReadProjectImportedEventArgs(),
BinaryLogRecordKind.TargetSkipped => ReadTargetSkippedEventArgs(),
BinaryLogRecordKind.EnvironmentVariableRead => ReadEnvironmentVariableReadEventArgs(),
BinaryLogRecordKind.FileUsed => ReadFileUsedEventArgs(),
BinaryLogRecordKind.PropertyReassignment => ReadPropertyReassignmentEventArgs(),
BinaryLogRecordKind.UninitializedPropertyRead => ReadUninitializedPropertyReadEventArgs(),
BinaryLogRecordKind.PropertyInitialValueSet => ReadPropertyInitialValueSetEventArgs(),
BinaryLogRecordKind.AssemblyLoad => ReadAssemblyLoadEventArgs(),
BinaryLogRecordKind.BuildCheckMessage => ReadBuildCheckMessageEventArgs(),
BinaryLogRecordKind.BuildCheckWarning => ReadBuildWarningEventArgs(),
BinaryLogRecordKind.BuildCheckError => ReadBuildErrorEventArgs(),
BinaryLogRecordKind.BuildCheckTracing => ReadBuildCheckTracingEventArgs(),
BinaryLogRecordKind.BuildCheckAcquisition => ReadBuildCheckAcquisitionEventArgs(),
BinaryLogRecordKind.BuildSubmissionStarted => ReadBuildSubmissionStartedEventArgs(),
BinaryLogRecordKind.BuildCanceled => ReadBuildCanceledEventArgs(),
_ => null,
};
private void SkipBytes(int count)
{
_binaryReader.BaseStream.Seek(count, SeekOrigin.Current);
}
private BinaryLogRecordKind PreprocessRecordsTillNextEvent(Func<BinaryLogRecordKind, bool> isPreprocessRecord)
{
_readStream.BytesCountAllowedToRead = null;
BinaryLogRecordKind recordKind = (BinaryLogRecordKind)ReadInt32();
// Skip over data storage records since they don't result in a BuildEventArgs.
// just ingest their data and continue.
while (isPreprocessRecord(recordKind))
{
// these are ordered by commonality
if (recordKind == BinaryLogRecordKind.String)
{
ReadStringRecord();
}
else if (recordKind == BinaryLogRecordKind.NameValueList)
{
ReadNameValueList();
_readStream.BytesCountAllowedToRead = null;
}
else if (recordKind == BinaryLogRecordKind.ProjectImportArchive)
{
ReadEmbeddedContent(recordKind);
}
_recordNumber += 1;
recordKind = (BinaryLogRecordKind)ReadInt32();
}
return recordKind;
}
private static bool IsAuxiliaryRecord(BinaryLogRecordKind recordKind)
{
return recordKind == BinaryLogRecordKind.String
|| recordKind == BinaryLogRecordKind.NameValueList
|| recordKind == BinaryLogRecordKind.ProjectImportArchive;
}
private static bool IsTextualDataRecord(BinaryLogRecordKind recordKind)
{
return recordKind == BinaryLogRecordKind.String
|| recordKind == BinaryLogRecordKind.ProjectImportArchive;
}
private void ReadEmbeddedContent(BinaryLogRecordKind kind)
{
// Work around bad logs caused by https://github.com/dotnet/msbuild/pull/9022#discussion_r1271468212
var canHaveCorruptedSize = kind == BinaryLogRecordKind.ProjectImportArchive && _fileFormatVersion == 16;
Stream embeddedStream = SliceOfEmdeddedContent(canHaveCorruptedSize);
if (ArchiveFileEncountered != null)
{
// We could create ZipArchive over the target stream, and write to that directly,
// however, binlog format needs to know stream size upfront - which is unknown,
// so we would need to write the size after - and that would require the target stream to be seekable (which it's not)
ProjectImportsCollector? projectImportsCollector = null;
if (EmbeddedContentRead != null)
{
projectImportsCollector =
new ProjectImportsCollector(PathUtils.TempPath, false, runOnBackground: false);
}
// We are intentionally not grace handling corrupt embedded stream
using var zipArchive = new ZipArchive(embeddedStream, ZipArchiveMode.Read);
foreach (var entry in zipArchive.Entries/*.OrderBy(e => e.LastWriteTime)*/)
{
var file = ArchiveFile.From(entry, adjustPath: false);
ArchiveFileEventArgs archiveFileEventArgs = new(file);
ArchiveFileEncountered(archiveFileEventArgs);
if (projectImportsCollector != null)
{
var resultFile = archiveFileEventArgs.ArchiveFile;
projectImportsCollector.AddFileFromMemory(
resultFile.FullPath,
resultFile.Text,
makePathAbsolute: false,
entryCreationStamp: entry.LastWriteTime);
}
}
// Once embedded files are replayed one by one - we can send the resulting stream to subscriber
if (OnBlobRead != null || EmbeddedContentRead != null)
{
projectImportsCollector!.ProcessResult(
streamToEmbed => InvokeEmbeddedDataListeners(kind, streamToEmbed),
error => throw new InvalidDataException(error));
projectImportsCollector.DeleteArchive();
}
}
else if (OnBlobRead != null || EmbeddedContentRead != null)
{
InvokeEmbeddedDataListeners(kind, embeddedStream);
}
else
{
embeddedStream.SkipBytes();
}
}
private void InvokeEmbeddedDataListeners(BinaryLogRecordKind kind, Stream embeddedStream)
{
byte[] bytes = null;
// we need to materialize the stream into a byte array
if (OnBlobRead != null)
{
bytes = embeddedStream.ReadToEnd();
OnBlobRead(kind, bytes);
}
if (EmbeddedContentRead != null)
{
// the embed stream was already read - we need to simulate the stream
if (bytes != null)
{
embeddedStream = new MemoryStream(bytes, writable: false);
}
EmbeddedContentRead(new EmbeddedContentEventArgs(kind, embeddedStream));
}
}
private Stream SliceOfEmdeddedContent(bool canHaveCorruptedSize)
{
// Work around bad logs caused by https://github.com/dotnet/msbuild/pull/9022#discussion_r1271468212
if (canHaveCorruptedSize)
{
int length;
// We have to preread some bytes to figure out if the log is buggy,
// so store bytes to backfill for the "real" read later.
byte[] prefixBytes;
// Version 16 is used by both 17.6 and 17.7, but some 17.7 builds have have a bug that writes length
// as a long instead of a 7-bit encoded int. We can detect this by looking for the zip header, which
// is right after the length in either case.
byte[] nextBytes = _binaryReader.ReadBytes(12 /* 8 for the accidental long, 4 for the zip header */ );
// Does the zip header start 8 bytes in? That should never happen with a 7-bit int which should
// take at most 5 bytes.
if (nextBytes[8] == 0x50 && nextBytes[9] == 0x4b && nextBytes[10] == 0x3 && nextBytes[11] == 0x4)
{
// The "buggy 17.7" case. Read the length as a long.
long length64 = BitConverter.ToInt64(nextBytes, 0);
if (length64 > int.MaxValue)
{
throw new NotSupportedException("Embedded archives larger than 2GB are not supported.");
}
length = (int)length64;
prefixBytes = new byte[4];
Array.Copy(nextBytes, 8, prefixBytes, 0, 4);
}
else
{
// The 17.6/correct 17.7 case. Read the length as a 7-bit encoded int.
MemoryStream stream = new MemoryStream(nextBytes);
BinaryReader reader = new BinaryReader(stream);
length = reader.Read7BitEncodedInt();
int bytesRead = (int)reader.BaseStream.Position;
prefixBytes = reader.ReadBytes(12 - bytesRead);
}
Stream prefixStream = new MemoryStream(prefixBytes);
Stream dataStream = _binaryReader.BaseStream.Slice(length - prefixBytes.Length);
return prefixStream.Concat(dataStream);
}
else
{
int length = ReadInt32();
return _binaryReader.BaseStream.Slice(length);
}
}
private readonly List<(int name, int value)> nameValues = new List<(int name, int value)>(4096);
private void ReadNameValueList()
{
if (_fileFormatVersion >= BinaryLogger.ForwardCompatibilityMinimalVersion)
{
_readStream.BytesCountAllowedToRead = ReadInt32();
}
int count = ReadInt32();
if (nameValues.Capacity < count)
{
nameValues.Capacity = count;
}
for (int i = 0; i < count; i++)
{
int key = ReadInt32();
int value = ReadInt32();
nameValues.Add((key, value));
}
var record = new NameValueRecord()
{
Dictionary = CreateDictionary(nameValues)
};
nameValueListRecords.Add(record);
nameValues.Clear();
OnNameValueListRead?.Invoke(record.Dictionary);
}
private IDictionary<string, string> GetNameValueList(int id)
{
id -= BuildEventArgsWriter.NameValueRecordStartIndex;
if (id >= 0 && id < nameValueListRecords.Count)
{
var list = nameValueListRecords[id];
return list.Dictionary;
}
// this should never happen for valid binlogs
throw new InvalidDataException(
$"NameValueList record number {_recordNumber} is invalid: index {id} is not within {nameValueListRecords.Count}.");
}
private void ReadStringRecord()
{
string text = ReadString();
text = text.NormalizeLineBreaks();
object storedString = stringStorage.Add(text);
stringRecords.Add(storedString);
OnStringRead?.Invoke(text);
}
private BuildEventArgs ReadProjectImportedEventArgs()
{
var fields = ReadBuildEventArgsFields(readImportance: true);
bool importIgnored = false;
// the ImportIgnored field was introduced in file format version 3
if (_fileFormatVersion > 2)
{
importIgnored = ReadBoolean();
}
var importedProjectFile = ReadOptionalString();
var unexpandedProject = ReadOptionalString();
var e = new ProjectImportedEventArgs(
fields.LineNumber,
fields.ColumnNumber,
fields.Message,
fields.Arguments);
SetCommonFields(e, fields);
e.ProjectFile = fields.ProjectFile;
e.ImportedProjectFile = importedProjectFile;
e.UnexpandedProject = unexpandedProject;
e.ImportIgnored = importIgnored;
return e;
}
private BuildEventArgs ReadTargetSkippedEventArgs()
{
var fields = ReadBuildEventArgsFields(readImportance: true);
var targetFile = ReadOptionalString();
var targetName = ReadOptionalString();
var parentTarget = ReadOptionalString();
string condition = null;
string evaluatedCondition = null;
bool originallySucceeded = false;
TargetSkipReason skipReason = TargetSkipReason.None;
BuildEventContext originalBuildEventContext = null;
string message = fields.Message;
if (_fileFormatVersion >= 13)
{
condition = ReadOptionalString();
evaluatedCondition = ReadOptionalString();
originallySucceeded = ReadBoolean();
if (_fileFormatVersion == 13)
{
// Attempt to infer skip reason from the data we have
skipReason = condition != null ?
TargetSkipReason.ConditionWasFalse // condition expression only stored when false
: originallySucceeded ?
TargetSkipReason.PreviouslyBuiltSuccessfully
: TargetSkipReason.PreviouslyBuiltUnsuccessfully;
message = GetTargetSkippedMessage(skipReason, targetName, condition, evaluatedCondition, originallySucceeded);
}
}
var buildReason = (TargetBuiltReason)ReadInt32();
if (_fileFormatVersion >= 14)
{
skipReason = (TargetSkipReason)ReadInt32();
originalBuildEventContext = _binaryReader.ReadOptionalBuildEventContext();
message = GetTargetSkippedMessage(skipReason, targetName, condition, evaluatedCondition, originallySucceeded);
}
var e = new TargetSkippedEventArgs(
message);
SetCommonFields(e, fields);
e.ProjectFile = fields.ProjectFile;
e.TargetFile = targetFile;
e.TargetName = targetName;
e.ParentTarget = parentTarget;
e.BuildReason = buildReason;
e.Condition = condition;
e.EvaluatedCondition = evaluatedCondition;
e.OriginallySucceeded = originallySucceeded;
e.SkipReason = skipReason;
e.OriginalBuildEventContext = originalBuildEventContext;
return e;
}
private BuildEventArgs ReadBuildStartedEventArgs()
{
var fields = ReadBuildEventArgsFields();
var environment = ReadStringDictionary();
var e = new BuildStartedEventArgs(
fields.Message,
fields.HelpKeyword,
environment);
SetCommonFields(e, fields);
return e;
}
private BuildEventArgs ReadBuildFinishedEventArgs()
{
var fields = ReadBuildEventArgsFields();
var succeeded = ReadBoolean();
var e = new BuildFinishedEventArgs(
fields.Message,
fields.HelpKeyword,
succeeded,
fields.Timestamp);
SetCommonFields(e, fields);
return e;
}
private BuildEventArgs ReadBuildCanceledEventArgs()
{
var fields = ReadBuildEventArgsFields();
var e = new BuildCanceledEventArgs(
fields.Message,
fields.Timestamp);
SetCommonFields(e, fields);
return e;
}
private BuildEventArgs ReadProjectEvaluationStartedEventArgs()
{
var fields = ReadBuildEventArgsFields();
var projectFile = ReadDeduplicatedString();
var e = new ProjectEvaluationStartedEventArgs(
ResourceUtilities.GetResourceString("EvaluationStarted"),
projectFile)
{
ProjectFile = projectFile
};
SetCommonFields(e, fields);
return e;
}
private BuildEventArgs ReadProjectEvaluationFinishedEventArgs()
{
var fields = ReadBuildEventArgsFields();
var projectFile = ReadDeduplicatedString();
var e = new ProjectEvaluationFinishedEventArgs(
ResourceUtilities.GetResourceString("EvaluationFinished"),
projectFile)
{
ProjectFile = projectFile
};
SetCommonFields(e, fields);
if (_fileFormatVersion >= 12)
{
IEnumerable globalProperties = null;
// In newer versions, we store the global properties always, as it handles
// null and empty within WriteProperties already.
// This saves a single boolean, but mainly doesn't hide the difference between null and empty
// during write->read roundtrip.
if (_fileFormatVersion >= BinaryLogger.ForwardCompatibilityMinimalVersion ||
ReadBoolean())
{
globalProperties = ReadStringDictionary();
}
var propertyList = ReadPropertyList();
var itemList = ReadProjectItems();
e.GlobalProperties = globalProperties;
e.Properties = propertyList;
e.Items = itemList;
}
// ProfilerResult was introduced in version 5
if (_fileFormatVersion > 4)
{
var hasProfileData = ReadBoolean();
if (hasProfileData)
{
var count = ReadInt32();
var d = new Dictionary<EvaluationLocation, ProfiledLocation>(count);
for (int i = 0; i < count; i++)
{
var evaluationLocation = ReadEvaluationLocation();
var profiledLocation = ReadProfiledLocation();
d[evaluationLocation] = profiledLocation;
}
e.ProfilerResult = new ProfilerResult(d);
}
}
return e;
}
private BuildEventArgs ReadProjectStartedEventArgs()
{
var fields = ReadBuildEventArgsFields();
BuildEventContext parentContext = null;
if (ReadBoolean())
{
parentContext = ReadBuildEventContext();
}
var projectFile = ReadOptionalString();
var projectId = ReadInt32();
var targetNames = ReadDeduplicatedString();
var toolsVersion = ReadOptionalString();
IDictionary<string, string> globalProperties = null;
if (_fileFormatVersion > 6)
{
// See ReadProjectEvaluationFinishedEventArgs for details on why we always store global properties in newer version.
if (_fileFormatVersion >= BinaryLogger.ForwardCompatibilityMinimalVersion ||
ReadBoolean())
{
globalProperties = ReadStringDictionary();
}
}
var propertyList = ReadPropertyList();
var itemList = ReadProjectItems();
string message = fields.Message;
if (_fileFormatVersion >= 13)
{
message = GetProjectStartedMessage(projectFile, targetNames);
}
var e = new ProjectStartedEventArgs(
projectId,
message,
fields.HelpKeyword,
projectFile,
targetNames,
propertyList,
itemList,
parentContext,
globalProperties,
toolsVersion);
SetCommonFields(e, fields);
return e;
}
private BuildEventArgs ReadProjectFinishedEventArgs()
{
var fields = ReadBuildEventArgsFields();
var projectFile = ReadOptionalString();
var succeeded = ReadBoolean();
string message = fields.Message;
if (_fileFormatVersion >= 13)
{
message = GetProjectFinishedMessage(succeeded, projectFile);
}
var e = new ProjectFinishedEventArgs(
message,
fields.HelpKeyword,
projectFile,
succeeded,
fields.Timestamp);
SetCommonFields(e, fields);
return e;
}
private BuildEventArgs ReadTargetStartedEventArgs()
{
var fields = ReadBuildEventArgsFields();
var targetName = ReadOptionalString();
var projectFile = ReadOptionalString();
var targetFile = ReadOptionalString();
var parentTarget = ReadOptionalString();
// BuildReason was introduced in version 4
var buildReason = _fileFormatVersion > 3 ? (TargetBuiltReason)ReadInt32() : TargetBuiltReason.None;
string message = fields.Message;
if (_fileFormatVersion >= 13)
{
message = GetTargetStartedMessage(projectFile, targetFile, parentTarget, targetName);
}
var e = new TargetStartedEventArgs(
message,
fields.HelpKeyword,
targetName,
projectFile,
targetFile,
parentTarget,
buildReason,
fields.Timestamp);
SetCommonFields(e, fields);
return e;
}
private BuildEventArgs ReadTargetFinishedEventArgs()
{
var fields = ReadBuildEventArgsFields();
var succeeded = ReadBoolean();
var projectFile = ReadOptionalString();
var targetFile = ReadOptionalString();
var targetName = ReadOptionalString();
var targetOutputItemList = ReadTaskItemList();
string message = fields.Message;
if (_fileFormatVersion >= 13)
{
message = GetTargetFinishedMessage(projectFile, targetName, succeeded);
}
var e = new TargetFinishedEventArgs(
message,
fields.HelpKeyword,
targetName,
projectFile,
targetFile,
succeeded,
fields.Timestamp,
targetOutputItemList);
SetCommonFields(e, fields);
return e;
}
private BuildEventArgs ReadTaskStartedEventArgs()
{
var fields = ReadBuildEventArgsFields();
var taskName = ReadOptionalString();
var projectFile = ReadOptionalString();
var taskFile = ReadOptionalString();
var taskAssemblyLocation = _fileFormatVersion >= 20 ? ReadOptionalString() : null;
string message = fields.Message;
if (_fileFormatVersion >= 13)
{
message = GetTaskStartedMessage(taskName);
}
var e = new TaskStartedEventArgs2(
message,
fields.HelpKeyword,
projectFile,
taskFile,
taskName,
fields.Timestamp);
e.LineNumber = fields.LineNumber;
e.ColumnNumber = fields.ColumnNumber;
e.TaskAssemblyLocation = taskAssemblyLocation;
SetCommonFields(e, fields);
return e;
}
private BuildEventArgs ReadTaskFinishedEventArgs()
{
var fields = ReadBuildEventArgsFields();
var succeeded = ReadBoolean();
var taskName = ReadOptionalString();
var projectFile = ReadOptionalString();
var taskFile = ReadOptionalString();
string message = fields.Message;
if (_fileFormatVersion >= 13)
{
message = GetTaskFinishedMessage(succeeded, taskName);
}
var e = new TaskFinishedEventArgs(
message,
fields.HelpKeyword,
projectFile,
taskFile,
taskName,
succeeded,
fields.Timestamp);
SetCommonFields(e, fields);
return e;
}
private BuildEventArgs ReadBuildErrorEventArgs()
{
var fields = ReadBuildEventArgsFields();
ReadDiagnosticFields(fields);
BuildEventArgs e;
if (fields.Extended == null)
{
e = new BuildErrorEventArgs(
fields.Subcategory,
fields.Code,
fields.File,
fields.LineNumber,
fields.ColumnNumber,
fields.EndLineNumber,
fields.EndColumnNumber,
fields.Message,
fields.HelpKeyword,
fields.SenderName,
fields.Timestamp,
fields.Arguments)