Source code

Revision control

Line Code
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* 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/. */

#include "ipc/IPCMessageUtils.h"

#include "nsBufferedStreams.h"
#include "nsStreamUtils.h"
#include "nsNetCID.h"
#include "nsIClassInfoImpl.h"
#include "mozilla/ipc/InputStreamUtils.h"
#include <algorithm>

#ifdef DEBUG_brendan
#define METERING
#endif

#ifdef METERING
#include <stdio.h>
#define METER(x) x
#define MAX_BIG_SEEKS 20

static struct {
  uint32_t mSeeksWithinBuffer;
  uint32_t mSeeksOutsideBuffer;
  uint32_t mBufferReadUponSeek;
  uint32_t mBufferUnreadUponSeek;
  uint32_t mBytesReadFromBuffer;
  uint32_t mBigSeekIndex;
  struct {
    int64_t mOldOffset;
    int64_t mNewOffset;
  } mBigSeek[MAX_BIG_SEEKS];
} bufstats;
#else
#define METER(x) /* nothing */
#endif

using namespace mozilla::ipc;
using mozilla::Maybe;
using mozilla::Nothing;
using mozilla::Some;

////////////////////////////////////////////////////////////////////////////////
// nsBufferedStream

nsBufferedStream::nsBufferedStream()
    : mBufferSize(0),
      mBuffer(nullptr),
      mBufferStartOffset(0),
      mCursor(0),
      mFillPoint(0),
      mStream(nullptr),
      mBufferDisabled(false),
      mEOF(false),
      mGetBufferCount(0) {}

nsBufferedStream::~nsBufferedStream() { Close(); }

NS_IMPL_ISUPPORTS(nsBufferedStream, nsITellableStream, nsISeekableStream)

nsresult nsBufferedStream::Init(nsISupports* stream, uint32_t bufferSize) {
  NS_ASSERTION(stream, "need to supply a stream");
  NS_ASSERTION(mStream == nullptr, "already inited");
  mStream = stream;
  NS_IF_ADDREF(mStream);
  mBufferSize = bufferSize;
  mBufferStartOffset = 0;
  mCursor = 0;
  mBuffer = new (mozilla::fallible) char[bufferSize];
  if (mBuffer == nullptr) {
    return NS_ERROR_OUT_OF_MEMORY;
  }
  return NS_OK;
}

nsresult nsBufferedStream::Close() {
  NS_IF_RELEASE(mStream);
  if (mBuffer) {
    delete[] mBuffer;
    mBuffer = nullptr;
    mBufferSize = 0;
    mBufferStartOffset = 0;
    mCursor = 0;
    mFillPoint = 0;
  }
#ifdef METERING
  {
    static FILE* tfp;
    if (!tfp) {
      tfp = fopen("/tmp/bufstats", "w");
      if (tfp) {
        setvbuf(tfp, nullptr, _IOLBF, 0);
      }
    }
    if (tfp) {
      fprintf(tfp, "seeks within buffer:    %u\n", bufstats.mSeeksWithinBuffer);
      fprintf(tfp, "seeks outside buffer:   %u\n",
              bufstats.mSeeksOutsideBuffer);
      fprintf(tfp, "buffer read on seek:    %u\n",
              bufstats.mBufferReadUponSeek);
      fprintf(tfp, "buffer unread on seek:  %u\n",
              bufstats.mBufferUnreadUponSeek);
      fprintf(tfp, "bytes read from buffer: %u\n",
              bufstats.mBytesReadFromBuffer);
      for (uint32_t i = 0; i < bufstats.mBigSeekIndex; i++) {
        fprintf(tfp, "bigseek[%u] = {old: %u, new: %u}\n", i,
                bufstats.mBigSeek[i].mOldOffset,
                bufstats.mBigSeek[i].mNewOffset);
      }
    }
  }
#endif
  return NS_OK;
}

NS_IMETHODIMP
nsBufferedStream::Seek(int32_t whence, int64_t offset) {
  if (mStream == nullptr) {
    return NS_BASE_STREAM_CLOSED;
  }

  // If the underlying stream isn't a random access store, then fail early.
  // We could possibly succeed for the case where the seek position denotes
  // something that happens to be read into the buffer, but that would make
  // the failure data-dependent.
  nsresult rv;
  nsCOMPtr<nsISeekableStream> ras = do_QueryInterface(mStream, &rv);
  if (NS_FAILED(rv)) {
#ifdef DEBUG
    NS_WARNING("mStream doesn't QI to nsISeekableStream");
#endif
    return rv;
  }

  int64_t absPos = 0;
  switch (whence) {
    case nsISeekableStream::NS_SEEK_SET:
      absPos = offset;
      break;
    case nsISeekableStream::NS_SEEK_CUR:
      absPos = mBufferStartOffset;
      absPos += mCursor;
      absPos += offset;
      break;
    case nsISeekableStream::NS_SEEK_END:
      absPos = -1;
      break;
    default:
      MOZ_ASSERT_UNREACHABLE("bogus seek whence parameter");
      return NS_ERROR_UNEXPECTED;
  }

  // Let mCursor point into the existing buffer if the new position is
  // between the current cursor and the mFillPoint "fencepost" -- the
  // client may never get around to a Read or Write after this Seek.
  // Read and Write worry about flushing and filling in that event.
  // But if we're at EOF, make sure to pass the seek through to the
  // underlying stream, because it may have auto-closed itself and
  // needs to reopen.
  uint32_t offsetInBuffer = uint32_t(absPos - mBufferStartOffset);
  if (offsetInBuffer <= mFillPoint && !mEOF) {
    METER(bufstats.mSeeksWithinBuffer++);
    mCursor = offsetInBuffer;
    return NS_OK;
  }

  METER(bufstats.mSeeksOutsideBuffer++);
  METER(bufstats.mBufferReadUponSeek += mCursor);
  METER(bufstats.mBufferUnreadUponSeek += mFillPoint - mCursor);
  rv = Flush();
  if (NS_FAILED(rv)) {
#ifdef DEBUG
    NS_WARNING(
        "(debug) Flush returned error within nsBufferedStream::Seek, so we "
        "exit early.");
#endif
    return rv;
  }

  rv = ras->Seek(whence, offset);
  if (NS_FAILED(rv)) {
#ifdef DEBUG
    NS_WARNING(
        "(debug) Error: ras->Seek() returned error within "
        "nsBufferedStream::Seek, so we exit early.");
#endif
    return rv;
  }

  mEOF = false;

  // Recompute whether the offset we're seeking to is in our buffer.
  // Note that we need to recompute because Flush() might have
  // changed mBufferStartOffset.
  offsetInBuffer = uint32_t(absPos - mBufferStartOffset);
  if (offsetInBuffer <= mFillPoint) {
    // It's safe to just set mCursor to offsetInBuffer.  In particular, we
    // want to avoid calling Fill() here since we already have the data that
    // was seeked to and calling Fill() might auto-close our underlying
    // stream in some cases.
    mCursor = offsetInBuffer;
    return NS_OK;
  }

  METER(if (bufstats.mBigSeekIndex < MAX_BIG_SEEKS)
            bufstats.mBigSeek[bufstats.mBigSeekIndex]
                .mOldOffset = mBufferStartOffset + int64_t(mCursor));
  const int64_t minus1 = -1;
  if (absPos == minus1) {
    // then we had the SEEK_END case, above
    int64_t tellPos;
    rv = ras->Tell(&tellPos);
    mBufferStartOffset = tellPos;
    if (NS_FAILED(rv)) {
      return rv;
    }
  } else {
    mBufferStartOffset = absPos;
  }
  METER(if (bufstats.mBigSeekIndex < MAX_BIG_SEEKS)
            bufstats.mBigSeek[bufstats.mBigSeekIndex++]
                .mNewOffset = mBufferStartOffset);

  mFillPoint = mCursor = 0;
  return Fill();
}

NS_IMETHODIMP
nsBufferedStream::Tell(int64_t* result) {
  if (mStream == nullptr) {
    return NS_BASE_STREAM_CLOSED;
  }

  int64_t result64 = mBufferStartOffset;
  result64 += mCursor;
  *result = result64;
  return NS_OK;
}

NS_IMETHODIMP
nsBufferedStream::SetEOF() {
  if (mStream == nullptr) {
    return NS_BASE_STREAM_CLOSED;
  }

  nsresult rv;
  nsCOMPtr<nsISeekableStream> ras = do_QueryInterface(mStream, &rv);
  if (NS_FAILED(rv)) {
    return rv;
  }

  rv = ras->SetEOF();
  if (NS_SUCCEEDED(rv)) {
    mEOF = true;
  }

  return rv;
}

nsresult nsBufferedStream::GetData(nsISupports** aResult) {
  nsCOMPtr<nsISupports> rv(mStream);
  *aResult = rv.forget().take();
  return NS_OK;
}

////////////////////////////////////////////////////////////////////////////////
// nsBufferedInputStream

NS_IMPL_ADDREF_INHERITED(nsBufferedInputStream, nsBufferedStream)
NS_IMPL_RELEASE_INHERITED(nsBufferedInputStream, nsBufferedStream)

NS_IMPL_CLASSINFO(nsBufferedInputStream, nullptr, nsIClassInfo::THREADSAFE,
                  NS_BUFFEREDINPUTSTREAM_CID)

NS_INTERFACE_MAP_BEGIN(nsBufferedInputStream)
  NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsIInputStream, nsIBufferedInputStream)
  NS_INTERFACE_MAP_ENTRY(nsIBufferedInputStream)
  NS_INTERFACE_MAP_ENTRY(nsIStreamBufferAccess)
  NS_INTERFACE_MAP_ENTRY_CONDITIONAL(nsIIPCSerializableInputStream,
                                     mIsIPCSerializable)
  NS_INTERFACE_MAP_ENTRY_CONDITIONAL(nsIAsyncInputStream, mIsAsyncInputStream)
  NS_INTERFACE_MAP_ENTRY_CONDITIONAL(nsIInputStreamCallback,
                                     mIsAsyncInputStream)
  NS_INTERFACE_MAP_ENTRY_CONDITIONAL(nsICloneableInputStream,
                                     mIsCloneableInputStream)
  NS_INTERFACE_MAP_ENTRY_CONDITIONAL(nsIInputStreamLength, mIsInputStreamLength)
  NS_INTERFACE_MAP_ENTRY_CONDITIONAL(nsIAsyncInputStreamLength,
                                     mIsAsyncInputStreamLength)
  NS_INTERFACE_MAP_ENTRY_CONDITIONAL(nsIInputStreamLengthCallback,
                                     mIsAsyncInputStreamLength)
  NS_IMPL_QUERY_CLASSINFO(nsBufferedInputStream)
NS_INTERFACE_MAP_END_INHERITING(nsBufferedStream)

NS_IMPL_CI_INTERFACE_GETTER(nsBufferedInputStream, nsIInputStream,
                            nsIBufferedInputStream, nsISeekableStream,
                            nsITellableStream, nsIStreamBufferAccess)

nsBufferedInputStream::nsBufferedInputStream()
    : nsBufferedStream(),
      mMutex("nsBufferedInputStream::mMutex"),
      mIsIPCSerializable(true),
      mIsAsyncInputStream(false),
      mIsCloneableInputStream(false),
      mIsInputStreamLength(false),
      mIsAsyncInputStreamLength(false) {}

nsresult nsBufferedInputStream::Create(nsISupports* aOuter, REFNSIID aIID,
                                       void** aResult) {
  NS_ENSURE_NO_AGGREGATION(aOuter);

  nsBufferedInputStream* stream = new nsBufferedInputStream();
  if (stream == nullptr) {
    return NS_ERROR_OUT_OF_MEMORY;
  }
  NS_ADDREF(stream);
  nsresult rv = stream->QueryInterface(aIID, aResult);
  NS_RELEASE(stream);
  return rv;
}

NS_IMETHODIMP
nsBufferedInputStream::Init(nsIInputStream* stream, uint32_t bufferSize) {
  nsresult rv = nsBufferedStream::Init(stream, bufferSize);
  NS_ENSURE_SUCCESS(rv, rv);

  {
    nsCOMPtr<nsIIPCSerializableInputStream> stream = do_QueryInterface(mStream);
    mIsIPCSerializable = !!stream;
  }

  {
    nsCOMPtr<nsIAsyncInputStream> stream = do_QueryInterface(mStream);
    mIsAsyncInputStream = !!stream;
  }

  {
    nsCOMPtr<nsICloneableInputStream> stream = do_QueryInterface(mStream);
    mIsCloneableInputStream = !!stream;
  }

  {
    nsCOMPtr<nsIInputStreamLength> stream = do_QueryInterface(mStream);
    mIsInputStreamLength = !!stream;
  }

  {
    nsCOMPtr<nsIAsyncInputStreamLength> stream = do_QueryInterface(mStream);
    mIsAsyncInputStreamLength = !!stream;
  }

  return NS_OK;
}

NS_IMETHODIMP
nsBufferedInputStream::Close() {
  nsresult rv1 = NS_OK, rv2;
  if (mStream) {
    rv1 = Source()->Close();
#ifdef DEBUG
    if (NS_FAILED(rv1)) {
      NS_WARNING(
          "(debug) Error: Source()->Close() returned error (rv1) in "
          "bsBuffedInputStream::Close().");
    };
#endif
    NS_RELEASE(mStream);
  }

  rv2 = nsBufferedStream::Close();

#ifdef DEBUG
  if (NS_FAILED(rv2)) {
    NS_WARNING(
        "(debug) Error: nsBufferedStream::Close() returned error (rv2) within "
        "nsBufferedInputStream::Close().");
  };
#endif

  if (NS_FAILED(rv1)) {
    return rv1;
  }
  return rv2;
}

NS_IMETHODIMP
nsBufferedInputStream::Available(uint64_t* result) {
  *result = 0;

  if (!mStream) {
    return NS_OK;
  }

  uint64_t avail = mFillPoint - mCursor;

  uint64_t tmp;
  nsresult rv = Source()->Available(&tmp);
  if (NS_SUCCEEDED(rv)) {
    avail += tmp;
  }

  if (avail) {
    *result = avail;
    return NS_OK;
  }

  return rv;
}

NS_IMETHODIMP
nsBufferedInputStream::Read(char* buf, uint32_t count, uint32_t* result) {
  if (mBufferDisabled) {
    if (!mStream) {
      *result = 0;
      return NS_OK;
    }
    nsresult rv = Source()->Read(buf, count, result);
    if (NS_SUCCEEDED(rv)) {
      mBufferStartOffset += *result;  // so nsBufferedStream::Tell works
      if (*result == 0) {
        mEOF = true;
      }
    }
    return rv;
  }

  return ReadSegments(NS_CopySegmentToBuffer, buf, count, result);
}

NS_IMETHODIMP
nsBufferedInputStream::ReadSegments(nsWriteSegmentFun writer, void* closure,
                                    uint32_t count, uint32_t* result) {
  *result = 0;

  if (!mStream) {
    return NS_OK;
  }

  nsresult rv = NS_OK;
  while (count > 0) {
    uint32_t amt = std::min(count, mFillPoint - mCursor);
    if (amt > 0) {
      uint32_t read = 0;
      rv = writer(static_cast<nsIBufferedInputStream*>(this), closure,
                  mBuffer + mCursor, *result, amt, &read);
      if (NS_FAILED(rv)) {
        // errors returned from the writer end here!
        rv = NS_OK;
        break;
      }
      *result += read;
      count -= read;
      mCursor += read;
    } else {
      rv = Fill();
      if (NS_FAILED(rv) || mFillPoint == mCursor) {
        break;
      }
    }
  }
  return (*result > 0) ? NS_OK : rv;
}

NS_IMETHODIMP
nsBufferedInputStream::IsNonBlocking(bool* aNonBlocking) {
  if (mStream) {
    return Source()->IsNonBlocking(aNonBlocking);
  }
  return NS_ERROR_NOT_INITIALIZED;
}

NS_IMETHODIMP
nsBufferedInputStream::Fill() {
  if (mBufferDisabled) {
    return NS_OK;
  }
  NS_ENSURE_TRUE(mStream, NS_ERROR_NOT_INITIALIZED);

  nsresult rv;
  int32_t rem = int32_t(mFillPoint - mCursor);
  if (rem > 0) {
    // slide the remainder down to the start of the buffer
    // |<------------->|<--rem-->|<--->|
    // b               c         f     s
    memcpy(mBuffer, mBuffer + mCursor, rem);
  }
  mBufferStartOffset += mCursor;
  mFillPoint = rem;
  mCursor = 0;

  uint32_t amt;
  rv = Source()->Read(mBuffer + mFillPoint, mBufferSize - mFillPoint, &amt);
  if (NS_FAILED(rv)) {
    return rv;
  }

  if (amt == 0) {
    mEOF = true;
  }

  mFillPoint += amt;
  return NS_OK;
}

NS_IMETHODIMP_(char*)
nsBufferedInputStream::GetBuffer(uint32_t aLength, uint32_t aAlignMask) {
  NS_ASSERTION(mGetBufferCount == 0, "nested GetBuffer!");
  if (mGetBufferCount != 0) {
    return nullptr;
  }

  if (mBufferDisabled) {
    return nullptr;
  }

  char* buf = mBuffer + mCursor;
  uint32_t rem = mFillPoint - mCursor;
  if (rem == 0) {
    if (NS_FAILED(Fill())) {
      return nullptr;
    }
    buf = mBuffer + mCursor;
    rem = mFillPoint - mCursor;
  }

  uint32_t mod = (NS_PTR_TO_INT32(buf) & aAlignMask);
  if (mod) {
    uint32_t pad = aAlignMask + 1 - mod;
    if (pad > rem) {
      return nullptr;
    }

    memset(buf, 0, pad);
    mCursor += pad;
    buf += pad;
    rem -= pad;
  }

  if (aLength > rem) {
    return nullptr;
  }
  mGetBufferCount++;
  return buf;
}

NS_IMETHODIMP_(void)
nsBufferedInputStream::PutBuffer(char* aBuffer, uint32_t aLength) {
  NS_ASSERTION(mGetBufferCount == 1, "stray PutBuffer!");
  if (--mGetBufferCount != 0) {
    return;
  }

  NS_ASSERTION(mCursor + aLength <= mFillPoint, "PutBuffer botch");
  mCursor += aLength;
}

NS_IMETHODIMP
nsBufferedInputStream::DisableBuffering() {
  NS_ASSERTION(!mBufferDisabled, "redundant call to DisableBuffering!");
  NS_ASSERTION(mGetBufferCount == 0,
               "DisableBuffer call between GetBuffer and PutBuffer!");
  if (mGetBufferCount != 0) {
    return NS_ERROR_UNEXPECTED;
  }

  // Empty the buffer so nsBufferedStream::Tell works.
  mBufferStartOffset += mCursor;
  mFillPoint = mCursor = 0;
  mBufferDisabled = true;
  return NS_OK;
}

NS_IMETHODIMP
nsBufferedInputStream::EnableBuffering() {
  NS_ASSERTION(mBufferDisabled, "gratuitous call to EnableBuffering!");
  mBufferDisabled = false;
  return NS_OK;
}

NS_IMETHODIMP
nsBufferedInputStream::GetUnbufferedStream(nsISupports** aStream) {
  // Empty the buffer so subsequent i/o trumps any buffered data.
  mBufferStartOffset += mCursor;
  mFillPoint = mCursor = 0;

  *aStream = mStream;
  NS_IF_ADDREF(*aStream);
  return NS_OK;
}

void nsBufferedInputStream::Serialize(InputStreamParams& aParams,
                                      FileDescriptorArray& aFileDescriptors) {
  BufferedInputStreamParams params;

  if (mStream) {
    nsCOMPtr<nsIInputStream> stream = do_QueryInterface(mStream);
    MOZ_ASSERT(stream);

    InputStreamParams wrappedParams;
    InputStreamHelper::SerializeInputStream(stream, wrappedParams,
                                            aFileDescriptors);

    params.optionalStream() = wrappedParams;
  } else {
    params.optionalStream() = mozilla::void_t();
  }

  params.bufferSize() = mBufferSize;

  aParams = params;
}

bool nsBufferedInputStream::Deserialize(
    const InputStreamParams& aParams,
    const FileDescriptorArray& aFileDescriptors) {
  if (aParams.type() != InputStreamParams::TBufferedInputStreamParams) {
    NS_ERROR("Received unknown parameters from the other process!");
    return false;
  }

  const BufferedInputStreamParams& params =
      aParams.get_BufferedInputStreamParams();
  const OptionalInputStreamParams& wrappedParams = params.optionalStream();

  nsCOMPtr<nsIInputStream> stream;
  if (wrappedParams.type() == OptionalInputStreamParams::TInputStreamParams) {
    stream = InputStreamHelper::DeserializeInputStream(
        wrappedParams.get_InputStreamParams(), aFileDescriptors);
    if (!stream) {
      NS_WARNING("Failed to deserialize wrapped stream!");
      return false;
    }
  } else {
    NS_ASSERTION(wrappedParams.type() == OptionalInputStreamParams::Tvoid_t,
                 "Unknown type for OptionalInputStreamParams!");
  }

  nsresult rv = Init(stream, params.bufferSize());
  NS_ENSURE_SUCCESS(rv, false);

  return true;
}

Maybe<uint64_t> nsBufferedInputStream::ExpectedSerializedLength() {
  nsCOMPtr<nsIIPCSerializableInputStream> stream = do_QueryInterface(mStream);
  if (stream) {
    return stream->ExpectedSerializedLength();
  }
  return Nothing();
}

NS_IMETHODIMP
nsBufferedInputStream::CloseWithStatus(nsresult aStatus) { return Close(); }

NS_IMETHODIMP
nsBufferedInputStream::AsyncWait(nsIInputStreamCallback* aCallback,
                                 uint32_t aFlags, uint32_t aRequestedCount,
                                 nsIEventTarget* aEventTarget) {
  nsCOMPtr<nsIAsyncInputStream> stream = do_QueryInterface(mStream);
  if (!stream) {
    return NS_ERROR_FAILURE;
  }

  nsCOMPtr<nsIInputStreamCallback> callback = aCallback ? this : nullptr;
  {
    MutexAutoLock lock(mMutex);

    if (mAsyncWaitCallback && aCallback) {
      return NS_ERROR_FAILURE;
    }

    mAsyncWaitCallback = aCallback;
  }

  return stream->AsyncWait(callback, aFlags, aRequestedCount, aEventTarget);
}

NS_IMETHODIMP
nsBufferedInputStream::OnInputStreamReady(nsIAsyncInputStream* aStream) {
  nsCOMPtr<nsIInputStreamCallback> callback;
  {
    MutexAutoLock lock(mMutex);

    // We have been canceled in the meanwhile.
    if (!mAsyncWaitCallback) {
      return NS_OK;
    }

    callback.swap(mAsyncWaitCallback);
  }

  MOZ_ASSERT(callback);
  return callback->OnInputStreamReady(this);
}

NS_IMETHODIMP
nsBufferedInputStream::GetData(nsIInputStream** aResult) {
  nsCOMPtr<nsISupports> stream;
  nsBufferedStream::GetData(getter_AddRefs(stream));
  nsCOMPtr<nsIInputStream> inputStream = do_QueryInterface(stream);
  *aResult = inputStream.forget().take();
  return NS_OK;
}

// nsICloneableInputStream interface

NS_IMETHODIMP
nsBufferedInputStream::GetCloneable(bool* aCloneable) {
  *aCloneable = false;

  // If we don't have the buffer, the inputStream has been already closed.
  // If mBufferStartOffset is not 0, the stream has been seeked or read.
  // In both case the cloning is not supported.
  if (!mBuffer || mBufferStartOffset) {
    return NS_OK;
  }

  nsCOMPtr<nsICloneableInputStream> stream = do_QueryInterface(mStream);

  // GetCloneable is infallible.
  NS_ENSURE_TRUE(stream, NS_OK);

  return stream->GetCloneable(aCloneable);
}

NS_IMETHODIMP
nsBufferedInputStream::Clone(nsIInputStream** aResult) {
  if (!mBuffer || mBufferStartOffset) {
    return NS_ERROR_FAILURE;
  }

  nsCOMPtr<nsICloneableInputStream> stream = do_QueryInterface(mStream);
  NS_ENSURE_TRUE(stream, NS_ERROR_FAILURE);

  nsCOMPtr<nsIInputStream> clonedStream;
  nsresult rv = stream->Clone(getter_AddRefs(clonedStream));
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr<nsIBufferedInputStream> bis = new nsBufferedInputStream();
  rv = bis->Init(clonedStream, mBufferSize);
  NS_ENSURE_SUCCESS(rv, rv);

  bis.forget(aResult);
  return NS_OK;
}

// nsIInputStreamLength

NS_IMETHODIMP
nsBufferedInputStream::Length(int64_t* aLength) {
  nsCOMPtr<nsIInputStreamLength> stream = do_QueryInterface(mStream);
  NS_ENSURE_TRUE(stream, NS_ERROR_FAILURE);

  return stream->Length(aLength);
}

// nsIAsyncInputStreamLength

NS_IMETHODIMP
nsBufferedInputStream::AsyncLengthWait(nsIInputStreamLengthCallback* aCallback,
                                       nsIEventTarget* aEventTarget) {
  nsCOMPtr<nsIAsyncInputStreamLength> stream = do_QueryInterface(mStream);
  if (!stream) {
    return NS_ERROR_FAILURE;
  }

  nsCOMPtr<nsIInputStreamLengthCallback> callback = aCallback ? this : nullptr;
  {
    MutexAutoLock lock(mMutex);
    mAsyncInputStreamLengthCallback = aCallback;
  }

  MOZ_ASSERT(stream);
  return stream->AsyncLengthWait(callback, aEventTarget);
}

// nsIInputStreamLengthCallback

NS_IMETHODIMP
nsBufferedInputStream::OnInputStreamLengthReady(
    nsIAsyncInputStreamLength* aStream, int64_t aLength) {
  nsCOMPtr<nsIInputStreamLengthCallback> callback;
  {
    MutexAutoLock lock(mMutex);
    // We have been canceled in the meanwhile.
    if (!mAsyncInputStreamLengthCallback) {
      return NS_OK;
    }

    callback.swap(mAsyncInputStreamLengthCallback);
  }

  MOZ_ASSERT(callback);
  return callback->OnInputStreamLengthReady(this, aLength);
}

////////////////////////////////////////////////////////////////////////////////
// nsBufferedOutputStream

NS_IMPL_ADDREF_INHERITED(nsBufferedOutputStream, nsBufferedStream)
NS_IMPL_RELEASE_INHERITED(nsBufferedOutputStream, nsBufferedStream)
// This QI uses NS_INTERFACE_MAP_ENTRY_CONDITIONAL to check for
// non-nullness of mSafeStream.
NS_INTERFACE_MAP_BEGIN(nsBufferedOutputStream)
  NS_INTERFACE_MAP_ENTRY(nsIOutputStream)
  NS_INTERFACE_MAP_ENTRY_CONDITIONAL(nsISafeOutputStream, mSafeStream)
  NS_INTERFACE_MAP_ENTRY(nsIBufferedOutputStream)
  NS_INTERFACE_MAP_ENTRY(nsIStreamBufferAccess)
NS_INTERFACE_MAP_END_INHERITING(nsBufferedStream)

nsresult nsBufferedOutputStream::Create(nsISupports* aOuter, REFNSIID aIID,
                                        void** aResult) {
  NS_ENSURE_NO_AGGREGATION(aOuter);

  nsBufferedOutputStream* stream = new nsBufferedOutputStream();
  if (stream == nullptr) {
    return NS_ERROR_OUT_OF_MEMORY;
  }
  NS_ADDREF(stream);
  nsresult rv = stream->QueryInterface(aIID, aResult);
  NS_RELEASE(stream);
  return rv;
}

NS_IMETHODIMP
nsBufferedOutputStream::Init(nsIOutputStream* stream, uint32_t bufferSize) {
  // QI stream to an nsISafeOutputStream, to see if we should support it
  mSafeStream = do_QueryInterface(stream);

  return nsBufferedStream::Init(stream, bufferSize);
}

NS_IMETHODIMP
nsBufferedOutputStream::Close() {
  nsresult rv1, rv2 = NS_OK, rv3;

  rv1 = Flush();

#ifdef DEBUG
  if (NS_FAILED(rv1)) {
    NS_WARNING(
        "(debug) Flush() inside nsBufferedOutputStream::Close() returned error "
        "(rv1).");
  }
#endif

  // If we fail to Flush all the data, then we close anyway and drop the
  // remaining data in the buffer. We do this because it's what Unix does
  // for fclose and close. However, we report the error from Flush anyway.
  if (mStream) {
    rv2 = Sink()->Close();
#ifdef DEBUG
    if (NS_FAILED(rv2)) {
      NS_WARNING(
          "(debug) Sink->Close() inside nsBufferedOutputStream::Close() "
          "returned error (rv2).");
    }
#endif
    NS_RELEASE(mStream);
  }
  rv3 = nsBufferedStream::Close();

#ifdef DEBUG
  if (NS_FAILED(rv3)) {
    NS_WARNING(
        "(debug) nsBufferedStream:Close() inside "
        "nsBufferedOutputStream::Close() returned error (rv3).");
  }
#endif

  if (NS_FAILED(rv1)) {
    return rv1;
  }
  if (NS_FAILED(rv2)) {
    return rv2;
  }
  return rv3;
}

NS_IMETHODIMP
nsBufferedOutputStream::Write(const char* buf, uint32_t count,
                              uint32_t* result) {
  nsresult rv = NS_OK;
  uint32_t written = 0;
  *result = 0;
  if (!mStream) {
    // We special case this situtaion.
    // We should catch the failure, NS_BASE_STREAM_CLOSED ASAP, here.
    // If we don't, eventually Flush() is called in the while loop below
    // after so many writes.
    // However, Flush() returns NS_OK when mStream is null (!!),
    // and we don't get a meaningful error, NS_BASE_STREAM_CLOSED,
    // soon enough when we use buffered output.
#ifdef DEBUG
    NS_WARNING(
        "(info) nsBufferedOutputStream::Write returns NS_BASE_STREAM_CLOSED "
        "immediately (mStream==null).");
#endif
    return NS_BASE_STREAM_CLOSED;
  }

  while (count > 0) {
    uint32_t amt = std::min(count, mBufferSize - mCursor);
    if (amt > 0) {
      memcpy(mBuffer + mCursor, buf + written, amt);
      written += amt;
      count -= amt;
      mCursor += amt;
      if (mFillPoint < mCursor) mFillPoint = mCursor;
    } else {
      NS_ASSERTION(mFillPoint, "loop in nsBufferedOutputStream::Write!");
      rv = Flush();
      if (NS_FAILED(rv)) {
#ifdef DEBUG
        NS_WARNING(
            "(debug) Flush() returned error in nsBufferedOutputStream::Write.");
#endif
        break;
      }
    }
  }
  *result = written;
  return (written > 0) ? NS_OK : rv;
}

NS_IMETHODIMP
nsBufferedOutputStream::Flush() {
  nsresult rv;
  uint32_t amt;
  if (!mStream) {
    // Stream already cancelled/flushed; probably because of previous error.
    return NS_OK;
  }
  // optimize : some code within C-C needs to call Seek -> Flush() often.
  if (mFillPoint == 0) {
    return NS_OK;
  }
  rv = Sink()->Write(mBuffer, mFillPoint, &amt);
  if (NS_FAILED(rv)) {
    return rv;
  }
  mBufferStartOffset += amt;
  if (amt == mFillPoint) {
    mFillPoint = mCursor = 0;
    return NS_OK;  // flushed everything
  }

  // slide the remainder down to the start of the buffer
  // |<-------------->|<---|----->|
  // b                a    c      s
  uint32_t rem = mFillPoint - amt;
  memmove(mBuffer, mBuffer + amt, rem);
  mFillPoint = mCursor = rem;
  return NS_ERROR_FAILURE;  // didn't flush all
}

// nsISafeOutputStream
NS_IMETHODIMP
nsBufferedOutputStream::Finish() {
  // flush the stream, to write out any buffered data...
  nsresult rv1 = nsBufferedOutputStream::Flush();
  nsresult rv2 = NS_OK, rv3;

  if (NS_FAILED(rv1)) {
    NS_WARNING(
        "(debug) nsBufferedOutputStream::Flush() failed in "
        "nsBufferedOutputStream::Finish()! Possible dataloss.");

    rv2 = Sink()->Close();
    if (NS_FAILED(rv2)) {
      NS_WARNING(
          "(debug) Sink()->Close() failed in nsBufferedOutputStream::Finish()! "
          "Possible dataloss.");
    }
  } else {
    rv2 = mSafeStream->Finish();
    if (NS_FAILED(rv2)) {
      NS_WARNING(
          "(debug) mSafeStream->Finish() failed within "
          "nsBufferedOutputStream::Flush()! Possible dataloss.");
    }
  }

  // ... and close the buffered stream, so any further attempts to flush/close
  // the buffered stream won't cause errors.
  rv3 = nsBufferedStream::Close();

  // We want to return the errors precisely from Finish()
  // and mimick the existing error handling in
  // nsBufferedOutputStream::Close() as reference.

  if (NS_FAILED(rv1)) {
    return rv1;
  }
  if (NS_FAILED(rv2)) {
    return rv2;
  }
  return rv3;
}

static nsresult nsReadFromInputStream(nsIOutputStream* outStr, void* closure,
                                      char* toRawSegment, uint32_t offset,
                                      uint32_t count, uint32_t* readCount) {
  nsIInputStream* fromStream = (nsIInputStream*)closure;
  return fromStream->Read(toRawSegment, count, readCount);
}

NS_IMETHODIMP
nsBufferedOutputStream::WriteFrom(nsIInputStream* inStr, uint32_t count,
                                  uint32_t* _retval) {
  return WriteSegments(nsReadFromInputStream, inStr, count, _retval);
}

NS_IMETHODIMP
nsBufferedOutputStream::WriteSegments(nsReadSegmentFun reader, void* closure,
                                      uint32_t count, uint32_t* _retval) {
  *_retval = 0;
  nsresult rv;
  while (count > 0) {
    uint32_t left = std::min(count, mBufferSize - mCursor);
    if (left == 0) {
      rv = Flush();
      if (NS_FAILED(rv)) {
        return (*_retval > 0) ? NS_OK : rv;
      }

      continue;
    }

    uint32_t read = 0;
    rv = reader(this, closure, mBuffer + mCursor, *_retval, left, &read);

    if (NS_FAILED(rv)) {  // If we have read some data, return ok
      return (*_retval > 0) ? NS_OK : rv;
    }
    mCursor += read;
    *_retval += read;
    count -= read;
    mFillPoint = std::max(mFillPoint, mCursor);
  }
  return NS_OK;
}

NS_IMETHODIMP
nsBufferedOutputStream::IsNonBlocking(bool* aNonBlocking) {
  if (mStream) {
    return Sink()->IsNonBlocking(aNonBlocking);
  }
  return NS_ERROR_NOT_INITIALIZED;
}

NS_IMETHODIMP_(char*)
nsBufferedOutputStream::GetBuffer(uint32_t aLength, uint32_t aAlignMask) {
  NS_ASSERTION(mGetBufferCount == 0, "nested GetBuffer!");
  if (mGetBufferCount != 0) {
    return nullptr;
  }

  if (mBufferDisabled) {
    return nullptr;
  }

  char* buf = mBuffer + mCursor;
  uint32_t rem = mBufferSize - mCursor;
  if (rem == 0) {
    if (NS_FAILED(Flush())) {
      return nullptr;
    }
    buf = mBuffer + mCursor;
    rem = mBufferSize - mCursor;
  }

  uint32_t mod = (NS_PTR_TO_INT32(buf) & aAlignMask);
  if (mod) {
    uint32_t pad = aAlignMask + 1 - mod;
    if (pad > rem) {
      return nullptr;
    }

    memset(buf, 0, pad);
    mCursor += pad;
    buf += pad;
    rem -= pad;
  }

  if (aLength > rem) {
    return nullptr;
  }
  mGetBufferCount++;
  return buf;
}

NS_IMETHODIMP_(void)
nsBufferedOutputStream::PutBuffer(char* aBuffer, uint32_t aLength) {
  NS_ASSERTION(mGetBufferCount == 1, "stray PutBuffer!");
  if (--mGetBufferCount != 0) {
    return;
  }

  NS_ASSERTION(mCursor + aLength <= mBufferSize, "PutBuffer botch");
  mCursor += aLength;
  if (mFillPoint < mCursor) {
    mFillPoint = mCursor;
  }
}

NS_IMETHODIMP
nsBufferedOutputStream::DisableBuffering() {
  NS_ASSERTION(!mBufferDisabled, "redundant call to DisableBuffering!");
  NS_ASSERTION(mGetBufferCount == 0,
               "DisableBuffer call between GetBuffer and PutBuffer!");
  if (mGetBufferCount != 0) {
    return NS_ERROR_UNEXPECTED;
  }

  // Empty the buffer so nsBufferedStream::Tell works.
  nsresult rv = Flush();
  if (NS_FAILED(rv)) {
    return rv;
  }

  mBufferDisabled = true;
  return NS_OK;
}

NS_IMETHODIMP
nsBufferedOutputStream::EnableBuffering() {
  NS_ASSERTION(mBufferDisabled, "gratuitous call to EnableBuffering!");
  mBufferDisabled = false;
  return NS_OK;
}

NS_IMETHODIMP
nsBufferedOutputStream::GetUnbufferedStream(nsISupports** aStream) {
  // Empty the buffer so subsequent i/o trumps any buffered data.
  if (mFillPoint) {
    nsresult rv = Flush();
    if (NS_FAILED(rv)) {
      return rv;
    }
  }

  *aStream = mStream;
  NS_IF_ADDREF(*aStream);
  return NS_OK;
}

NS_IMETHODIMP
nsBufferedOutputStream::GetData(nsIOutputStream** aResult) {
  nsCOMPtr<nsISupports> stream;
  nsBufferedStream::GetData(getter_AddRefs(stream));
  nsCOMPtr<nsIOutputStream> outputStream = do_QueryInterface(stream);
  *aResult = outputStream.forget().take();
  return NS_OK;
}
#undef METER

////////////////////////////////////////////////////////////////////////////////