// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file.
// Helper for checking `T::kHasDeprecatedReadParamPrivateConstructor` using a // fallback when the member isn't defined. template <typename T>
inline constexpr auto HasDeprecatedReadParamPrivateConstructor(int)
-> decltype(T::kHasDeprecatedReadParamPrivateConstructor) { return T::kHasDeprecatedReadParamPrivateConstructor;
}
// Try to extract a `Maybe<T>` from this ReadResult.
mozilla::Maybe<T> TakeMaybe() {
if (mIsOk) {
mIsOk = false; return mozilla::Some(std::move(mData));
} return mozilla::Nothing();
}
// Get the underlying data from this ReadResult, even if not OK. // // This is only available for types which are default constructible, and is // used to optimize old-style `ReadParam` calls.
T& GetStorage() { return mData; }
// Compliment to `GetStorage` used to set the ReadResult into an OK state // without constructing the underlying value. void SetOk(bool aIsOk) { mIsOk = aIsOk; }
// Try to extract a `Maybe<T>` from this ReadResult.
mozilla::Maybe<T> TakeMaybe() { return std::move(mData); }
// These methods are only available if the type is default constructible.
T& GetStorage() = delete; void SetOk(bool aIsOk) = delete;
private:
mozilla::Maybe<T> mData;
};
//----------------------------------------------------------------------------- // An iterator class for reading the fields contained within a Message.
class MessageIterator { public:
explicit MessageIterator(const Message& m) : msg_(m), iter_(m) {}
int NextInt() const {
int val;
if (!msg_.ReadInt(&iter_, &val)) NOTREACHED(); return val;
}
intptr_t NextIntPtr() const {
intptr_t val;
if (!msg_.ReadIntPtr(&iter_, &val)) NOTREACHED(); return val;
} const std::string NextString() const {
std::string val;
if (!msg_.ReadString(&iter_, &val)) NOTREACHED(); return val;
} const std::wstring NextWString() const {
std::wstring val;
if (!msg_.ReadWString(&iter_, &val)) NOTREACHED(); return val;
}
//----------------------------------------------------------------------------- // ParamTraits specializations, etc. // // The full set of types ParamTraits is specialized upon contains *possibly* // repeated types: unsigned long may be uint32_t or size_t, unsigned long long // may be uint64_t or size_t, nsresult may be uint32_t, and so on. You can't // have ParamTraits<unsigned int> *and* ParamTraits<uint32_t> if unsigned int // is uint32_t -- that's multiple definitions, and you can only have one. // // You could use #ifs and macro conditions to avoid duplicates, but they'd be // hairy: heavily dependent upon OS and compiler author choices, forced to // address all conflicts by hand. Happily there's a better way. The basic // idea looks like this, where T -> U represents T inheriting from U: // // class ParamTraits<P> // | // --> class ParamTraits1<P> // | // --> class ParamTraits2<P> // | // --> class ParamTraitsN<P> // or however many levels // // The default specialization of ParamTraits{M}<P> is an empty class that // inherits from ParamTraits{M + 1}<P> (or nothing in the base case). // // Now partition the set of parameter types into sets without duplicates. // Assign each set of types to a level M. Then specialize ParamTraitsM for // each of those types. A reference to ParamTraits<P> will consist of some // number of empty classes inheriting in sequence, ending in a non-empty // ParamTraits{N}<P>. It's okay for the parameter types to be duplicative: // either name of a type will resolve to the same ParamTraits{N}<P>. // // The nice thing is that because templates are instantiated lazily, if we // indeed have uint32_t == unsigned int, say, with the former in level N and // the latter in M > N, ParamTraitsM<unsigned int> won't be created (as long as // nobody uses ParamTraitsM<unsigned int>, but why would you), and no duplicate // code will be compiled or extra symbols generated. It's as efficient at // runtime as manually figuring out and avoiding conflicts by #ifs. // // The scheme we follow below names the various classes according to the types // in them, and the number of ParamTraits levels is larger, but otherwise it's // exactly the above idea. //
template <typename P>
[[nodiscard]] inline bool ReadParam(MessageReader* reader, P* p) {
static_assert(!std::is_const_v<P>, "ReadParam may only be used with const types when returning a " "ReadResult (call as ReadParam<T>(reader)).");
if constexpr (!detail::ParamTraitsReadUsesOutParam<P>()) { auto maybe = ParamTraits<P>::Read(reader);
if (maybe) {
*p = std::move(*maybe); returntrue;
} return false;
} else { return ParamTraits<P>::Read(reader, p);
}
}
class MOZ_STACK_CLASS MessageBufferWriter { public: // Create a MessageBufferWriter to write `full_len` bytes into `writer`. // If the length exceeds a threshold, a shared memory region may be used // instead of including the data inline. // // NOTE: This does _NOT_ write out the length of the buffer. // NOTE: Data written this way _MUST_ be read using `MessageBufferReader`.
MessageBufferWriter(MessageWriter* writer, uint32_t full_len);
~MessageBufferWriter();
// Write `len` bytes from `data` into the message. // // Exactly `full_len` bytes should be written across multiple calls before the // `MessageBufferWriter` is destroyed. // // WARNING: all writes (other than the last write) must be multiples of 4 // bytes in length. Not doing this will lead to padding being introduced into // the payload and break things. This can probably be improved in the future // with deeper integration between `MessageBufferWriter` and `Pickle`. bool WriteBytes(constvoid* data, uint32_t len);
class MOZ_STACK_CLASS MessageBufferReader { public: // Create a MessageBufferReader to read `full_len` bytes from `reader` which // were written using `MessageBufferWriter`. // // NOTE: This may consume a shared memory region from the message, meaning // that the same data cannot be read multiple times. // NOTE: Data read this way _MUST_ be written using `MessageBufferWriter`.
MessageBufferReader(MessageReader* reader, uint32_t full_len);
~MessageBufferReader();
// Read `count` bytes from the message into `data`. // // Exactly `full_len` bytes should be read across multiple calls before the // `MessageBufferReader` is destroyed. // // WARNING: all reads (other than the last read) must be multiples of 4 bytes // in length. Not doing this will lead to bytes being skipped in the payload // and break things. This can probably be improved in the future with deeper // integration between `MessageBufferReader` and `Pickle`.
[[nodiscard]] bool ReadBytesInto(void* data, uint32_t len);
// Whether or not it is safe to serialize the given type using // `WriteBytesOrShmem`. template <typename P>
constexpr bool kUseWriteBytes =
!std::is_same_v<std::remove_const_t<std::remove_reference_t<P>>, bool> &&
(std::is_integral_v<std::remove_const_t<std::remove_reference_t<P>>> ||
std::is_floating_point_v<std::remove_const_t<std::remove_reference_t<P>>>);
if (isNull) {
r->reset();
} else { // NOTE: We need to use outparam-style deserialization here, as unique_ptr // is used to deserialize data structures without move constructors.
*r = std::make_unique<T>();
if (!ReadParam(reader, r->get())) { return false;
}
} returntrue;
}
};
// `UniqueFileHandle` may be serialized over IPC channels. On the receiving // side, the UniqueFileHandle is a valid duplicate of the handle which was // transmitted. // // When sending a UniqueFileHandle, the handle must be valid at the time of // transmission. As transmission is asynchronous, this requires passing // ownership of the handle to IPC. // // A UniqueFileHandle may only be read once. After it has been read once, it // will be consumed, and future reads will return an invalid handle. template <> struct ParamTraitsIPC<mozilla::UniqueFileHandle> { typedef mozilla::UniqueFileHandle param_type; staticvoid Write(MessageWriter* writer, param_type&& p) { constbool valid = p != nullptr;
WriteParam(writer, valid);
if (valid) {
if (!writer->WriteFileHandle(std::move(p))) {
writer->FatalError("Too many file handles for one message!");
NOTREACHED() << "Too many file handles for one message!";
}
}
} staticbool Read(MessageReader* reader, param_type* r) { bool valid;
if (!ReadParam(reader, &valid)) {
reader->FatalError("Error reading file handle validity"); return false;
}
if (!valid) {
*r = nullptr; returntrue;
}
if (!reader->ConsumeFileHandle(r)) {
reader->FatalError("File handle not found in message!"); return false;
} returntrue;
}
};
#ifdefined(XP_DARWIN) // `UniqueMachSendRight` may be serialized over IPC channels. On the receiving // side, the UniqueMachSendRight is the local name of the right which was // transmitted. // // When sending a UniqueMachSendRight, the right must be valid at the time of // transmission. As transmission is asynchronous, this requires passing // ownership of the handle to IPC. // // A UniqueMachSendRight may only be read once. After it has been read once, it // will be consumed, and future reads will return an invalid right. template <> struct ParamTraitsIPC<mozilla::UniqueMachSendRight> { typedef mozilla::UniqueMachSendRight param_type; staticvoid Write(MessageWriter* writer, param_type&& p) { constbool valid = p != nullptr;
WriteParam(writer, valid);
if (valid) {
if (!writer->WriteMachSendRight(std::move(p))) {
writer->FatalError("Too many mach send rights for one message!");
NOTREACHED() << "Too many mach send rights for one message!";
}
}
} staticbool Read(MessageReader* reader, param_type* r) { bool valid;
if (!ReadParam(reader, &valid)) {
reader->FatalError("Error reading mach send right validity"); return false;
}
if (!valid) {
*r = nullptr; returntrue;
}
if (!reader->ConsumeMachSendRight(r)) {
reader->FatalError("Mach send right not found in message!"); return false;
} returntrue;
}
};
// `UniqueMachReceiveRight` may be serialized over IPC channels. On the // receiving side, the UniqueMachReceiveRight is the local name of the right // which was transmitted. // // When sending a UniqueMachReceiveRight, the right must be valid at the time of // transmission. As transmission is asynchronous, this requires passing // ownership of the handle to IPC. // // A UniqueMachReceiveRight may only be read once. After it has been read once, // it will be consumed, and future reads will return an invalid right. template <> struct ParamTraitsIPC<mozilla::UniqueMachReceiveRight> { typedef mozilla::UniqueMachReceiveRight param_type; staticvoid Write(MessageWriter* writer, param_type&& p) { constbool valid = p != nullptr;
WriteParam(writer, valid);
if (valid) {
if (!writer->WriteMachReceiveRight(std::move(p))) {
writer->FatalError("Too many mach receive rights for one message!");
NOTREACHED() << "Too many mach receive rights for one message!";
}
}
} staticbool Read(MessageReader* reader, param_type* r) { bool valid;
if (!ReadParam(reader, &valid)) {
reader->FatalError("Error reading mach receive right validity"); return false;
}
if (!valid) {
*r = nullptr; returntrue;
}
if (!reader->ConsumeMachReceiveRight(r)) {
reader->FatalError("Mach receive right not found in message!"); return false;
} returntrue;
}
}; #endif
// When being passed `RefPtr<T>` or `nsCOMPtr<T>`, forward to a specialization // for the underlying target type. The parameter type will be passed as `T*`, // and result as `RefPtr<T>*`. // // This is done explicitly to ensure that the deleted `&&` overload for // `operator T*` is not selected in generic contexts, and to support // deserializing into `nsCOMPtr<T>`. template <class T> struct ParamTraitsMozilla<RefPtr<T>> { staticvoid Write(MessageWriter* writer, const RefPtr<T>& p) {
ParamTraits<T*>::Write(writer, p.get());
}
staticbool Read(MessageReader* reader, mozilla::Maybe<T>* r) { bool isSome;
if (!ReadParam(reader, &isSome)) { return false;
}
if (isSome) {
r->emplace();
if (!ReadParam(reader, r->ptr())) { return false;
}
} returntrue;
}
};
template <> struct ParamTraits<mozilla::Nothing> { // Serialize as if it is a mozilla::Maybe (though in practice this is used for // a monostate Variant alternative type).
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.