forked from Floorp-Projects/Floorp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnsMultiplexInputStream.cpp
1557 lines (1268 loc) · 45 KB
/
nsMultiplexInputStream.cpp
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
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/**
* The multiplex stream concatenates a list of input streams into a single
* stream.
*/
#include "mozilla/Attributes.h"
#include "mozilla/CheckedInt.h"
#include "mozilla/MathAlgorithms.h"
#include "mozilla/Mutex.h"
#include "base/basictypes.h"
#include "nsMultiplexInputStream.h"
#include "nsIBufferedStreams.h"
#include "nsICloneableInputStream.h"
#include "nsIMultiplexInputStream.h"
#include "nsISeekableStream.h"
#include "nsCOMPtr.h"
#include "nsCOMArray.h"
#include "nsIClassInfoImpl.h"
#include "nsIIPCSerializableInputStream.h"
#include "mozilla/ipc/InputStreamUtils.h"
#include "nsIAsyncInputStream.h"
#include "nsIInputStreamLength.h"
#include "nsNetUtil.h"
#include "nsStreamUtils.h"
using namespace mozilla;
using namespace mozilla::ipc;
using mozilla::DeprecatedAbs;
class nsMultiplexInputStream final : public nsIMultiplexInputStream,
public nsISeekableStream,
public nsIIPCSerializableInputStream,
public nsICloneableInputStream,
public nsIAsyncInputStream,
public nsIInputStreamCallback,
public nsIInputStreamLength,
public nsIAsyncInputStreamLength {
public:
nsMultiplexInputStream();
NS_DECL_THREADSAFE_ISUPPORTS
NS_DECL_NSIINPUTSTREAM
NS_DECL_NSIMULTIPLEXINPUTSTREAM
NS_DECL_NSISEEKABLESTREAM
NS_DECL_NSITELLABLESTREAM
NS_DECL_NSIIPCSERIALIZABLEINPUTSTREAM
NS_DECL_NSICLONEABLEINPUTSTREAM
NS_DECL_NSIASYNCINPUTSTREAM
NS_DECL_NSIINPUTSTREAMCALLBACK
NS_DECL_NSIINPUTSTREAMLENGTH
NS_DECL_NSIASYNCINPUTSTREAMLENGTH
// This is used for nsIAsyncInputStream::AsyncWait
void AsyncWaitCompleted();
// This is used for nsIAsyncInputStreamLength::AsyncLengthWait
void AsyncWaitCompleted(int64_t aLength, const MutexAutoLock& aProofOfLock)
MOZ_REQUIRES(mLock);
struct StreamData {
nsresult Initialize(nsIInputStream* aOriginalStream) {
mCurrentPos = 0;
mOriginalStream = aOriginalStream;
mBufferedStream = aOriginalStream;
if (!NS_InputStreamIsBuffered(mBufferedStream)) {
nsCOMPtr<nsIInputStream> bufferedStream;
nsresult rv = NS_NewBufferedInputStream(getter_AddRefs(bufferedStream),
mBufferedStream.forget(), 4096);
NS_ENSURE_SUCCESS(rv, rv);
mBufferedStream = bufferedStream;
}
mAsyncStream = do_QueryInterface(mBufferedStream);
mSeekableStream = do_QueryInterface(mBufferedStream);
return NS_OK;
}
nsCOMPtr<nsIInputStream> mOriginalStream;
// Equal to mOriginalStream or a wrap around the original stream to make it
// buffered.
nsCOMPtr<nsIInputStream> mBufferedStream;
// This can be null.
nsCOMPtr<nsIAsyncInputStream> mAsyncStream;
// This can be null.
nsCOMPtr<nsISeekableStream> mSeekableStream;
uint64_t mCurrentPos;
};
Mutex& GetLock() MOZ_RETURN_CAPABILITY(mLock) { return mLock; }
private:
~nsMultiplexInputStream() = default;
void NextStream() MOZ_REQUIRES(mLock) {
++mCurrentStream;
mStartedReadingCurrent = false;
}
nsresult AsyncWaitInternal();
// This method updates mSeekableStreams, mTellableStreams,
// mIPCSerializableStreams and mCloneableStreams values.
void UpdateQIMap(StreamData& aStream) MOZ_REQUIRES(mLock);
struct MOZ_STACK_CLASS ReadSegmentsState {
nsCOMPtr<nsIInputStream> mThisStream;
uint32_t mOffset;
nsWriteSegmentFun mWriter;
void* mClosure;
bool mDone;
};
void SerializedComplexityInternal(uint32_t aMaxSize, uint32_t* aSizeUsed,
uint32_t* aPipes, uint32_t* aTransferables,
bool* aSerializeAsPipe);
static nsresult ReadSegCb(nsIInputStream* aIn, void* aClosure,
const char* aFromRawSegment, uint32_t aToOffset,
uint32_t aCount, uint32_t* aWriteCount);
bool IsSeekable() const;
bool IsIPCSerializable() const;
bool IsCloneable() const;
bool IsAsyncInputStream() const;
bool IsInputStreamLength() const;
bool IsAsyncInputStreamLength() const;
Mutex mLock; // Protects access to all data members.
nsTArray<StreamData> mStreams MOZ_GUARDED_BY(mLock);
uint32_t mCurrentStream MOZ_GUARDED_BY(mLock);
bool mStartedReadingCurrent MOZ_GUARDED_BY(mLock);
nsresult mStatus MOZ_GUARDED_BY(mLock);
nsCOMPtr<nsIInputStreamCallback> mAsyncWaitCallback MOZ_GUARDED_BY(mLock);
uint32_t mAsyncWaitFlags MOZ_GUARDED_BY(mLock);
uint32_t mAsyncWaitRequestedCount MOZ_GUARDED_BY(mLock);
nsCOMPtr<nsIEventTarget> mAsyncWaitEventTarget MOZ_GUARDED_BY(mLock);
nsCOMPtr<nsIInputStreamLengthCallback> mAsyncWaitLengthCallback
MOZ_GUARDED_BY(mLock);
class AsyncWaitLengthHelper;
RefPtr<AsyncWaitLengthHelper> mAsyncWaitLengthHelper MOZ_GUARDED_BY(mLock);
uint32_t mSeekableStreams MOZ_GUARDED_BY(mLock);
uint32_t mIPCSerializableStreams MOZ_GUARDED_BY(mLock);
uint32_t mCloneableStreams MOZ_GUARDED_BY(mLock);
// These are Atomics so that we can check them in QueryInterface without
// taking a lock (to look at mStreams.Length() and the numbers above)
// With no streams added yet, all of these are possible
Atomic<bool, Relaxed> mIsSeekableStream{true};
Atomic<bool, Relaxed> mIsIPCSerializableStream{true};
Atomic<bool, Relaxed> mIsCloneableStream{true};
Atomic<bool, Relaxed> mIsAsyncInputStream{false};
Atomic<bool, Relaxed> mIsInputStreamLength{false};
Atomic<bool, Relaxed> mIsAsyncInputStreamLength{false};
};
NS_IMPL_ADDREF(nsMultiplexInputStream)
NS_IMPL_RELEASE(nsMultiplexInputStream)
NS_IMPL_CLASSINFO(nsMultiplexInputStream, nullptr, nsIClassInfo::THREADSAFE,
NS_MULTIPLEXINPUTSTREAM_CID)
NS_INTERFACE_MAP_BEGIN(nsMultiplexInputStream)
NS_INTERFACE_MAP_ENTRY(nsIMultiplexInputStream)
NS_INTERFACE_MAP_ENTRY(nsIInputStream)
NS_INTERFACE_MAP_ENTRY_CONDITIONAL(nsISeekableStream, IsSeekable())
NS_INTERFACE_MAP_ENTRY(nsITellableStream)
NS_INTERFACE_MAP_ENTRY_CONDITIONAL(nsIIPCSerializableInputStream,
IsIPCSerializable())
NS_INTERFACE_MAP_ENTRY_CONDITIONAL(nsICloneableInputStream, IsCloneable())
NS_INTERFACE_MAP_ENTRY_CONDITIONAL(nsIAsyncInputStream, IsAsyncInputStream())
NS_INTERFACE_MAP_ENTRY_CONDITIONAL(nsIInputStreamCallback,
IsAsyncInputStream())
NS_INTERFACE_MAP_ENTRY_CONDITIONAL(nsIInputStreamLength,
IsInputStreamLength())
NS_INTERFACE_MAP_ENTRY_CONDITIONAL(nsIAsyncInputStreamLength,
IsAsyncInputStreamLength())
NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIMultiplexInputStream)
NS_IMPL_QUERY_CLASSINFO(nsMultiplexInputStream)
NS_INTERFACE_MAP_END
NS_IMPL_CI_INTERFACE_GETTER(nsMultiplexInputStream, nsIMultiplexInputStream,
nsIInputStream, nsISeekableStream,
nsITellableStream)
static nsresult AvailableMaybeSeek(nsMultiplexInputStream::StreamData& aStream,
uint64_t* aResult) {
nsresult rv = aStream.mBufferedStream->Available(aResult);
if (rv == NS_BASE_STREAM_CLOSED) {
// Blindly seek to the current position if Available() returns
// NS_BASE_STREAM_CLOSED.
// If nsIFileInputStream is closed in Read() due to CLOSE_ON_EOF flag,
// Seek() could reopen the file if REOPEN_ON_REWIND flag is set.
if (aStream.mSeekableStream) {
nsresult rvSeek =
aStream.mSeekableStream->Seek(nsISeekableStream::NS_SEEK_CUR, 0);
if (NS_SUCCEEDED(rvSeek)) {
rv = aStream.mBufferedStream->Available(aResult);
}
}
}
return rv;
}
nsMultiplexInputStream::nsMultiplexInputStream()
: mLock("nsMultiplexInputStream lock"),
mCurrentStream(0),
mStartedReadingCurrent(false),
mStatus(NS_OK),
mAsyncWaitFlags(0),
mAsyncWaitRequestedCount(0),
mSeekableStreams(0),
mIPCSerializableStreams(0),
mCloneableStreams(0) {}
NS_IMETHODIMP
nsMultiplexInputStream::GetCount(uint32_t* aCount) {
MutexAutoLock lock(mLock);
*aCount = mStreams.Length();
return NS_OK;
}
NS_IMETHODIMP
nsMultiplexInputStream::AppendStream(nsIInputStream* aStream) {
MutexAutoLock lock(mLock);
StreamData* streamData = mStreams.AppendElement(fallible);
if (NS_WARN_IF(!streamData)) {
return NS_ERROR_OUT_OF_MEMORY;
}
nsresult rv = streamData->Initialize(aStream);
NS_ENSURE_SUCCESS(rv, rv);
UpdateQIMap(*streamData);
if (mStatus == NS_BASE_STREAM_CLOSED) {
// We were closed, but now we have more data to read.
mStatus = NS_OK;
}
return NS_OK;
}
NS_IMETHODIMP
nsMultiplexInputStream::GetStream(uint32_t aIndex, nsIInputStream** aResult) {
MutexAutoLock lock(mLock);
if (aIndex >= mStreams.Length()) {
return NS_ERROR_NOT_AVAILABLE;
}
StreamData& streamData = mStreams.ElementAt(aIndex);
nsCOMPtr<nsIInputStream> stream = streamData.mOriginalStream;
stream.forget(aResult);
return NS_OK;
}
NS_IMETHODIMP
nsMultiplexInputStream::Close() {
nsTArray<nsCOMPtr<nsIInputStream>> streams;
// Let's take a copy of the streams becuase, calling close() it could trigger
// a nsIInputStreamCallback immediately and we don't want to create a deadlock
// with mutex.
{
MutexAutoLock lock(mLock);
uint32_t len = mStreams.Length();
for (uint32_t i = 0; i < len; ++i) {
if (NS_WARN_IF(
!streams.AppendElement(mStreams[i].mBufferedStream, fallible))) {
mStatus = NS_BASE_STREAM_CLOSED;
return NS_ERROR_OUT_OF_MEMORY;
}
}
mStatus = NS_BASE_STREAM_CLOSED;
}
nsresult rv = NS_OK;
uint32_t len = streams.Length();
for (uint32_t i = 0; i < len; ++i) {
nsresult rv2 = streams[i]->Close();
// We still want to close all streams, but we should return an error
if (NS_FAILED(rv2)) {
rv = rv2;
}
}
return rv;
}
NS_IMETHODIMP
nsMultiplexInputStream::Available(uint64_t* aResult) {
*aResult = 0;
MutexAutoLock lock(mLock);
if (NS_FAILED(mStatus)) {
return mStatus;
}
uint64_t avail = 0;
nsresult rv = NS_BASE_STREAM_CLOSED;
uint32_t len = mStreams.Length();
for (uint32_t i = mCurrentStream; i < len; i++) {
uint64_t streamAvail;
rv = AvailableMaybeSeek(mStreams[i], &streamAvail);
if (rv == NS_BASE_STREAM_CLOSED) {
// If a stream is closed, we continue with the next one.
// If this is the current stream we move to the following stream.
if (mCurrentStream == i) {
NextStream();
}
// If this is the last stream, we want to return this error code.
continue;
}
if (NS_WARN_IF(NS_FAILED(rv))) {
mStatus = rv;
return mStatus;
}
// If the current stream is async, we have to return what we have so far
// without processing the following streams. This is needed because
// ::Available should return only what is currently available. In case of an
// nsIAsyncInputStream, we have to call AsyncWait() in order to read more.
if (mStreams[i].mAsyncStream) {
avail += streamAvail;
break;
}
if (streamAvail == 0) {
// Nothing to read for this stream. Let's move to the next one.
continue;
}
avail += streamAvail;
}
// We still have something to read. We don't want to return an error code yet.
if (avail) {
*aResult = avail;
return NS_OK;
}
// Let's propagate the last error message.
mStatus = rv;
return rv;
}
NS_IMETHODIMP
nsMultiplexInputStream::StreamStatus() {
MutexAutoLock lock(mLock);
return mStatus;
}
NS_IMETHODIMP
nsMultiplexInputStream::Read(char* aBuf, uint32_t aCount, uint32_t* aResult) {
MutexAutoLock lock(mLock);
// It is tempting to implement this method in terms of ReadSegments, but
// that would prevent this class from being used with streams that only
// implement Read (e.g., file streams).
*aResult = 0;
if (mStatus == NS_BASE_STREAM_CLOSED) {
return NS_OK;
}
if (NS_FAILED(mStatus)) {
return mStatus;
}
nsresult rv = NS_OK;
uint32_t len = mStreams.Length();
while (mCurrentStream < len && aCount) {
uint32_t read;
rv = mStreams[mCurrentStream].mBufferedStream->Read(aBuf, aCount, &read);
// XXX some streams return NS_BASE_STREAM_CLOSED to indicate EOF.
// (This is a bug in those stream implementations)
if (rv == NS_BASE_STREAM_CLOSED) {
MOZ_ASSERT_UNREACHABLE(
"Input stream's Read method returned "
"NS_BASE_STREAM_CLOSED");
rv = NS_OK;
read = 0;
} else if (NS_FAILED(rv)) {
break;
}
if (read == 0) {
NextStream();
} else {
NS_ASSERTION(aCount >= read, "Read more than requested");
*aResult += read;
aCount -= read;
aBuf += read;
mStartedReadingCurrent = true;
mStreams[mCurrentStream].mCurrentPos += read;
}
}
return *aResult ? NS_OK : rv;
}
NS_IMETHODIMP
nsMultiplexInputStream::ReadSegments(nsWriteSegmentFun aWriter, void* aClosure,
uint32_t aCount, uint32_t* aResult) {
MutexAutoLock lock(mLock);
if (mStatus == NS_BASE_STREAM_CLOSED) {
*aResult = 0;
return NS_OK;
}
if (NS_FAILED(mStatus)) {
return mStatus;
}
NS_ASSERTION(aWriter, "missing aWriter");
nsresult rv = NS_OK;
ReadSegmentsState state;
state.mThisStream = this;
state.mOffset = 0;
state.mWriter = aWriter;
state.mClosure = aClosure;
state.mDone = false;
uint32_t len = mStreams.Length();
while (mCurrentStream < len && aCount) {
uint32_t read;
rv = mStreams[mCurrentStream].mBufferedStream->ReadSegments(
ReadSegCb, &state, aCount, &read);
// XXX some streams return NS_BASE_STREAM_CLOSED to indicate EOF.
// (This is a bug in those stream implementations)
if (rv == NS_BASE_STREAM_CLOSED) {
MOZ_ASSERT_UNREACHABLE(
"Input stream's Read method returned "
"NS_BASE_STREAM_CLOSED");
rv = NS_OK;
read = 0;
}
// if |aWriter| decided to stop reading segments...
if (state.mDone || NS_FAILED(rv)) {
break;
}
// if stream is empty, then advance to the next stream.
if (read == 0) {
NextStream();
} else {
NS_ASSERTION(aCount >= read, "Read more than requested");
state.mOffset += read;
aCount -= read;
mStartedReadingCurrent = true;
mStreams[mCurrentStream].mCurrentPos += read;
}
}
// if we successfully read some data, then this call succeeded.
*aResult = state.mOffset;
return state.mOffset ? NS_OK : rv;
}
nsresult nsMultiplexInputStream::ReadSegCb(nsIInputStream* aIn, void* aClosure,
const char* aFromRawSegment,
uint32_t aToOffset, uint32_t aCount,
uint32_t* aWriteCount) {
nsresult rv;
ReadSegmentsState* state = (ReadSegmentsState*)aClosure;
rv = (state->mWriter)(state->mThisStream, state->mClosure, aFromRawSegment,
aToOffset + state->mOffset, aCount, aWriteCount);
if (NS_FAILED(rv)) {
state->mDone = true;
}
return rv;
}
NS_IMETHODIMP
nsMultiplexInputStream::IsNonBlocking(bool* aNonBlocking) {
MutexAutoLock lock(mLock);
uint32_t len = mStreams.Length();
if (len == 0) {
// Claim to be non-blocking, since we won't block the caller.
*aNonBlocking = true;
return NS_OK;
}
for (uint32_t i = 0; i < len; ++i) {
nsresult rv = mStreams[i].mBufferedStream->IsNonBlocking(aNonBlocking);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
// If one is blocking the entire stream becomes blocking.
if (!*aNonBlocking) {
return NS_OK;
}
}
return NS_OK;
}
NS_IMETHODIMP
nsMultiplexInputStream::Seek(int32_t aWhence, int64_t aOffset) {
MutexAutoLock lock(mLock);
if (NS_FAILED(mStatus)) {
return mStatus;
}
nsresult rv;
uint32_t oldCurrentStream = mCurrentStream;
bool oldStartedReadingCurrent = mStartedReadingCurrent;
if (aWhence == NS_SEEK_SET) {
int64_t remaining = aOffset;
if (aOffset == 0) {
mCurrentStream = 0;
}
for (uint32_t i = 0; i < mStreams.Length(); ++i) {
nsCOMPtr<nsISeekableStream> stream = mStreams[i].mSeekableStream;
if (!stream) {
return NS_ERROR_FAILURE;
}
// See if all remaining streams should be rewound
if (remaining == 0) {
if (i < oldCurrentStream ||
(i == oldCurrentStream && oldStartedReadingCurrent)) {
rv = stream->Seek(NS_SEEK_SET, 0);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
mStreams[i].mCurrentPos = 0;
continue;
} else {
break;
}
}
// Get position in the current stream
int64_t streamPos;
if (i > oldCurrentStream ||
(i == oldCurrentStream && !oldStartedReadingCurrent)) {
streamPos = 0;
} else {
streamPos = mStreams[i].mCurrentPos;
}
// See if we need to seek the current stream forward or backward
if (remaining < streamPos) {
rv = stream->Seek(NS_SEEK_SET, remaining);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
mStreams[i].mCurrentPos = remaining;
mCurrentStream = i;
mStartedReadingCurrent = remaining != 0;
remaining = 0;
} else if (remaining > streamPos) {
if (i < oldCurrentStream) {
// We're already at end so no need to seek this stream
remaining -= streamPos;
NS_ASSERTION(remaining >= 0, "Remaining invalid");
} else {
uint64_t avail;
rv = AvailableMaybeSeek(mStreams[i], &avail);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
int64_t newPos = XPCOM_MIN(remaining, streamPos + (int64_t)avail);
rv = stream->Seek(NS_SEEK_SET, newPos);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
mStreams[i].mCurrentPos = newPos;
mCurrentStream = i;
mStartedReadingCurrent = true;
remaining -= newPos;
NS_ASSERTION(remaining >= 0, "Remaining invalid");
}
} else {
NS_ASSERTION(remaining == streamPos, "Huh?");
MOZ_ASSERT(remaining != 0, "Zero remaining should be handled earlier");
remaining = 0;
mCurrentStream = i;
mStartedReadingCurrent = true;
}
}
return NS_OK;
}
if (aWhence == NS_SEEK_CUR && aOffset > 0) {
int64_t remaining = aOffset;
for (uint32_t i = mCurrentStream; remaining && i < mStreams.Length(); ++i) {
uint64_t avail;
rv = AvailableMaybeSeek(mStreams[i], &avail);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
int64_t seek = XPCOM_MIN((int64_t)avail, remaining);
rv = mStreams[i].mSeekableStream->Seek(NS_SEEK_CUR, seek);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
mStreams[i].mCurrentPos += seek;
mCurrentStream = i;
mStartedReadingCurrent = true;
remaining -= seek;
}
return NS_OK;
}
if (aWhence == NS_SEEK_CUR && aOffset < 0) {
int64_t remaining = -aOffset;
for (uint32_t i = mCurrentStream; remaining && i != (uint32_t)-1; --i) {
int64_t pos = mStreams[i].mCurrentPos;
int64_t seek = XPCOM_MIN(pos, remaining);
rv = mStreams[i].mSeekableStream->Seek(NS_SEEK_CUR, -seek);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
mStreams[i].mCurrentPos -= seek;
mCurrentStream = i;
mStartedReadingCurrent = seek != -pos;
remaining -= seek;
}
return NS_OK;
}
if (aWhence == NS_SEEK_CUR) {
NS_ASSERTION(aOffset == 0, "Should have handled all non-zero values");
return NS_OK;
}
if (aWhence == NS_SEEK_END) {
if (aOffset > 0) {
return NS_ERROR_INVALID_ARG;
}
int64_t remaining = aOffset;
int32_t i;
for (i = mStreams.Length() - 1; i >= 0; --i) {
nsCOMPtr<nsISeekableStream> stream = mStreams[i].mSeekableStream;
uint64_t avail;
rv = AvailableMaybeSeek(mStreams[i], &avail);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
int64_t streamLength = avail + mStreams[i].mCurrentPos;
// The seek(END) can be completed in the current stream.
if (streamLength >= DeprecatedAbs(remaining)) {
rv = stream->Seek(NS_SEEK_END, remaining);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
mStreams[i].mCurrentPos = streamLength + remaining;
mCurrentStream = i;
mStartedReadingCurrent = true;
break;
}
// We are at the beginning of this stream.
rv = stream->Seek(NS_SEEK_SET, 0);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
remaining += streamLength;
mStreams[i].mCurrentPos = 0;
}
// Any other stream must be set to the end.
for (--i; i >= 0; --i) {
nsCOMPtr<nsISeekableStream> stream = mStreams[i].mSeekableStream;
uint64_t avail;
rv = AvailableMaybeSeek(mStreams[i], &avail);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
int64_t streamLength = avail + mStreams[i].mCurrentPos;
rv = stream->Seek(NS_SEEK_END, 0);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
mStreams[i].mCurrentPos = streamLength;
}
return NS_OK;
}
// other Seeks not implemented yet
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsMultiplexInputStream::Tell(int64_t* aResult) {
MutexAutoLock lock(mLock);
if (NS_FAILED(mStatus)) {
return mStatus;
}
int64_t ret64 = 0;
#ifdef DEBUG
bool zeroFound = false;
#endif
for (uint32_t i = 0; i < mStreams.Length(); ++i) {
ret64 += mStreams[i].mCurrentPos;
#ifdef DEBUG
// When we see 1 stream with currentPos = 0, all the remaining streams must
// be set to 0 as well.
MOZ_ASSERT_IF(zeroFound, mStreams[i].mCurrentPos == 0);
if (mStreams[i].mCurrentPos == 0) {
zeroFound = true;
}
#endif
}
*aResult = ret64;
return NS_OK;
}
NS_IMETHODIMP
nsMultiplexInputStream::SetEOF() { return NS_ERROR_NOT_IMPLEMENTED; }
NS_IMETHODIMP
nsMultiplexInputStream::CloseWithStatus(nsresult aStatus) { return Close(); }
// This class is used to inform nsMultiplexInputStream that it's time to execute
// the asyncWait callback.
class AsyncWaitRunnable final : public DiscardableRunnable {
RefPtr<nsMultiplexInputStream> mStream;
public:
static void Create(nsMultiplexInputStream* aStream,
nsIEventTarget* aEventTarget) {
RefPtr<AsyncWaitRunnable> runnable = new AsyncWaitRunnable(aStream);
if (aEventTarget) {
aEventTarget->Dispatch(runnable.forget(), NS_DISPATCH_NORMAL);
} else {
runnable->Run();
}
}
NS_IMETHOD
Run() override {
mStream->AsyncWaitCompleted();
return NS_OK;
}
private:
explicit AsyncWaitRunnable(nsMultiplexInputStream* aStream)
: DiscardableRunnable("AsyncWaitRunnable"), mStream(aStream) {
MOZ_ASSERT(aStream);
}
};
NS_IMETHODIMP
nsMultiplexInputStream::AsyncWait(nsIInputStreamCallback* aCallback,
uint32_t aFlags, uint32_t aRequestedCount,
nsIEventTarget* aEventTarget) {
{
MutexAutoLock lock(mLock);
// We must execute the callback also when the stream is closed.
if (NS_FAILED(mStatus) && mStatus != NS_BASE_STREAM_CLOSED) {
return mStatus;
}
if (NS_WARN_IF(mAsyncWaitCallback && aCallback &&
mAsyncWaitCallback != aCallback)) {
return NS_ERROR_FAILURE;
}
mAsyncWaitCallback = aCallback;
mAsyncWaitFlags = aFlags;
mAsyncWaitRequestedCount = aRequestedCount;
mAsyncWaitEventTarget = aEventTarget;
}
return AsyncWaitInternal();
}
nsresult nsMultiplexInputStream::AsyncWaitInternal() {
nsCOMPtr<nsIAsyncInputStream> stream;
nsIInputStreamCallback* asyncWaitCallback = nullptr;
uint32_t asyncWaitFlags = 0;
uint32_t asyncWaitRequestedCount = 0;
nsCOMPtr<nsIEventTarget> asyncWaitEventTarget;
{
MutexAutoLock lock(mLock);
// Let's take the first async stream if we are not already closed, and if
// it has data to read or if it async.
if (mStatus != NS_BASE_STREAM_CLOSED) {
for (; mCurrentStream < mStreams.Length(); NextStream()) {
stream = mStreams[mCurrentStream].mAsyncStream;
if (stream) {
break;
}
uint64_t avail = 0;
nsresult rv = AvailableMaybeSeek(mStreams[mCurrentStream], &avail);
if (rv == NS_BASE_STREAM_CLOSED || (NS_SUCCEEDED(rv) && avail == 0)) {
// Nothing to read here. Let's move on.
continue;
}
if (NS_FAILED(rv)) {
return rv;
}
break;
}
}
asyncWaitCallback = mAsyncWaitCallback ? this : nullptr;
asyncWaitFlags = mAsyncWaitFlags;
asyncWaitRequestedCount = mAsyncWaitRequestedCount;
asyncWaitEventTarget = mAsyncWaitEventTarget;
MOZ_ASSERT_IF(stream, NS_SUCCEEDED(mStatus));
}
// If we are here it's because we are already closed, or if the current stream
// is not async. In both case we have to execute the callback.
if (!stream) {
if (asyncWaitCallback) {
AsyncWaitRunnable::Create(this, asyncWaitEventTarget);
}
return NS_OK;
}
return stream->AsyncWait(asyncWaitCallback, asyncWaitFlags,
asyncWaitRequestedCount, asyncWaitEventTarget);
}
NS_IMETHODIMP
nsMultiplexInputStream::OnInputStreamReady(nsIAsyncInputStream* aStream) {
nsCOMPtr<nsIInputStreamCallback> callback;
// When OnInputStreamReady is called, we could be in 2 scenarios:
// a. there is something to read;
// b. the stream is closed.
// But if the stream is closed and it was not the last one, we must proceed
// with the following stream in order to have something to read by the callee.
{
MutexAutoLock lock(mLock);
// The callback has been nullified in the meantime.
if (!mAsyncWaitCallback) {
return NS_OK;
}
if (NS_SUCCEEDED(mStatus)) {
uint64_t avail = 0;
nsresult rv = NS_OK;
// Only check `Available()` if `aStream` is actually the current stream,
// otherwise we'll always want to re-poll, as we got the callback for the
// wrong stream.
if (mCurrentStream < mStreams.Length() &&
aStream == mStreams[mCurrentStream].mAsyncStream) {
rv = aStream->Available(&avail);
}
if (rv == NS_BASE_STREAM_CLOSED || (NS_SUCCEEDED(rv) && avail == 0)) {
// This stream is either closed, has no data available, or is not the
// current stream. If it is closed and current, move to the next stream,
// otherwise re-wait on the current stream until it has data available
// or becomes closed.
// Unlike streams not implementing nsIAsyncInputStream, async streams
// cannot use `Available() == 0` to indicate EOF, so we re-poll in that
// situation.
if (NS_FAILED(rv)) {
NextStream();
}
// Unlock and invoke AsyncWaitInternal to wait again. If this succeeds,
// we'll be called again, otherwise fall through and notify.
MutexAutoUnlock unlock(mLock);
if (NS_SUCCEEDED(AsyncWaitInternal())) {
return NS_OK;
}
}
}
mAsyncWaitCallback.swap(callback);
mAsyncWaitEventTarget = nullptr;
}
return callback ? callback->OnInputStreamReady(this) : NS_OK;
}
void nsMultiplexInputStream::AsyncWaitCompleted() {
nsCOMPtr<nsIInputStreamCallback> callback;
{
MutexAutoLock lock(mLock);
// The callback has been nullified in the meantime.
if (!mAsyncWaitCallback) {
return;
}
mAsyncWaitCallback.swap(callback);
mAsyncWaitEventTarget = nullptr;
}
callback->OnInputStreamReady(this);
}
nsresult nsMultiplexInputStreamConstructor(REFNSIID aIID, void** aResult) {
*aResult = nullptr;
RefPtr<nsMultiplexInputStream> inst = new nsMultiplexInputStream();
return inst->QueryInterface(aIID, aResult);
}
void nsMultiplexInputStream::SerializedComplexity(uint32_t aMaxSize,
uint32_t* aSizeUsed,
uint32_t* aPipes,
uint32_t* aTransferables) {
MutexAutoLock lock(mLock);
bool serializeAsPipe = false;
SerializedComplexityInternal(aMaxSize, aSizeUsed, aPipes, aTransferables,
&serializeAsPipe);
}
void nsMultiplexInputStream::SerializedComplexityInternal(
uint32_t aMaxSize, uint32_t* aSizeUsed, uint32_t* aPipes,
uint32_t* aTransferables, bool* aSerializeAsPipe) {
mLock.AssertCurrentThreadOwns();
CheckedUint32 totalSizeUsed = 0;
CheckedUint32 totalPipes = 0;
CheckedUint32 totalTransferables = 0;
CheckedUint32 maxSize = aMaxSize;
uint32_t streamCount = mStreams.Length();
for (uint32_t index = 0; index < streamCount; index++) {
uint32_t sizeUsed = 0;