summaryrefslogtreecommitdiffstats
path: root/contrib/restricted/wavm/Include/WAVM/Inline/Serialization.h
blob: 3a4b9642d10d2bb9a76cfabca06c71c71124ea77 (plain) (blame)
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
#pragma once

#include <string.h>
#include <algorithm>
#include <string>
#include <vector>
#include "WAVM/Inline/Assert.h"
#include "WAVM/Inline/BasicTypes.h"

namespace WAVM { namespace Serialization {
	// An exception that is thrown for various errors during serialization.
	// Any code using serialization should handle it!
	struct FatalSerializationException
	{
		std::string message;
		FatalSerializationException(std::string&& inMessage) : message(std::move(inMessage)) {}
	};

	// An abstract output stream.
	struct OutputStream
	{
		static constexpr bool isInput = false;

		OutputStream() : next(nullptr), end(nullptr) {}
		virtual ~OutputStream() {}

		Uptr capacity() const { return SIZE_MAX; }

		// Advances the stream cursor by numBytes, and returns a pointer to the previous stream
		// cursor.
		inline U8* advance(Uptr numBytes)
		{
			if(Uptr(end - next) < numBytes) { extendBuffer(numBytes); }
			WAVM_ASSERT(next + numBytes <= end);

			U8* data = next;
			next += numBytes;
			return data;
		}

	protected:
		U8* next;
		U8* end;

		// Called when there isn't enough space in the buffer to hold a write to the stream.
		// Should update next and end to point to a new buffer, and ensure that the new
		// buffer has at least numBytes. May throw FatalSerializationException.
		virtual void extendBuffer(Uptr numBytes) = 0;
	};

	// An output stream that writes to an array of bytes.
	struct ArrayOutputStream : public OutputStream
	{
		// Moves the output array from the stream to the caller.
		std::vector<U8>&& getBytes()
		{
			bytes.resize(next - bytes.data());
			next = nullptr;
			end = nullptr;
			return std::move(bytes);
		}

	private:
		std::vector<U8> bytes;

		virtual void extendBuffer(Uptr numBytes)
		{
			const Uptr nextIndex = next - bytes.data();

			// Grow the array by larger and larger increments, so the time spent growing
			// the buffer is O(1).
			bytes.resize(std::max((Uptr)nextIndex + numBytes, (Uptr)bytes.size() * 7 / 5 + 32));

			next = bytes.data() + nextIndex;
			end = bytes.data() + bytes.size();
		}
	};

	// An abstract input stream.
	struct InputStream
	{
		static constexpr bool isInput = true;

		InputStream(const U8* inNext, const U8* inEnd) : next(inNext), end(inEnd) {}
		virtual ~InputStream() {}

		virtual Uptr capacity() const = 0;

		// Advances the stream cursor by numBytes, and returns a pointer to the previous stream
		// cursor.
		inline const U8* advance(Uptr numBytes)
		{
			if(!next || next + numBytes > end) { getMoreData(numBytes); }
			const U8* data = next;
			next += numBytes;
			return data;
		}

		// Returns a pointer to the current stream cursor, ensuring that there are at least numBytes
		// following it.
		inline const U8* peek(Uptr numBytes)
		{
			if(next + numBytes > end) { getMoreData(numBytes); }
			return next;
		}

	protected:
		const U8* next;
		const U8* end;

		// Called when there isn't enough space in the buffer to satisfy a read from the stream.
		// Should update next and end to point to a new buffer, and ensure that the new
		// buffer has at least numBytes. May throw FatalSerializationException.
		virtual void getMoreData(Uptr numBytes) = 0;
	};

	// An input stream that reads from a contiguous range of memory.
	struct MemoryInputStream : InputStream
	{
		MemoryInputStream(const void* begin, Uptr numBytes)
		: InputStream((const U8*)begin, (const U8*)begin + numBytes)
		{
		}
		virtual Uptr capacity() const { return end - next; }

	private:
		virtual void getMoreData(Uptr numBytes)
		{
			throw FatalSerializationException("expected data but found end of stream");
		}
	};

	// Serialize raw byte sequences.
	WAVM_FORCEINLINE void serializeBytes(OutputStream& stream, const U8* bytes, Uptr numBytes)
	{
		if(numBytes) { memcpy(stream.advance(numBytes), bytes, numBytes); }
	}
	WAVM_FORCEINLINE void serializeBytes(InputStream& stream, U8* bytes, Uptr numBytes)
	{
		if(numBytes) { memcpy(bytes, stream.advance(numBytes), numBytes); }
	}

	// Serialize basic C++ types.
	template<typename Stream, typename Value>
	WAVM_FORCEINLINE void serializeNativeValue(Stream& stream, Value& value)
	{
		serializeBytes(stream, (U8*)&value, sizeof(Value));
	}

	template<typename Stream> void serialize(Stream& stream, U8& i)
	{
		serializeNativeValue(stream, i);
	}
	template<typename Stream> void serialize(Stream& stream, U32& i)
	{
		serializeNativeValue(stream, i);
	}
	template<typename Stream> void serialize(Stream& stream, U64& i)
	{
		serializeNativeValue(stream, i);
	}
	template<typename Stream> void serialize(Stream& stream, I8& i)
	{
		serializeNativeValue(stream, i);
	}
	template<typename Stream> void serialize(Stream& stream, I32& i)
	{
		serializeNativeValue(stream, i);
	}
	template<typename Stream> void serialize(Stream& stream, I64& i)
	{
		serializeNativeValue(stream, i);
	}
	template<typename Stream> void serialize(Stream& stream, F32& f)
	{
		serializeNativeValue(stream, f);
	}
	template<typename Stream> void serialize(Stream& stream, F64& f)
	{
		serializeNativeValue(stream, f);
	}

	// Serializes a constant. If deserializing, throws a FatalSerializationException if the
	// deserialized value doesn't match the constant.
	template<typename Constant>
	void serializeConstant(InputStream& stream,
						   const char* constantMismatchMessage,
						   Constant constant)
	{
		Constant savedConstant;
		serialize(stream, savedConstant);
		if(savedConstant != constant)
		{
			throw FatalSerializationException(std::string(constantMismatchMessage) + ": loaded "
											  + std::to_string(savedConstant)
											  + " but was expecting " + std::to_string(constant));
		}
	}
	template<typename Constant>
	void serializeConstant(OutputStream& stream,
						   const char* constantMismatchMessage,
						   Constant constant)
	{
		serialize(stream, constant);
	}

	// Serialize containers.
	template<typename Stream> void serialize(Stream& stream, std::string& string)
	{
		Uptr size = string.size();
		serializeVarUInt32(stream, size);
		if(Stream::isInput)
		{
			// Advance the stream before resizing the string:
			// try to get a serialization exception before making a huge allocation for malformed
			// input.
			const U8* inputBytes = stream.advance(size);
			string.resize(size);
			memcpy(const_cast<char*>(string.data()), inputBytes, size);
			string.shrink_to_fit();
		}
		else
		{
			serializeBytes(stream, (U8*)string.c_str(), size);
		}
	}

	template<typename Stream, typename Element, typename Allocator, typename SerializeElement>
	void serializeArray(Stream& stream,
						std::vector<Element, Allocator>& vector,
						SerializeElement serializeElement)
	{
		Uptr size = vector.size();
		serializeVarUInt32(stream, size);
		if(Stream::isInput)
		{
			// Grow the vector one element at a time:
			// try to get a serialization exception before making a huge allocation for malformed
			// input.
			vector.clear();
			for(Uptr index = 0; index < size; ++index)
			{
				vector.push_back(Element());
				serializeElement(stream, vector.back());
			}
			vector.shrink_to_fit();
		}
		else
		{
			for(Uptr index = 0; index < vector.size(); ++index)
			{ serializeElement(stream, vector[index]); }
		}
	}

	template<typename Stream, typename Element, typename Allocator>
	void serialize(Stream& stream, std::vector<Element, Allocator>& vector)
	{
		serializeArray(
			stream, vector, [](Stream& stream, Element& element) { serialize(stream, element); });
	}
}}