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
|
/* -*- 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/. */
#ifndef mozilla_dom_ipc_StructuredCloneData_h
#define mozilla_dom_ipc_StructuredCloneData_h
#include <algorithm>
#include "mozilla/RefPtr.h"
#include "mozilla/UniquePtr.h"
#include "mozilla/dom/StructuredCloneHolder.h"
#include "nsIInputStream.h"
#include "nsISupportsImpl.h"
namespace IPC {
class Message;
class MessageReader;
class MessageWriter;
} // namespace IPC
class PickleIterator;
namespace mozilla {
namespace ipc {
class PBackgroundChild;
class PBackgroundParent;
} // namespace ipc
namespace dom {
class ContentChild;
class ContentParent;
namespace ipc {
/**
* Wraps the non-reference-counted JSStructuredCloneData class to have a
* reference count so that multiple StructuredCloneData instances can reference
* a single underlying serialized representation.
*
* As used by StructuredCloneData, it is an invariant that our
* JSStructuredCloneData owns its buffers. (For the non-owning case,
* StructuredCloneData uses mExternalData which holds a BufferList::Borrow()ed
* read-only view of the data.)
*/
class SharedJSAllocatedData final {
public:
explicit SharedJSAllocatedData(JSStructuredCloneData&& aData)
: mData(std::move(aData)) {}
static already_AddRefed<SharedJSAllocatedData> CreateFromExternalData(
const char* aData, size_t aDataLength) {
JSStructuredCloneData buf(JS::StructuredCloneScope::DifferentProcess);
NS_ENSURE_TRUE(buf.AppendBytes(aData, aDataLength), nullptr);
RefPtr<SharedJSAllocatedData> sharedData =
new SharedJSAllocatedData(std::move(buf));
return sharedData.forget();
}
static already_AddRefed<SharedJSAllocatedData> CreateFromExternalData(
const JSStructuredCloneData& aData) {
JSStructuredCloneData buf(aData.scope());
NS_ENSURE_TRUE(buf.Append(aData), nullptr);
RefPtr<SharedJSAllocatedData> sharedData =
new SharedJSAllocatedData(std::move(buf));
return sharedData.forget();
}
NS_INLINE_DECL_THREADSAFE_REFCOUNTING(SharedJSAllocatedData)
JSStructuredCloneData& Data() { return mData; }
size_t DataLength() const { return mData.Size(); }
private:
~SharedJSAllocatedData() = default;
JSStructuredCloneData mData;
};
/**
* IPC-aware StructuredCloneHolder subclass that serves as both a helper class
* for dealing with message data (blobs, transferables) and also an IPDL
* data-type in cases where message data is not needed. If your use-case does
* not (potentially) involve IPC, then you should use StructuredCloneHolder or
* one of its other subclasses instead.
*
* ## Usage ##
*
* The general recipe for using this class is:
* - In your IPDL definition, use the ClonedMessageData type whenever you want
* to send a structured clone that may include blobs or transferables such as
* message ports.
* - To send the data, instantiate a StructuredCloneData instance and Write()
* into it like a normal structured clone. When you are ready to send the
* ClonedMessageData-bearing IPC message, call the BuildClonedMessageData
* method to populate the ClonedMessageData and then send it before your
* StructuredCloneData instance is destroyed. (Buffer borrowing is used
* under-the-hood to avoid duplicating the serialized data, requiring this.)
* - To receive the data, instantiate a StructuredCloneData and then call
* the BorrowFromClonedMessageData method. See the memory management
* section for more information.
*
* ## Memory Management ##
*
* Serialized structured clone representations can be quite large. So it's best
* to avoid wasteful duplication. When Write()ing into the StructuredCloneData,
* you don't need to worry about this[1], but when you already have serialized
* structured clone data you plan to Read(), you do need to. Similarly, if
* you're using StructuredCloneData as an IPDL type, it efficiently unmarshals.
*
* The from-ClonedMessageData memory management strategies available are:
* - Borrow: Create a JSStructuredCloneData that holds a non-owning, read-only
* BufferList::Borrow()ed copy of the source. Your StructuredCloneData needs
* to be destroyed before the source is. Commonly used when the
* StructuredCloneData instance is stack-allocated (and Read() is used before
* the function returns).
* - Copy: Makes a reference-counted copy of the source JSStructuredCloneData,
* making it safe for the StructuredCloneData to outlive the source data.
* - Steal: Steal the buffers from the underlying JSStructuredCloneData so that
* it's safe for the StructuredCloneData to outlive the source data. This is
* safe to use with IPC-provided ClonedMessageData instances because
* JSStructuredCloneData's IPC ParamTraits::Read method copies the relevant
* data into owned buffers. But if it's possible the ClonedMessageData came
* from a different source that might have borrowed the buffers itself, then
* things will crash. That would be a pretty strange implementation; if you
* see one, change it to use SharedJSAllocatedData.
*
* 1: Specifically, in the Write() case an owning SharedJSAllocatedData is
* created efficiently (by stealing from StructuredCloneHolder). The
* BuildClonedMessageData method can be called at any time and it will
* borrow the underlying memory. While it would be even better if
* SerializedStructuredCloneBuffer could hold a SharedJSAllocatedData ref,
* there's no reason you can't wait to call the BuildClonedMessageData
* method until you need to make the IPC Send* call.
*/
class StructuredCloneData : public StructuredCloneHolder {
public:
StructuredCloneData();
// StructuredCloneData is a large data structure, so don't let it be
// implicitly copied.
StructuredCloneData(const StructuredCloneData&) = delete;
StructuredCloneData& operator=(const StructuredCloneData& aOther) = delete;
// It would be safe to define a move operator for StructuredCloneData, unlike
// for the parent classes, but the large number of arrays for storing extra
// DOM data mean that it would fragile. Instead, use
// UniquePtr<StructuredCloneData> to pass around SCDs without copying.
StructuredCloneData(StructuredCloneData&& aOther) = delete;
StructuredCloneData& operator=(StructuredCloneData&& aOther) = delete;
// Only DifferentProcess and UnknownDestination scopes are supported.
StructuredCloneData(StructuredCloneScope aScope,
TransferringSupport aSupportsTransferring);
~StructuredCloneData();
const nsTArray<RefPtr<BlobImpl>>& BlobImpls() const { return mBlobImplArray; }
nsTArray<RefPtr<BlobImpl>>& BlobImpls() { return mBlobImplArray; }
const nsTArray<nsCOMPtr<nsIInputStream>>& InputStreams() const {
return mInputStreamArray;
}
nsTArray<nsCOMPtr<nsIInputStream>>& InputStreams() {
return mInputStreamArray;
}
bool Copy(const StructuredCloneData& aData);
void Read(JSContext* aCx, JS::MutableHandle<JS::Value> aValue,
ErrorResult& aRv);
void Read(JSContext* aCx, JS::MutableHandle<JS::Value> aValue,
const JS::CloneDataPolicy& aCloneDataPolicy, ErrorResult& aRv);
// Write with no transfer objects and with the default CloneDataPolicy. With
// a default CloneDataPolicy, read and write will not be considered as part of
// the same agent cluster and shared memory objects will not be supported.
void Write(JSContext* aCx, JS::Handle<JS::Value> aValue,
ErrorResult& aRv) override;
// The most generic Write method, with tansfers and CloneDataPolicy.
void Write(JSContext* aCx, JS::Handle<JS::Value> aValue,
JS::Handle<JS::Value> aTransfers,
const JS::CloneDataPolicy& aCloneDataPolicy,
ErrorResult& aRv) override;
// Method to convert the structured clone stored in this holder by a previous
// call to Write() into ClonedMessageData IPC representation.
bool BuildClonedMessageData(ClonedMessageData& aClonedData);
// Memory-management-strategy-varying methods to initialize this holder from a
// ClonedMessageData representation.
void BorrowFromClonedMessageData(const ClonedMessageData& aClonedData);
void CopyFromClonedMessageData(const ClonedMessageData& aClonedData);
// The steal variant of course takes a non-const ClonedMessageData.
void StealFromClonedMessageData(ClonedMessageData& aClonedData);
// Initialize this instance, borrowing the contents of the given
// JSStructuredCloneData. You are responsible for ensuring that this
// StructuredCloneData instance is destroyed before aData is destroyed.
bool UseExternalData(const JSStructuredCloneData& aData) {
auto iter = aData.Start();
bool success = false;
mExternalData = aData.Borrow(iter, aData.Size(), &success);
mInitialized = true;
return success;
}
// Initialize this instance by copying the given data that probably came from
// nsStructuredClone doing a base64 decode. Don't use this.
bool CopyExternalData(const char* aData, size_t aDataLength);
// Initialize this instance by copying the contents of an existing
// JSStructuredCloneData. Use when this StructuredCloneData instance may
// outlive aData.
bool CopyExternalData(const JSStructuredCloneData& aData);
// Initialize this instance by stealing the contents of aData via Move
// constructor, clearing the original aData as a side-effect. This is only
// safe if aData owns the underlying buffers. This is the case for instances
// provided by IPC to Recv calls.
bool StealExternalData(JSStructuredCloneData& aData);
JSStructuredCloneData& Data() {
return mSharedData ? mSharedData->Data() : mExternalData;
}
const JSStructuredCloneData& Data() const {
return mSharedData ? mSharedData->Data() : mExternalData;
}
void InitScope(JS::StructuredCloneScope aScope) { Data().initScope(aScope); }
size_t DataLength() const {
return mSharedData ? mSharedData->DataLength() : mExternalData.Size();
}
SharedJSAllocatedData* SharedData() const { return mSharedData; }
bool SupportsTransferring() { return mSupportsTransferring; }
// For IPC serialization
void WriteIPCParams(IPC::MessageWriter* aWriter) const;
bool ReadIPCParams(IPC::MessageReader* aReader);
protected:
already_AddRefed<SharedJSAllocatedData> TakeSharedData();
private:
JSStructuredCloneData mExternalData;
RefPtr<SharedJSAllocatedData> mSharedData;
bool mInitialized;
};
} // namespace ipc
} // namespace dom
} // namespace mozilla
#endif // mozilla_dom_ipc_StructuredCloneData_h
|