1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4  * License, v. 2.0. If a copy of the MPL was not distributed with this
5  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 
7 /**
8  * This file contains implementations of the nsIBinaryInputStream and
9  * nsIBinaryOutputStream interfaces.  Together, these interfaces allows reading
10  * and writing of primitive data types (integers, floating-point values,
11  * booleans, etc.) to a stream in a binary, untagged, fixed-endianness format.
12  * This might be used, for example, to implement network protocols or to
13  * produce architecture-neutral binary disk files, i.e. ones that can be read
14  * and written by both big-endian and little-endian platforms.  Output is
15  * written in big-endian order (high-order byte first), as this is traditional
16  * network order.
17  *
18  * @See nsIBinaryInputStream
19  * @See nsIBinaryOutputStream
20  */
21 #include <algorithm>
22 #include <string.h>
23 
24 #include "nsBinaryStream.h"
25 
26 #include "mozilla/EndianUtils.h"
27 #include "mozilla/PodOperations.h"
28 #include "mozilla/RefPtr.h"
29 #include "mozilla/Span.h"
30 #include "mozilla/UniquePtr.h"
31 
32 #include "nsCRT.h"
33 #include "nsString.h"
34 #include "nsISerializable.h"
35 #include "nsIClassInfo.h"
36 #include "nsComponentManagerUtils.h"
37 #include "nsIURI.h"       // for NS_IURI_IID
38 #include "nsIX509Cert.h"  // for NS_IX509CERT_IID
39 
40 #include "js/ArrayBuffer.h"  // JS::{GetArrayBuffer{,ByteLength},IsArrayBufferObject}
41 #include "js/GCAPI.h"        // JS::AutoCheckCannotGC
42 #include "js/RootingAPI.h"  // JS::{Handle,Rooted}
43 #include "js/Value.h"       // JS::Value
44 
45 using mozilla::AsBytes;
46 using mozilla::MakeUnique;
47 using mozilla::PodCopy;
48 using mozilla::Span;
49 using mozilla::UniquePtr;
50 
NS_NewObjectOutputStream(nsIOutputStream * aOutputStream)51 already_AddRefed<nsIObjectOutputStream> NS_NewObjectOutputStream(
52     nsIOutputStream* aOutputStream) {
53   MOZ_ASSERT(aOutputStream);
54   auto stream = mozilla::MakeRefPtr<nsBinaryOutputStream>();
55 
56   MOZ_ALWAYS_SUCCEEDS(stream->SetOutputStream(aOutputStream));
57   return stream.forget();
58 }
59 
NS_NewObjectInputStream(nsIInputStream * aInputStream)60 already_AddRefed<nsIObjectInputStream> NS_NewObjectInputStream(
61     nsIInputStream* aInputStream) {
62   MOZ_ASSERT(aInputStream);
63   auto stream = mozilla::MakeRefPtr<nsBinaryInputStream>();
64 
65   MOZ_ALWAYS_SUCCEEDS(stream->SetInputStream(aInputStream));
66   return stream.forget();
67 }
68 
NS_IMPL_ISUPPORTS(nsBinaryOutputStream,nsIObjectOutputStream,nsIBinaryOutputStream,nsIOutputStream)69 NS_IMPL_ISUPPORTS(nsBinaryOutputStream, nsIObjectOutputStream,
70                   nsIBinaryOutputStream, nsIOutputStream)
71 
72 NS_IMETHODIMP
73 nsBinaryOutputStream::Flush() {
74   if (NS_WARN_IF(!mOutputStream)) {
75     return NS_ERROR_UNEXPECTED;
76   }
77   return mOutputStream->Flush();
78 }
79 
80 NS_IMETHODIMP
Close()81 nsBinaryOutputStream::Close() {
82   if (NS_WARN_IF(!mOutputStream)) {
83     return NS_ERROR_UNEXPECTED;
84   }
85   return mOutputStream->Close();
86 }
87 
88 NS_IMETHODIMP
Write(const char * aBuf,uint32_t aCount,uint32_t * aActualBytes)89 nsBinaryOutputStream::Write(const char* aBuf, uint32_t aCount,
90                             uint32_t* aActualBytes) {
91   if (NS_WARN_IF(!mOutputStream)) {
92     return NS_ERROR_UNEXPECTED;
93   }
94   return mOutputStream->Write(aBuf, aCount, aActualBytes);
95 }
96 
97 NS_IMETHODIMP
WriteFrom(nsIInputStream * aInStr,uint32_t aCount,uint32_t * aResult)98 nsBinaryOutputStream::WriteFrom(nsIInputStream* aInStr, uint32_t aCount,
99                                 uint32_t* aResult) {
100   MOZ_ASSERT_UNREACHABLE("WriteFrom");
101   return NS_ERROR_NOT_IMPLEMENTED;
102 }
103 
104 NS_IMETHODIMP
WriteSegments(nsReadSegmentFun aReader,void * aClosure,uint32_t aCount,uint32_t * aResult)105 nsBinaryOutputStream::WriteSegments(nsReadSegmentFun aReader, void* aClosure,
106                                     uint32_t aCount, uint32_t* aResult) {
107   MOZ_ASSERT_UNREACHABLE("WriteSegments");
108   return NS_ERROR_NOT_IMPLEMENTED;
109 }
110 
111 NS_IMETHODIMP
IsNonBlocking(bool * aNonBlocking)112 nsBinaryOutputStream::IsNonBlocking(bool* aNonBlocking) {
113   if (NS_WARN_IF(!mOutputStream)) {
114     return NS_ERROR_UNEXPECTED;
115   }
116   return mOutputStream->IsNonBlocking(aNonBlocking);
117 }
118 
WriteFully(const char * aBuf,uint32_t aCount)119 nsresult nsBinaryOutputStream::WriteFully(const char* aBuf, uint32_t aCount) {
120   if (NS_WARN_IF(!mOutputStream)) {
121     return NS_ERROR_UNEXPECTED;
122   }
123 
124   nsresult rv;
125   uint32_t bytesWritten;
126 
127   rv = mOutputStream->Write(aBuf, aCount, &bytesWritten);
128   if (NS_FAILED(rv)) {
129     return rv;
130   }
131   if (bytesWritten != aCount) {
132     return NS_ERROR_FAILURE;
133   }
134   return NS_OK;
135 }
136 
137 NS_IMETHODIMP
SetOutputStream(nsIOutputStream * aOutputStream)138 nsBinaryOutputStream::SetOutputStream(nsIOutputStream* aOutputStream) {
139   if (NS_WARN_IF(!aOutputStream)) {
140     return NS_ERROR_INVALID_ARG;
141   }
142   mOutputStream = aOutputStream;
143   mBufferAccess = do_QueryInterface(aOutputStream);
144   return NS_OK;
145 }
146 
147 NS_IMETHODIMP
WriteBoolean(bool aBoolean)148 nsBinaryOutputStream::WriteBoolean(bool aBoolean) { return Write8(aBoolean); }
149 
150 NS_IMETHODIMP
Write8(uint8_t aByte)151 nsBinaryOutputStream::Write8(uint8_t aByte) {
152   return WriteFully((const char*)&aByte, sizeof(aByte));
153 }
154 
155 NS_IMETHODIMP
Write16(uint16_t aNum)156 nsBinaryOutputStream::Write16(uint16_t aNum) {
157   aNum = mozilla::NativeEndian::swapToBigEndian(aNum);
158   return WriteFully((const char*)&aNum, sizeof(aNum));
159 }
160 
161 NS_IMETHODIMP
Write32(uint32_t aNum)162 nsBinaryOutputStream::Write32(uint32_t aNum) {
163   aNum = mozilla::NativeEndian::swapToBigEndian(aNum);
164   return WriteFully((const char*)&aNum, sizeof(aNum));
165 }
166 
167 NS_IMETHODIMP
Write64(uint64_t aNum)168 nsBinaryOutputStream::Write64(uint64_t aNum) {
169   nsresult rv;
170   uint32_t bytesWritten;
171 
172   aNum = mozilla::NativeEndian::swapToBigEndian(aNum);
173   rv = Write(reinterpret_cast<char*>(&aNum), sizeof(aNum), &bytesWritten);
174   if (NS_FAILED(rv)) {
175     return rv;
176   }
177   if (bytesWritten != sizeof(aNum)) {
178     return NS_ERROR_FAILURE;
179   }
180   return rv;
181 }
182 
183 NS_IMETHODIMP
WriteFloat(float aFloat)184 nsBinaryOutputStream::WriteFloat(float aFloat) {
185   static_assert(sizeof(float) == sizeof(uint32_t),
186                 "False assumption about sizeof(float)");
187   return Write32(*reinterpret_cast<uint32_t*>(&aFloat));
188 }
189 
190 NS_IMETHODIMP
WriteDouble(double aDouble)191 nsBinaryOutputStream::WriteDouble(double aDouble) {
192   static_assert(sizeof(double) == sizeof(uint64_t),
193                 "False assumption about sizeof(double)");
194   return Write64(*reinterpret_cast<uint64_t*>(&aDouble));
195 }
196 
197 NS_IMETHODIMP
WriteStringZ(const char * aString)198 nsBinaryOutputStream::WriteStringZ(const char* aString) {
199   uint32_t length;
200   nsresult rv;
201 
202   length = strlen(aString);
203   rv = Write32(length);
204   if (NS_FAILED(rv)) {
205     return rv;
206   }
207   return WriteFully(aString, length);
208 }
209 
210 NS_IMETHODIMP
WriteWStringZ(const char16_t * aString)211 nsBinaryOutputStream::WriteWStringZ(const char16_t* aString) {
212   uint32_t length = NS_strlen(aString);
213   nsresult rv = Write32(length);
214   if (NS_FAILED(rv)) {
215     return rv;
216   }
217 
218   if (length == 0) {
219     return NS_OK;
220   }
221 
222 #ifdef IS_BIG_ENDIAN
223   rv = WriteBytes(AsBytes(Span(aString, length)));
224 #else
225   // XXX use WriteSegments here to avoid copy!
226   char16_t* copy;
227   char16_t temp[64];
228   if (length <= 64) {
229     copy = temp;
230   } else {
231     copy = static_cast<char16_t*>(malloc(length * sizeof(char16_t)));
232     if (!copy) {
233       return NS_ERROR_OUT_OF_MEMORY;
234     }
235   }
236   NS_ASSERTION((uintptr_t(aString) & 0x1) == 0, "aString not properly aligned");
237   mozilla::NativeEndian::copyAndSwapToBigEndian(copy, aString, length);
238   rv = WriteBytes(AsBytes(Span(copy, length)));
239   if (copy != temp) {
240     free(copy);
241   }
242 #endif
243 
244   return rv;
245 }
246 
247 NS_IMETHODIMP
WriteUtf8Z(const char16_t * aString)248 nsBinaryOutputStream::WriteUtf8Z(const char16_t* aString) {
249   return WriteStringZ(NS_ConvertUTF16toUTF8(aString).get());
250 }
251 
WriteBytes(Span<const uint8_t> aBytes)252 nsresult nsBinaryOutputStream::WriteBytes(Span<const uint8_t> aBytes) {
253   nsresult rv;
254   uint32_t bytesWritten;
255 
256   rv = Write(reinterpret_cast<const char*>(aBytes.Elements()), aBytes.Length(),
257              &bytesWritten);
258   if (NS_FAILED(rv)) {
259     return rv;
260   }
261   if (bytesWritten != aBytes.Length()) {
262     return NS_ERROR_FAILURE;
263   }
264   return rv;
265 }
266 
267 NS_IMETHODIMP
WriteBytesFromJS(const char * aString,uint32_t aLength)268 nsBinaryOutputStream::WriteBytesFromJS(const char* aString, uint32_t aLength) {
269   return WriteBytes(AsBytes(Span(aString, aLength)));
270 }
271 
272 NS_IMETHODIMP
WriteByteArray(const nsTArray<uint8_t> & aByteArray)273 nsBinaryOutputStream::WriteByteArray(const nsTArray<uint8_t>& aByteArray) {
274   return WriteBytes(aByteArray);
275 }
276 
277 NS_IMETHODIMP
WriteObject(nsISupports * aObject,bool aIsStrongRef)278 nsBinaryOutputStream::WriteObject(nsISupports* aObject, bool aIsStrongRef) {
279   return WriteCompoundObject(aObject, NS_GET_IID(nsISupports), aIsStrongRef);
280 }
281 
282 NS_IMETHODIMP
WriteSingleRefObject(nsISupports * aObject)283 nsBinaryOutputStream::WriteSingleRefObject(nsISupports* aObject) {
284   return WriteCompoundObject(aObject, NS_GET_IID(nsISupports), true);
285 }
286 
287 NS_IMETHODIMP
WriteCompoundObject(nsISupports * aObject,const nsIID & aIID,bool aIsStrongRef)288 nsBinaryOutputStream::WriteCompoundObject(nsISupports* aObject,
289                                           const nsIID& aIID,
290                                           bool aIsStrongRef) {
291   nsCOMPtr<nsIClassInfo> classInfo = do_QueryInterface(aObject);
292   nsCOMPtr<nsISerializable> serializable = do_QueryInterface(aObject);
293 
294   // Can't deal with weak refs
295   if (NS_WARN_IF(!aIsStrongRef)) {
296     return NS_ERROR_UNEXPECTED;
297   }
298   if (NS_WARN_IF(!classInfo) || NS_WARN_IF(!serializable)) {
299     return NS_ERROR_NOT_AVAILABLE;
300   }
301 
302   nsCID cid;
303   nsresult rv = classInfo->GetClassIDNoAlloc(&cid);
304   if (NS_SUCCEEDED(rv)) {
305     rv = WriteID(cid);
306   } else {
307     nsCID* cidptr = nullptr;
308     rv = classInfo->GetClassID(&cidptr);
309     if (NS_WARN_IF(NS_FAILED(rv))) {
310       return rv;
311     }
312 
313     rv = WriteID(*cidptr);
314 
315     free(cidptr);
316   }
317 
318   if (NS_WARN_IF(NS_FAILED(rv))) {
319     return rv;
320   }
321 
322   rv = WriteID(aIID);
323   if (NS_WARN_IF(NS_FAILED(rv))) {
324     return rv;
325   }
326 
327   return serializable->Write(this);
328 }
329 
330 NS_IMETHODIMP
WriteID(const nsIID & aIID)331 nsBinaryOutputStream::WriteID(const nsIID& aIID) {
332   nsresult rv = Write32(aIID.m0);
333   if (NS_WARN_IF(NS_FAILED(rv))) {
334     return rv;
335   }
336 
337   rv = Write16(aIID.m1);
338   if (NS_WARN_IF(NS_FAILED(rv))) {
339     return rv;
340   }
341 
342   rv = Write16(aIID.m2);
343   if (NS_WARN_IF(NS_FAILED(rv))) {
344     return rv;
345   }
346 
347   rv = WriteBytes(aIID.m3);
348   if (NS_WARN_IF(NS_FAILED(rv))) {
349     return rv;
350   }
351 
352   return NS_OK;
353 }
354 
NS_IMETHODIMP_(char *)355 NS_IMETHODIMP_(char*)
356 nsBinaryOutputStream::GetBuffer(uint32_t aLength, uint32_t aAlignMask) {
357   if (mBufferAccess) {
358     return mBufferAccess->GetBuffer(aLength, aAlignMask);
359   }
360   return nullptr;
361 }
362 
NS_IMETHODIMP_(void)363 NS_IMETHODIMP_(void)
364 nsBinaryOutputStream::PutBuffer(char* aBuffer, uint32_t aLength) {
365   if (mBufferAccess) {
366     mBufferAccess->PutBuffer(aBuffer, aLength);
367   }
368 }
369 
NS_IMPL_ISUPPORTS(nsBinaryInputStream,nsIObjectInputStream,nsIBinaryInputStream,nsIInputStream)370 NS_IMPL_ISUPPORTS(nsBinaryInputStream, nsIObjectInputStream,
371                   nsIBinaryInputStream, nsIInputStream)
372 
373 NS_IMETHODIMP
374 nsBinaryInputStream::Available(uint64_t* aResult) {
375   if (NS_WARN_IF(!mInputStream)) {
376     return NS_ERROR_UNEXPECTED;
377   }
378   return mInputStream->Available(aResult);
379 }
380 
381 NS_IMETHODIMP
Read(char * aBuffer,uint32_t aCount,uint32_t * aNumRead)382 nsBinaryInputStream::Read(char* aBuffer, uint32_t aCount, uint32_t* aNumRead) {
383   if (NS_WARN_IF(!mInputStream)) {
384     return NS_ERROR_UNEXPECTED;
385   }
386 
387   // mInputStream might give us short reads, so deal with that.
388   uint32_t totalRead = 0;
389 
390   uint32_t bytesRead;
391   do {
392     nsresult rv = mInputStream->Read(aBuffer, aCount, &bytesRead);
393     if (rv == NS_BASE_STREAM_WOULD_BLOCK && totalRead != 0) {
394       // We already read some data.  Return it.
395       break;
396     }
397 
398     if (NS_FAILED(rv)) {
399       return rv;
400     }
401 
402     totalRead += bytesRead;
403     aBuffer += bytesRead;
404     aCount -= bytesRead;
405   } while (aCount != 0 && bytesRead != 0);
406 
407   *aNumRead = totalRead;
408 
409   return NS_OK;
410 }
411 
412 // when forwarding ReadSegments to mInputStream, we need to make sure
413 // 'this' is being passed to the writer each time. To do this, we need
414 // a thunking function which keeps the real input stream around.
415 
416 // the closure wrapper
417 struct MOZ_STACK_CLASS ReadSegmentsClosure {
418   nsCOMPtr<nsIInputStream> mRealInputStream;
419   void* mRealClosure;
420   nsWriteSegmentFun mRealWriter;
421   nsresult mRealResult;
422   uint32_t mBytesRead;  // to properly implement aToOffset
423 };
424 
425 // the thunking function
ReadSegmentForwardingThunk(nsIInputStream * aStream,void * aClosure,const char * aFromSegment,uint32_t aToOffset,uint32_t aCount,uint32_t * aWriteCount)426 static nsresult ReadSegmentForwardingThunk(nsIInputStream* aStream,
427                                            void* aClosure,
428                                            const char* aFromSegment,
429                                            uint32_t aToOffset, uint32_t aCount,
430                                            uint32_t* aWriteCount) {
431   ReadSegmentsClosure* thunkClosure =
432       reinterpret_cast<ReadSegmentsClosure*>(aClosure);
433 
434   NS_ASSERTION(NS_SUCCEEDED(thunkClosure->mRealResult),
435                "How did this get to be a failure status?");
436 
437   thunkClosure->mRealResult = thunkClosure->mRealWriter(
438       thunkClosure->mRealInputStream, thunkClosure->mRealClosure, aFromSegment,
439       thunkClosure->mBytesRead + aToOffset, aCount, aWriteCount);
440 
441   return thunkClosure->mRealResult;
442 }
443 
444 NS_IMETHODIMP
ReadSegments(nsWriteSegmentFun aWriter,void * aClosure,uint32_t aCount,uint32_t * aResult)445 nsBinaryInputStream::ReadSegments(nsWriteSegmentFun aWriter, void* aClosure,
446                                   uint32_t aCount, uint32_t* aResult) {
447   if (NS_WARN_IF(!mInputStream)) {
448     return NS_ERROR_UNEXPECTED;
449   }
450 
451   ReadSegmentsClosure thunkClosure = {this, aClosure, aWriter, NS_OK, 0};
452 
453   // mInputStream might give us short reads, so deal with that.
454   uint32_t bytesRead;
455   do {
456     nsresult rv = mInputStream->ReadSegments(ReadSegmentForwardingThunk,
457                                              &thunkClosure, aCount, &bytesRead);
458 
459     if (rv == NS_BASE_STREAM_WOULD_BLOCK && thunkClosure.mBytesRead != 0) {
460       // We already read some data.  Return it.
461       break;
462     }
463 
464     if (NS_FAILED(rv)) {
465       return rv;
466     }
467 
468     thunkClosure.mBytesRead += bytesRead;
469     aCount -= bytesRead;
470   } while (aCount != 0 && bytesRead != 0 &&
471            NS_SUCCEEDED(thunkClosure.mRealResult));
472 
473   *aResult = thunkClosure.mBytesRead;
474 
475   return NS_OK;
476 }
477 
478 NS_IMETHODIMP
IsNonBlocking(bool * aNonBlocking)479 nsBinaryInputStream::IsNonBlocking(bool* aNonBlocking) {
480   if (NS_WARN_IF(!mInputStream)) {
481     return NS_ERROR_UNEXPECTED;
482   }
483   return mInputStream->IsNonBlocking(aNonBlocking);
484 }
485 
486 NS_IMETHODIMP
Close()487 nsBinaryInputStream::Close() {
488   if (NS_WARN_IF(!mInputStream)) {
489     return NS_ERROR_UNEXPECTED;
490   }
491   return mInputStream->Close();
492 }
493 
494 NS_IMETHODIMP
SetInputStream(nsIInputStream * aInputStream)495 nsBinaryInputStream::SetInputStream(nsIInputStream* aInputStream) {
496   if (NS_WARN_IF(!aInputStream)) {
497     return NS_ERROR_INVALID_ARG;
498   }
499   mInputStream = aInputStream;
500   mBufferAccess = do_QueryInterface(aInputStream);
501   return NS_OK;
502 }
503 
504 NS_IMETHODIMP
ReadBoolean(bool * aBoolean)505 nsBinaryInputStream::ReadBoolean(bool* aBoolean) {
506   uint8_t byteResult;
507   nsresult rv = Read8(&byteResult);
508   if (NS_FAILED(rv)) {
509     return rv;
510   }
511   *aBoolean = !!byteResult;
512   return rv;
513 }
514 
515 NS_IMETHODIMP
Read8(uint8_t * aByte)516 nsBinaryInputStream::Read8(uint8_t* aByte) {
517   nsresult rv;
518   uint32_t bytesRead;
519 
520   rv = Read(reinterpret_cast<char*>(aByte), sizeof(*aByte), &bytesRead);
521   if (NS_FAILED(rv)) {
522     return rv;
523   }
524   if (bytesRead != 1) {
525     return NS_ERROR_FAILURE;
526   }
527   return rv;
528 }
529 
530 NS_IMETHODIMP
Read16(uint16_t * aNum)531 nsBinaryInputStream::Read16(uint16_t* aNum) {
532   uint32_t bytesRead;
533   nsresult rv = Read(reinterpret_cast<char*>(aNum), sizeof(*aNum), &bytesRead);
534   if (NS_FAILED(rv)) {
535     return rv;
536   }
537   if (bytesRead != sizeof(*aNum)) {
538     return NS_ERROR_FAILURE;
539   }
540   *aNum = mozilla::NativeEndian::swapFromBigEndian(*aNum);
541   return rv;
542 }
543 
544 NS_IMETHODIMP
Read32(uint32_t * aNum)545 nsBinaryInputStream::Read32(uint32_t* aNum) {
546   uint32_t bytesRead;
547   nsresult rv = Read(reinterpret_cast<char*>(aNum), sizeof(*aNum), &bytesRead);
548   if (NS_FAILED(rv)) {
549     return rv;
550   }
551   if (bytesRead != sizeof(*aNum)) {
552     return NS_ERROR_FAILURE;
553   }
554   *aNum = mozilla::NativeEndian::swapFromBigEndian(*aNum);
555   return rv;
556 }
557 
558 NS_IMETHODIMP
Read64(uint64_t * aNum)559 nsBinaryInputStream::Read64(uint64_t* aNum) {
560   uint32_t bytesRead;
561   nsresult rv = Read(reinterpret_cast<char*>(aNum), sizeof(*aNum), &bytesRead);
562   if (NS_FAILED(rv)) {
563     return rv;
564   }
565   if (bytesRead != sizeof(*aNum)) {
566     return NS_ERROR_FAILURE;
567   }
568   *aNum = mozilla::NativeEndian::swapFromBigEndian(*aNum);
569   return rv;
570 }
571 
572 NS_IMETHODIMP
ReadFloat(float * aFloat)573 nsBinaryInputStream::ReadFloat(float* aFloat) {
574   static_assert(sizeof(float) == sizeof(uint32_t),
575                 "False assumption about sizeof(float)");
576   return Read32(reinterpret_cast<uint32_t*>(aFloat));
577 }
578 
579 NS_IMETHODIMP
ReadDouble(double * aDouble)580 nsBinaryInputStream::ReadDouble(double* aDouble) {
581   static_assert(sizeof(double) == sizeof(uint64_t),
582                 "False assumption about sizeof(double)");
583   return Read64(reinterpret_cast<uint64_t*>(aDouble));
584 }
585 
WriteSegmentToCString(nsIInputStream * aStream,void * aClosure,const char * aFromSegment,uint32_t aToOffset,uint32_t aCount,uint32_t * aWriteCount)586 static nsresult WriteSegmentToCString(nsIInputStream* aStream, void* aClosure,
587                                       const char* aFromSegment,
588                                       uint32_t aToOffset, uint32_t aCount,
589                                       uint32_t* aWriteCount) {
590   nsACString* outString = static_cast<nsACString*>(aClosure);
591 
592   outString->Append(aFromSegment, aCount);
593 
594   *aWriteCount = aCount;
595 
596   return NS_OK;
597 }
598 
599 NS_IMETHODIMP
ReadCString(nsACString & aString)600 nsBinaryInputStream::ReadCString(nsACString& aString) {
601   nsresult rv;
602   uint32_t length, bytesRead;
603 
604   rv = Read32(&length);
605   if (NS_FAILED(rv)) {
606     return rv;
607   }
608 
609   aString.Truncate();
610   rv = ReadSegments(WriteSegmentToCString, &aString, length, &bytesRead);
611   if (NS_FAILED(rv)) {
612     return rv;
613   }
614 
615   if (bytesRead != length) {
616     return NS_ERROR_FAILURE;
617   }
618 
619   return NS_OK;
620 }
621 
622 // sometimes, WriteSegmentToString will be handed an odd-number of
623 // bytes, which means we only have half of the last char16_t
624 struct WriteStringClosure {
625   char16_t* mWriteCursor;
626   bool mHasCarryoverByte;
627   char mCarryoverByte;
628 };
629 
630 // there are a few cases we have to account for here:
631 // * even length buffer, no carryover - easy, just append
632 // * odd length buffer, no carryover - the last byte needs to be saved
633 //                                     for carryover
634 // * odd length buffer, with carryover - first byte needs to be used
635 //                              with the carryover byte, and
636 //                              the rest of the even length
637 //                              buffer is appended as normal
638 // * even length buffer, with carryover - the first byte needs to be
639 //                              used with the previous carryover byte.
640 //                              this gives you an odd length buffer,
641 //                              so you have to save the last byte for
642 //                              the next carryover
643 
644 // same version of the above, but with correct casting and endian swapping
WriteSegmentToString(nsIInputStream * aStream,void * aClosure,const char * aFromSegment,uint32_t aToOffset,uint32_t aCount,uint32_t * aWriteCount)645 static nsresult WriteSegmentToString(nsIInputStream* aStream, void* aClosure,
646                                      const char* aFromSegment,
647                                      uint32_t aToOffset, uint32_t aCount,
648                                      uint32_t* aWriteCount) {
649   MOZ_ASSERT(aCount > 0, "Why are we being told to write 0 bytes?");
650   static_assert(sizeof(char16_t) == 2, "We can't handle other sizes!");
651 
652   WriteStringClosure* closure = static_cast<WriteStringClosure*>(aClosure);
653   char16_t* cursor = closure->mWriteCursor;
654 
655   // we're always going to consume the whole buffer no matter what
656   // happens, so take care of that right now.. that allows us to
657   // tweak aCount later. Do NOT move this!
658   *aWriteCount = aCount;
659 
660   // if the last Write had an odd-number of bytes read, then
661   if (closure->mHasCarryoverByte) {
662     // re-create the two-byte sequence we want to work with
663     char bytes[2] = {closure->mCarryoverByte, *aFromSegment};
664     *cursor = *(char16_t*)bytes;
665     // Now the little endianness dance
666     mozilla::NativeEndian::swapToBigEndianInPlace(cursor, 1);
667     ++cursor;
668 
669     // now skip past the first byte of the buffer.. code from here
670     // can assume normal operations, but should not assume aCount
671     // is relative to the ORIGINAL buffer
672     ++aFromSegment;
673     --aCount;
674 
675     closure->mHasCarryoverByte = false;
676   }
677 
678   // this array is possibly unaligned... be careful how we access it!
679   const char16_t* unicodeSegment =
680       reinterpret_cast<const char16_t*>(aFromSegment);
681 
682   // calculate number of full characters in segment (aCount could be odd!)
683   uint32_t segmentLength = aCount / sizeof(char16_t);
684 
685   // copy all data into our aligned buffer.  byte swap if necessary.
686   // cursor may be unaligned, so we cannot use copyAndSwapToBigEndian directly
687   memcpy(cursor, unicodeSegment, segmentLength * sizeof(char16_t));
688   char16_t* end = cursor + segmentLength;
689   mozilla::NativeEndian::swapToBigEndianInPlace(cursor, segmentLength);
690   closure->mWriteCursor = end;
691 
692   // remember this is the modifed aCount and aFromSegment,
693   // so that will take into account the fact that we might have
694   // skipped the first byte in the buffer
695   if (aCount % sizeof(char16_t) != 0) {
696     // we must have had a carryover byte, that we'll need the next
697     // time around
698     closure->mCarryoverByte = aFromSegment[aCount - 1];
699     closure->mHasCarryoverByte = true;
700   }
701 
702   return NS_OK;
703 }
704 
705 NS_IMETHODIMP
ReadString(nsAString & aString)706 nsBinaryInputStream::ReadString(nsAString& aString) {
707   nsresult rv;
708   uint32_t length, bytesRead;
709 
710   rv = Read32(&length);
711   if (NS_FAILED(rv)) {
712     return rv;
713   }
714 
715   if (length == 0) {
716     aString.Truncate();
717     return NS_OK;
718   }
719 
720   // pre-allocate output buffer, and get direct access to buffer...
721   if (!aString.SetLength(length, mozilla::fallible)) {
722     return NS_ERROR_OUT_OF_MEMORY;
723   }
724 
725   WriteStringClosure closure;
726   closure.mWriteCursor = aString.BeginWriting();
727   closure.mHasCarryoverByte = false;
728 
729   rv = ReadSegments(WriteSegmentToString, &closure, length * sizeof(char16_t),
730                     &bytesRead);
731   if (NS_FAILED(rv)) {
732     return rv;
733   }
734 
735   NS_ASSERTION(!closure.mHasCarryoverByte, "some strange stream corruption!");
736 
737   if (bytesRead != length * sizeof(char16_t)) {
738     return NS_ERROR_FAILURE;
739   }
740 
741   return NS_OK;
742 }
743 
ReadBytesToBuffer(uint32_t aLength,uint8_t * aBuffer)744 nsresult nsBinaryInputStream::ReadBytesToBuffer(uint32_t aLength,
745                                                 uint8_t* aBuffer) {
746   uint32_t bytesRead;
747   nsresult rv = Read(reinterpret_cast<char*>(aBuffer), aLength, &bytesRead);
748   if (NS_FAILED(rv)) {
749     return rv;
750   }
751   if (bytesRead != aLength) {
752     return NS_ERROR_FAILURE;
753   }
754 
755   return NS_OK;
756 }
757 
758 NS_IMETHODIMP
ReadBytes(uint32_t aLength,char ** aResult)759 nsBinaryInputStream::ReadBytes(uint32_t aLength, char** aResult) {
760   char* s = static_cast<char*>(malloc(aLength));
761   if (!s) {
762     return NS_ERROR_OUT_OF_MEMORY;
763   }
764 
765   nsresult rv = ReadBytesToBuffer(aLength, reinterpret_cast<uint8_t*>(s));
766   if (NS_FAILED(rv)) {
767     free(s);
768     return rv;
769   }
770 
771   *aResult = s;
772   return NS_OK;
773 }
774 
775 NS_IMETHODIMP
ReadByteArray(uint32_t aLength,nsTArray<uint8_t> & aResult)776 nsBinaryInputStream::ReadByteArray(uint32_t aLength,
777                                    nsTArray<uint8_t>& aResult) {
778   if (!aResult.SetLength(aLength, mozilla::fallible)) {
779     return NS_ERROR_OUT_OF_MEMORY;
780   }
781   nsresult rv = ReadBytesToBuffer(aLength, aResult.Elements());
782   if (NS_FAILED(rv)) {
783     aResult.Clear();
784   }
785   return rv;
786 }
787 
788 NS_IMETHODIMP
ReadArrayBuffer(uint64_t aLength,JS::Handle<JS::Value> aBuffer,JSContext * aCx,uint64_t * aReadLength)789 nsBinaryInputStream::ReadArrayBuffer(uint64_t aLength,
790                                      JS::Handle<JS::Value> aBuffer,
791                                      JSContext* aCx, uint64_t* aReadLength) {
792   if (!aBuffer.isObject()) {
793     return NS_ERROR_FAILURE;
794   }
795   JS::Rooted<JSObject*> buffer(aCx, &aBuffer.toObject());
796   if (!JS::IsArrayBufferObject(buffer)) {
797     return NS_ERROR_FAILURE;
798   }
799 
800   size_t bufferLength = JS::GetArrayBufferByteLength(buffer);
801   if (bufferLength < aLength) {
802     return NS_ERROR_FAILURE;
803   }
804 
805   uint32_t bufSize = std::min<uint64_t>(aLength, 4096);
806   UniquePtr<char[]> buf = MakeUnique<char[]>(bufSize);
807 
808   uint64_t pos = 0;
809   *aReadLength = 0;
810   do {
811     // Read data into temporary buffer.
812     uint32_t bytesRead;
813     uint32_t amount = std::min<uint64_t>(aLength - pos, bufSize);
814     nsresult rv = Read(buf.get(), amount, &bytesRead);
815     if (NS_WARN_IF(NS_FAILED(rv))) {
816       return rv;
817     }
818     MOZ_ASSERT(bytesRead <= amount);
819 
820     if (bytesRead == 0) {
821       break;
822     }
823 
824     // Copy data into actual buffer.
825 
826     JS::AutoCheckCannotGC nogc;
827     bool isShared;
828     if (bufferLength != JS::GetArrayBufferByteLength(buffer)) {
829       return NS_ERROR_FAILURE;
830     }
831 
832     char* data = reinterpret_cast<char*>(
833         JS::GetArrayBufferData(buffer, &isShared, nogc));
834     MOZ_ASSERT(!isShared);  // Implied by JS::GetArrayBufferData()
835     if (!data) {
836       return NS_ERROR_FAILURE;
837     }
838 
839     *aReadLength += bytesRead;
840     PodCopy(data + pos, buf.get(), bytesRead);
841 
842     pos += bytesRead;
843   } while (pos < aLength);
844 
845   return NS_OK;
846 }
847 
848 NS_IMETHODIMP
ReadObject(bool aIsStrongRef,nsISupports ** aObject)849 nsBinaryInputStream::ReadObject(bool aIsStrongRef, nsISupports** aObject) {
850   nsCID cid;
851   nsIID iid;
852   nsresult rv = ReadID(&cid);
853   if (NS_WARN_IF(NS_FAILED(rv))) {
854     return rv;
855   }
856 
857   rv = ReadID(&iid);
858   if (NS_WARN_IF(NS_FAILED(rv))) {
859     return rv;
860   }
861 
862   // HACK: Intercept old (pre-gecko6) nsIURI IID, and replace with
863   // the updated IID, so that we're QI'ing to an actual interface.
864   // (As soon as we drop support for upgrading from pre-gecko6, we can
865   // remove this chunk.)
866   static const nsIID oldURIiid = {
867       0x7a22cc0,
868       0xce5,
869       0x11d3,
870       {0x93, 0x31, 0x0, 0x10, 0x4b, 0xa0, 0xfd, 0x40}};
871 
872   // hackaround for bug 670542
873   static const nsIID oldURIiid2 = {
874       0xd6d04c36,
875       0x0fa4,
876       0x4db3,
877       {0xbe, 0x05, 0x4a, 0x18, 0x39, 0x71, 0x03, 0xe2}};
878 
879   // hackaround for bug 682031
880   static const nsIID oldURIiid3 = {
881       0x12120b20,
882       0x0929,
883       0x40e9,
884       {0x88, 0xcf, 0x6e, 0x08, 0x76, 0x6e, 0x8b, 0x23}};
885 
886   // hackaround for bug 1195415
887   static const nsIID oldURIiid4 = {
888       0x395fe045,
889       0x7d18,
890       0x4adb,
891       {0xa3, 0xfd, 0xaf, 0x98, 0xc8, 0xa1, 0xaf, 0x11}};
892 
893   if (iid.Equals(oldURIiid) || iid.Equals(oldURIiid2) ||
894       iid.Equals(oldURIiid3) || iid.Equals(oldURIiid4)) {
895     const nsIID newURIiid = NS_IURI_IID;
896     iid = newURIiid;
897   }
898 
899   // Hack around bug 1508939
900   // The old CSP serialization can't be handled cleanly when
901   // it's embedded in an old style principal
902   static const nsIID oldCSPiid = {
903       0xb3c4c0ae,
904       0xbd5e,
905       0x4cad,
906       {0x87, 0xe0, 0x8d, 0x21, 0x0d, 0xbb, 0x3f, 0x9f}};
907   if (iid.Equals(oldCSPiid)) {
908     return NS_ERROR_FAILURE;
909   }
910   // END HACK
911 
912   // HACK:  Service workers store resource security info on disk in the dom
913   //        Cache API.  When the uuid of the nsIX509Cert interface changes
914   //        these serialized objects cannot be loaded any more.  This hack
915   //        works around this issue.
916 
917   // hackaround for bug 1247580 (FF45 to FF46 transition)
918   static const nsIID oldCertIID = {
919       0xf8ed8364,
920       0xced9,
921       0x4c6e,
922       {0x86, 0xba, 0x48, 0xaf, 0x53, 0xc3, 0x93, 0xe6}};
923 
924   if (iid.Equals(oldCertIID)) {
925     const nsIID newCertIID = NS_IX509CERT_IID;
926     iid = newCertIID;
927   }
928   // END HACK
929 
930   nsCOMPtr<nsISupports> object = do_CreateInstance(cid, &rv);
931   if (NS_WARN_IF(NS_FAILED(rv))) {
932     return rv;
933   }
934 
935   nsCOMPtr<nsISerializable> serializable = do_QueryInterface(object);
936   if (NS_WARN_IF(!serializable)) {
937     return NS_ERROR_UNEXPECTED;
938   }
939 
940   rv = serializable->Read(this);
941   if (NS_WARN_IF(NS_FAILED(rv))) {
942     return rv;
943   }
944 
945   return object->QueryInterface(iid, reinterpret_cast<void**>(aObject));
946 }
947 
948 NS_IMETHODIMP
ReadID(nsID * aResult)949 nsBinaryInputStream::ReadID(nsID* aResult) {
950   nsresult rv = Read32(&aResult->m0);
951   if (NS_WARN_IF(NS_FAILED(rv))) {
952     return rv;
953   }
954 
955   rv = Read16(&aResult->m1);
956   if (NS_WARN_IF(NS_FAILED(rv))) {
957     return rv;
958   }
959 
960   rv = Read16(&aResult->m2);
961   if (NS_WARN_IF(NS_FAILED(rv))) {
962     return rv;
963   }
964 
965   const uint32_t toRead = sizeof(aResult->m3);
966   uint32_t bytesRead = 0;
967   rv = Read(reinterpret_cast<char*>(&aResult->m3[0]), toRead, &bytesRead);
968   if (NS_WARN_IF(NS_FAILED(rv))) {
969     return rv;
970   }
971   if (bytesRead != toRead) {
972     return NS_ERROR_FAILURE;
973   }
974 
975   return NS_OK;
976 }
977 
NS_IMETHODIMP_(char *)978 NS_IMETHODIMP_(char*)
979 nsBinaryInputStream::GetBuffer(uint32_t aLength, uint32_t aAlignMask) {
980   if (mBufferAccess) {
981     return mBufferAccess->GetBuffer(aLength, aAlignMask);
982   }
983   return nullptr;
984 }
985 
NS_IMETHODIMP_(void)986 NS_IMETHODIMP_(void)
987 nsBinaryInputStream::PutBuffer(char* aBuffer, uint32_t aLength) {
988   if (mBufferAccess) {
989     mBufferAccess->PutBuffer(aBuffer, aLength);
990   }
991 }
992