-
Notifications
You must be signed in to change notification settings - Fork 709
/
serialization.cpp
493 lines (432 loc) · 17.6 KB
/
serialization.cpp
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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
#include "seal/dynarray.h"
#include "seal/memorymanager.h"
#include "seal/serialization.h"
#include "seal/util/common.h"
#include "seal/util/streambuf.h"
#include "seal/util/ztools.h"
#include <stdexcept>
#include <typeinfo>
using namespace std;
using namespace seal::util;
namespace seal
{
// Required for C++14 compliance: static constexpr member variables are not necessarily inlined so need to ensure
// symbol is created.
constexpr compr_mode_type Serialization::compr_mode_default;
// Required for C++14 compliance: static constexpr member variables are not necessarily inlined so need to ensure
// symbol is created.
constexpr uint16_t Serialization::seal_magic;
// Required for C++14 compliance: static constexpr member variables are not necessarily inlined so need to ensure
// symbol is created.
constexpr uint8_t Serialization::seal_header_size;
namespace
{
[[noreturn]] void expressive_rethrow_on_ios_base_failure(const ostream &stream)
{
if (!stream.rdbuf())
{
throw runtime_error("I/O error: output stream has no associated buffer");
}
// Use RTTI to determine if this is an ArrayPutBuffer
auto &rdbuf_ref = *stream.rdbuf();
if (typeid(rdbuf_ref).hash_code() == typeid(ArrayPutBuffer).hash_code())
{
auto buffer = reinterpret_cast<ArrayPutBuffer *>(stream.rdbuf());
// Determine if write overflow occurred
if (buffer->at_end())
{
// Return a more expressive error
throw runtime_error("I/O error: insufficient output buffer");
}
}
// Generic message
throw runtime_error("I/O error");
}
[[noreturn]] void expressive_rethrow_on_ios_base_failure(const istream &stream)
{
if (!stream.rdbuf())
{
throw runtime_error("I/O error: input stream has no associated buffer");
}
// Use RTTI to determine if this is an ArrayGetBuffer
if (stream.eof())
{
auto &rdbuf_ref = *stream.rdbuf();
if (typeid(rdbuf_ref).hash_code() == typeid(ArrayGetBuffer).hash_code())
{
// Report buffer underflow
throw runtime_error("I/O error: input buffer ended unexpectedly");
}
else
{
// Report generic underflow
throw runtime_error("I/O error: input stream ended unexpectedly");
}
}
// Generic message
throw runtime_error("I/O error");
}
} // namespace
size_t Serialization::ComprSizeEstimate(size_t in_size, compr_mode_type compr_mode)
{
if (!IsSupportedComprMode(compr_mode))
{
throw invalid_argument("unsupported compression mode");
}
switch (compr_mode)
{
#ifdef SEAL_USE_ZSTD
case compr_mode_type::zstd:
return ztools::zstd_deflate_size_bound(in_size);
#endif
#ifdef SEAL_USE_ZLIB
case compr_mode_type::zlib:
return ztools::zlib_deflate_size_bound(in_size);
#endif
case compr_mode_type::none:
// No compression
return in_size;
default:
throw invalid_argument("unsupported compression mode");
}
}
streamoff Serialization::SaveHeader(const SEALHeader &header, ostream &stream)
{
auto old_except_mask = stream.exceptions();
try
{
// Throw exceptions on ios_base::badbit and ios_base::failbit
stream.exceptions(ios_base::badbit | ios_base::failbit);
stream.write(reinterpret_cast<const char *>(&header), sizeof(SEALHeader));
}
catch (const ios_base::failure &)
{
stream.exceptions(old_except_mask);
expressive_rethrow_on_ios_base_failure(stream);
}
catch (...)
{
stream.exceptions(old_except_mask);
throw;
}
stream.exceptions(old_except_mask);
// Return the size of the SEALHeader
return static_cast<streamoff>(sizeof(SEALHeader));
}
streamoff Serialization::LoadHeader(istream &stream, SEALHeader &header, bool try_upgrade_if_invalid)
{
auto old_except_mask = stream.exceptions();
try
{
// Throw exceptions on ios_base::badbit and ios_base::failbit
stream.exceptions(ios_base::badbit | ios_base::failbit);
stream.read(reinterpret_cast<char *>(&header), sizeof(SEALHeader));
// If header is invalid this may be an older header and we can try to automatically upgrade it
if (try_upgrade_if_invalid && !IsValidHeader(header))
{
// Try interpret the data as a Microsoft SEAL 3.4 header
legacy_headers::SEALHeader_3_4 header_3_4(header);
SEALHeader new_header;
new_header.version_major = 3;
new_header.version_minor = 4;
// Copy over the fields; of course the result may not be valid depending on whether the input was a
// valid version 3.4 header
new_header.compr_mode = header_3_4.compr_mode;
new_header.size = header_3_4.size;
// Now validate the new header and discard if still not valid; something else is probably wrong
if (IsValidHeader(new_header))
{
header = new_header;
}
}
}
catch (const ios_base::failure &)
{
stream.exceptions(old_except_mask);
expressive_rethrow_on_ios_base_failure(stream);
}
catch (...)
{
stream.exceptions(old_except_mask);
throw;
}
stream.exceptions(old_except_mask);
// Return the size of the SEALHeader
return static_cast<streamoff>(sizeof(SEALHeader));
}
streamoff Serialization::SaveHeader(const SEALHeader &header, seal_byte *out, size_t size)
{
if (!out)
{
throw invalid_argument("out cannot be null");
}
if (size < sizeof(SEALHeader))
{
throw invalid_argument("insufficient size");
}
if (!fits_in<streamsize>(size))
{
throw invalid_argument("size is too large");
}
ArrayPutBuffer apbuf(reinterpret_cast<char *>(out), static_cast<streamsize>(size));
ostream stream(&apbuf);
return SaveHeader(header, stream);
}
streamoff Serialization::LoadHeader(
const seal_byte *in, size_t size, SEALHeader &header, bool try_upgrade_if_invalid)
{
if (!in)
{
throw invalid_argument("in cannot be null");
}
if (size < sizeof(SEALHeader))
{
throw invalid_argument("insufficient size");
}
if (!fits_in<streamsize>(size))
{
throw invalid_argument("size is too large");
}
ArrayGetBuffer agbuf(reinterpret_cast<const char *>(in), static_cast<streamsize>(size));
istream stream(&agbuf);
return LoadHeader(stream, header, try_upgrade_if_invalid);
}
streamoff Serialization::Save(
function<void(ostream &)> save_members, streamoff raw_size, ostream &stream, compr_mode_type compr_mode,
SEAL_MAYBE_UNUSED bool clear_buffers)
{
if (!save_members)
{
throw invalid_argument("save_members is invalid");
}
if (raw_size < static_cast<streamoff>(sizeof(SEALHeader)))
{
throw invalid_argument("raw_size is too small");
}
if (!IsSupportedComprMode(compr_mode))
{
throw invalid_argument("unsupported compression mode");
}
streamoff out_size = 0;
auto old_except_mask = stream.exceptions();
try
{
// Throw exceptions on ios_base::badbit and ios_base::failbit
stream.exceptions(ios_base::badbit | ios_base::failbit);
// Save the starting position
auto stream_start_pos = stream.tellp();
// Create the header
SEALHeader header;
switch (compr_mode)
{
case compr_mode_type::none:
// We set the compression mode and size here, and save the header
header.compr_mode = compr_mode;
header.size = safe_cast<uint64_t>(raw_size);
SaveHeader(header, stream);
// Write rest of the data
save_members(stream);
break;
#ifdef SEAL_USE_ZLIB
case compr_mode_type::zlib:
{
// First save_members to a temporary byte stream; set the size of the temporary stream to be right from
// the start to avoid extra reallocs.
SafeByteBuffer safe_buffer(
ztools::zlib_deflate_size_bound(raw_size - static_cast<streamoff>(sizeof(SEALHeader))),
clear_buffers);
iostream temp_stream(&safe_buffer);
temp_stream.exceptions(ios_base::badbit | ios_base::failbit);
save_members(temp_stream);
auto safe_pool(MemoryManager::GetPool(mm_prof_opt::mm_force_new, clear_buffers));
// Create temporary aliasing DynArray to wrap safe_buffer
DynArray<seal_byte> safe_buffer_array(
Pointer<seal_byte>::Aliasing(safe_buffer.data()), safe_buffer.size(),
static_cast<size_t>(temp_stream.tellp()), false, safe_pool);
// After compression, write_header_deflate_buffer will write the final size to the given header and
// write the header to stream, before writing the compressed output.
ztools::zlib_write_header_deflate_buffer(
safe_buffer_array, reinterpret_cast<void *>(&header), stream, safe_pool);
break;
}
#endif
#ifdef SEAL_USE_ZSTD
case compr_mode_type::zstd:
{
// First save_members to a temporary byte stream; set the size of the temporary stream to be right from
// the start to avoid extra reallocs.
SafeByteBuffer safe_buffer(
ztools::zstd_deflate_size_bound(raw_size - static_cast<streamoff>(sizeof(SEALHeader))),
clear_buffers);
iostream temp_stream(&safe_buffer);
temp_stream.exceptions(ios_base::badbit | ios_base::failbit);
save_members(temp_stream);
auto safe_pool(MemoryManager::GetPool(mm_prof_opt::mm_force_new, clear_buffers));
// Create temporary aliasing DynArray to wrap safe_buffer
DynArray<seal_byte> safe_buffer_array(
Pointer<seal_byte>::Aliasing(safe_buffer.data()), safe_buffer.size(),
static_cast<size_t>(temp_stream.tellp()), false, safe_pool);
// After compression, write_header_deflate_buffer will write the final size to the given header and
// write the header to stream, before writing the compressed output.
ztools::zstd_write_header_deflate_buffer(
safe_buffer_array, reinterpret_cast<void *>(&header), stream, safe_pool);
break;
}
#endif
default:
throw invalid_argument("unsupported compression mode");
}
// Compute how many bytes were written
auto stream_end_pos = stream.tellp();
out_size = stream_end_pos - stream_start_pos;
}
catch (const ios_base::failure &)
{
stream.exceptions(old_except_mask);
expressive_rethrow_on_ios_base_failure(stream);
}
catch (...)
{
stream.exceptions(old_except_mask);
throw;
}
stream.exceptions(old_except_mask);
return out_size;
}
streamoff Serialization::Load(
function<void(istream &, SEALVersion)> load_members, istream &stream, SEAL_MAYBE_UNUSED bool clear_buffers)
{
if (!load_members)
{
throw invalid_argument("load_members is invalid");
}
streamoff in_size = 0;
SEALHeader header;
auto old_except_mask = stream.exceptions();
try
{
// Throw exceptions on ios_base::badbit and ios_base::failbit
stream.exceptions(ios_base::badbit | ios_base::failbit);
// Save the starting position
auto stream_start_pos = stream.tellg();
// First read the header
LoadHeader(stream, header);
if (!IsCompatibleVersion(header))
{
throw logic_error("incompatible version");
}
if (!IsValidHeader(header))
{
throw logic_error("loaded SEALHeader is invalid");
}
// Read header version information so we can call, if necessary, the
// correct variant of load_members.
SEALVersion version{ header.version_major, header.version_minor, 0, 0 };
switch (header.compr_mode)
{
case compr_mode_type::none:
// Read rest of the data
load_members(stream, version);
if (header.size != safe_cast<uint64_t>(stream.tellg() - stream_start_pos))
{
throw logic_error("invalid data size");
}
break;
#ifdef SEAL_USE_ZLIB
case compr_mode_type::zlib:
{
auto compr_size = header.size - safe_cast<uint64_t>(stream.tellg() - stream_start_pos);
// We don't know the decompressed size, but use compr_size as
// starting point for the buffer.
SafeByteBuffer safe_buffer(safe_cast<streamsize>(compr_size), clear_buffers);
iostream temp_stream(&safe_buffer);
temp_stream.exceptions(ios_base::badbit | ios_base::failbit);
auto safe_pool = MemoryManager::GetPool(mm_prof_opt::mm_force_new, clear_buffers);
// Throw an exception on non-zero return value
if (ztools::zlib_inflate_stream(stream, safe_cast<streamoff>(compr_size), temp_stream, safe_pool))
{
throw logic_error("stream decompression failed");
}
load_members(temp_stream, version);
break;
}
#endif
#ifdef SEAL_USE_ZSTD
case compr_mode_type::zstd:
{
auto compr_size = header.size - safe_cast<uint64_t>(stream.tellg() - stream_start_pos);
// We don't know the decompressed size, but use compr_size as
// starting point for the buffer.
SafeByteBuffer safe_buffer(safe_cast<streamsize>(compr_size), clear_buffers);
iostream temp_stream(&safe_buffer);
temp_stream.exceptions(ios_base::badbit | ios_base::failbit);
auto safe_pool = MemoryManager::GetPool(mm_prof_opt::mm_force_new, clear_buffers);
// Throw an exception on non-zero return value
if (ztools::zstd_inflate_stream(stream, safe_cast<streamoff>(compr_size), temp_stream, safe_pool))
{
throw logic_error("stream decompression failed");
}
load_members(temp_stream, version);
break;
}
#endif
default:
throw invalid_argument("unsupported compression mode");
}
in_size = safe_cast<streamoff>(header.size);
}
catch (const ios_base::failure &)
{
stream.exceptions(old_except_mask);
expressive_rethrow_on_ios_base_failure(stream);
}
catch (...)
{
stream.exceptions(old_except_mask);
throw;
}
stream.exceptions(old_except_mask);
return in_size;
}
streamoff Serialization::Save(
function<void(ostream &)> save_members, streamoff raw_size, seal_byte *out, size_t size,
compr_mode_type compr_mode, bool clear_buffers)
{
if (!out)
{
throw invalid_argument("out cannot be null");
}
if (size < sizeof(SEALHeader))
{
throw invalid_argument("insufficient size");
}
if (!fits_in<streamsize>(size))
{
throw invalid_argument("size is too large");
}
ArrayPutBuffer apbuf(reinterpret_cast<char *>(out), static_cast<streamsize>(size));
ostream stream(&apbuf);
return Save(save_members, raw_size, stream, compr_mode, clear_buffers);
}
streamoff Serialization::Load(
function<void(istream &, SEALVersion)> load_members, const seal_byte *in, size_t size, bool clear_buffers)
{
if (!in)
{
throw invalid_argument("in cannot be null");
}
if (size < sizeof(SEALHeader))
{
throw invalid_argument("insufficient size");
}
if (!fits_in<streamsize>(size))
{
throw invalid_argument("size is too large");
}
ArrayGetBuffer agbuf(reinterpret_cast<const char *>(in), static_cast<streamsize>(size));
istream stream(&agbuf);
return Load(load_members, stream, clear_buffers);
}
} // namespace seal