-
Notifications
You must be signed in to change notification settings - Fork 47
/
fossilize_db.cpp
2360 lines (1976 loc) · 62.4 KB
/
fossilize_db.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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Copyright (c) 2019 Hans-Kristian Arntzen
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <io.h>
#include <fcntl.h>
#else
#include <unistd.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#endif
#include "fossilize_db.hpp"
#include "path.hpp"
#include "layer/utils.hpp"
#include "miniz.h"
#include <unordered_map>
#include <unordered_set>
#include <algorithm>
#include <memory>
#include <mutex>
#include <atomic>
#include <dirent.h>
#include "fossilize_inttypes.h"
#include "fossilize_errors.hpp"
using namespace std;
// So we can use SHA-1 for hashing blobs.
// Fossilize itself doesn't need this much.
// It only uses 18 hex characters.
// 2 for type and 16 for 64-bit Fossilize hash.
#define FOSSILIZE_BLOB_HASH_LENGTH 40
static_assert(FOSSILIZE_BLOB_HASH_LENGTH >= 32, "Blob hash length must be at least 32.");
namespace Fossilize
{
class ConditionalLockGuard
{
public:
ConditionalLockGuard(std::mutex &lock_, bool enable_)
: lock(lock_), enable(enable_)
{
if (enable)
lock.lock();
}
~ConditionalLockGuard()
{
if (enable)
lock.unlock();
}
private:
std::mutex &lock;
bool enable;
};
struct PayloadHeader
{
uint32_t payload_size;
uint32_t format;
uint32_t crc;
uint32_t uncompressed_size;
};
struct ExportedMetadataBlock
{
Hash hash;
uint64_t file_offset;
PayloadHeader payload;
};
static_assert(sizeof(ExportedMetadataBlock) % 8 == 0, "Alignment of ExportedMetadataBlock must be 8.");
// Encodes a unique list of hashes, so that we don't have to maintain per-process hashmaps
// when replaying concurrent databases.
using ExportedMetadataConcurrentPrimedBlock = Hash;
static_assert(sizeof(ExportedMetadataConcurrentPrimedBlock) % 8 == 0, "Alignment of ExportedMetadataPrimedBlock must be 8.");
struct ExportedMetadataList
{
uint64_t offset;
uint64_t count;
};
static_assert(sizeof(ExportedMetadataList) % 8 == 0, "Alignment of ExportedMetadataList must be 8.");
// Only for sanity checking when importing blobs, not a true file format.
static const uint64_t ExportedMetadataMagic = 0xb10bf05511153ull;
static const uint64_t ExportedMetadataMagicConcurrent = 0xb10b5f05511153ull;
struct ExportedMetadataHeader
{
uint64_t magic;
uint64_t size;
ExportedMetadataList lists[RESOURCE_COUNT];
};
static_assert(sizeof(ExportedMetadataHeader) % 8 == 0, "Alignment of ExportedMetadataHeader must be 8.");
// Allow termination request if using the interface on a thread
std::atomic<bool> shutdown_requested;
struct DatabaseInterface::Impl
{
std::unique_ptr<DatabaseInterface> whitelist;
std::unique_ptr<DatabaseInterface> blacklist;
std::vector<unsigned> sub_databases_in_whitelist;
std::unordered_set<Hash> implicit_whitelisted[RESOURCE_COUNT];
DatabaseMode mode;
uint32_t whitelist_tag_mask = (1u << RESOURCE_SHADER_MODULE) |
(1u << RESOURCE_GRAPHICS_PIPELINE) |
(1u << RESOURCE_COMPUTE_PIPELINE);
const ExportedMetadataHeader *imported_concurrent_metadata = nullptr;
std::vector<const ExportedMetadataHeader *> imported_metadata;
const uint8_t *mapped_metadata = nullptr;
size_t mapped_metadata_size = 0;
bool parse_imported_metadata(const void *data, size_t size);
};
DatabaseInterface::DatabaseInterface(DatabaseMode mode)
{
impl = new Impl;
impl->mode = mode;
}
bool DatabaseInterface::has_sub_databases()
{
return false;
}
DatabaseInterface *DatabaseInterface::get_sub_database(unsigned)
{
return nullptr;
}
void DatabaseInterface::set_whitelist_tag_mask(uint32_t mask)
{
impl->whitelist_tag_mask = mask;
}
bool DatabaseInterface::load_whitelist_database(const char *path)
{
if (impl->mode != DatabaseMode::ReadOnly)
return false;
if (!impl->imported_metadata.empty())
{
LOGE_LEVEL("Cannot use imported metadata together with whitelists.\n");
return false;
}
impl->whitelist.reset(create_stream_archive_database(path, DatabaseMode::ReadOnly));
if (!impl->whitelist)
return false;
if (!impl->whitelist->prepare())
{
impl->whitelist.reset();
return false;
}
return true;
}
bool DatabaseInterface::load_blacklist_database(const char *path)
{
if (impl->mode != DatabaseMode::ReadOnly)
return false;
if (!impl->imported_metadata.empty())
{
LOGE_LEVEL("Cannot use imported metadata together with blacklists.\n");
return false;
}
impl->blacklist.reset(create_stream_archive_database(path, DatabaseMode::ReadOnly));
if (!impl->blacklist)
return false;
if (!impl->blacklist->prepare())
{
impl->blacklist.reset();
return false;
}
return true;
}
void DatabaseInterface::promote_sub_database_to_whitelist(unsigned index)
{
if (impl->mode != DatabaseMode::ReadOnly)
return;
impl->sub_databases_in_whitelist.push_back(index);
}
bool DatabaseInterface::add_to_implicit_whitelist(DatabaseInterface &iface)
{
std::vector<Hash> hashes;
size_t size = 0;
const auto promote = [&](ResourceTag tag) -> bool {
if (!iface.get_hash_list_for_resource_tag(tag, &size, nullptr))
return false;
hashes.resize(size);
if (!iface.get_hash_list_for_resource_tag(tag, &size, hashes.data()))
return false;
for (auto &h : hashes)
impl->implicit_whitelisted[tag].insert(h);
return true;
};
if (!promote(RESOURCE_SHADER_MODULE))
return false;
if (!promote(RESOURCE_GRAPHICS_PIPELINE))
return false;
if (!promote(RESOURCE_COMPUTE_PIPELINE))
return false;
return true;
}
DatabaseInterface::~DatabaseInterface()
{
#ifdef _WIN32
if (impl->mapped_metadata)
UnmapViewOfFile(impl->mapped_metadata);
#else
if (impl->mapped_metadata)
munmap(const_cast<uint8_t *>(impl->mapped_metadata), impl->mapped_metadata_size);
#endif
delete impl;
}
bool DatabaseInterface::test_resource_filter(ResourceTag tag, Hash hash) const
{
if ((impl->whitelist_tag_mask & (1u << tag)) != 0)
{
bool whitelist_sensitive = impl->whitelist || !impl->sub_databases_in_whitelist.empty();
if (whitelist_sensitive)
{
bool whitelisted = (impl->whitelist && impl->whitelist->has_entry(tag, hash)) ||
(impl->implicit_whitelisted[tag].count(hash) != 0);
if (!whitelisted)
return false;
}
}
if (impl->blacklist && impl->blacklist->has_entry(tag, hash))
return false;
return true;
}
intptr_t DatabaseInterface::invalid_metadata_handle()
{
#ifdef _WIN32
return 0;
#else
return -1;
#endif
}
bool DatabaseInterface::metadata_handle_is_valid(intptr_t handle)
{
#ifdef _WIN32
return handle != 0;
#else
return handle >= 0;
#endif
}
static std::atomic<uint32_t> name_counter;
void DatabaseInterface::get_unique_os_export_name(char *buffer, size_t size)
{
unsigned counter_value = name_counter.fetch_add(1);
#ifdef _WIN32
snprintf(buffer, size, "fossilize-replayer-%lu-%u", GetCurrentProcessId(), counter_value);
#else
snprintf(buffer, size, "/fossilize-replayer-%d-%u", getpid(), counter_value);
#endif
}
intptr_t DatabaseInterface::export_metadata_to_os_handle(const char *name)
{
if (impl->mode != DatabaseMode::ReadOnly)
return invalid_metadata_handle();
size_t size = compute_exported_metadata_size();
if (!size)
return invalid_metadata_handle();
#ifdef _WIN32
HANDLE mapping_handle = CreateFileMappingA(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, 0, (DWORD)size, name);
if (!mapping_handle)
return invalid_metadata_handle();
void *mapped = MapViewOfFile(mapping_handle, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, size);
if (!mapped)
{
CloseHandle(mapping_handle);
return invalid_metadata_handle();
}
if (!write_exported_metadata(mapped, size))
{
LOGE_LEVEL("Failed to write metadata block.\n");
UnmapViewOfFile(mapped);
CloseHandle(mapping_handle);
return invalid_metadata_handle();
}
UnmapViewOfFile(mapped);
return reinterpret_cast<intptr_t>(mapping_handle);
#elif !defined(ANDROID)
int fd = shm_open(name, O_RDWR | O_CREAT | O_EXCL, 0600);
if (fd < 0)
{
LOGE_LEVEL("Failed to create shared memory.\n");
return invalid_metadata_handle();
}
if (shm_unlink(name) < 0)
{
LOGE_LEVEL("Failed to unlink SHM block.\n");
close(fd);
return invalid_metadata_handle();
}
if (ftruncate(fd, size) < 0)
{
LOGE_LEVEL("Failed to allocate space for metadata block.\n");
close(fd);
return invalid_metadata_handle();
}
void *mapped = mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (mapped == MAP_FAILED)
{
LOGE_LEVEL("Failed to map metadata block.\n");
close(fd);
return invalid_metadata_handle();
}
if (!write_exported_metadata(mapped, size))
{
LOGE_LEVEL("Failed to write metadata block.\n");
munmap(mapped, size);
close(fd);
return invalid_metadata_handle();
}
munmap(mapped, size);
return intptr_t(fd);
#else
return invalid_metadata_handle();
#endif
}
size_t DatabaseInterface::compute_exported_metadata_size() const
{
return 0;
}
bool DatabaseInterface::write_exported_metadata(void *, size_t) const
{
return false;
}
void DatabaseInterface::add_imported_metadata(const ExportedMetadataHeader *header)
{
impl->imported_metadata.push_back(header);
}
bool DatabaseInterface::set_bucket_path(const char *, const char *)
{
return false;
}
static size_t deduce_imported_size(const void *mapped, size_t maximum_size)
{
size_t total_size = 0;
while (total_size + sizeof(ExportedMetadataHeader) <= maximum_size)
{
auto *header = reinterpret_cast<const ExportedMetadataHeader *>(static_cast<const uint8_t *>(mapped) + total_size);
if (header->size + total_size > maximum_size)
break;
if (header->magic != ExportedMetadataMagic && header->magic != ExportedMetadataMagicConcurrent)
break;
total_size += header->size;
}
return total_size;
}
bool DatabaseInterface::Impl::parse_imported_metadata(const void *data_, size_t size_)
{
std::vector<const ExportedMetadataHeader *> headers;
auto *data = static_cast<const uint8_t *>(data_);
// Imported size might be rounded up to page size, so find exact bound first.
size_t size = deduce_imported_size(data_, size_);
if (size < sizeof(ExportedMetadataHeader))
return false;
auto *concurrent_header = reinterpret_cast<const ExportedMetadataHeader *>(data);
if (concurrent_header->magic == ExportedMetadataMagicConcurrent)
{
data += concurrent_header->size;
size -= concurrent_header->size;
}
else
concurrent_header = nullptr;
while (size != 0)
{
if (size < sizeof(ExportedMetadataHeader))
return false;
auto *header = reinterpret_cast<const ExportedMetadataHeader *>(data);
if (header->magic != ExportedMetadataMagic)
return false;
if (header->size > size)
return false;
for (auto &list : header->lists)
if (list.offset + list.count * sizeof(ExportedMetadataBlock) > size)
return false;
data += header->size;
size -= header->size;
headers.push_back(header);
}
#ifdef _WIN32
if (mapped_metadata)
UnmapViewOfFile(mapped_metadata);
#else
if (mapped_metadata)
munmap(const_cast<uint8_t *>(mapped_metadata), mapped_metadata_size);
#endif
mapped_metadata = static_cast<const uint8_t *>(data_);
mapped_metadata_size = size_;
imported_metadata = std::move(headers);
imported_concurrent_metadata = concurrent_header;
return true;
}
bool DatabaseInterface::import_metadata_from_os_handle(intptr_t handle)
{
if (impl->whitelist || impl->blacklist)
{
LOGE_LEVEL("Cannot use imported metadata along with white- or blacklists.\n");
return false;
}
#ifdef _WIN32
HANDLE mapping_handle = reinterpret_cast<HANDLE>(handle);
void *mapped = MapViewOfFile(mapping_handle, FILE_MAP_READ, 0, 0, 0);
if (!mapped)
return false;
// There is no documented way to query size of a file mapping handle in Windows (?!?!), so rely on parsing the metadata.
// As long as we find valid records within the bounds of the VirtualQuery, we will be fine.
MEMORY_BASIC_INFORMATION info;
if (!VirtualQuery(mapped, &info, sizeof(info)))
{
UnmapViewOfFile(mapped);
return false;
}
bool ret = impl->parse_imported_metadata(mapped, info.RegionSize);
if (ret)
CloseHandle(mapping_handle);
else
UnmapViewOfFile(mapped);
return ret;
#else
int fd = int(handle);
struct stat s = {};
if (fstat(fd, &s) < 0)
return false;
if (s.st_size == 0)
return false;
void *mapped = mmap(nullptr, s.st_size, PROT_READ, MAP_SHARED, fd, 0);
if (mapped == MAP_FAILED)
return false;
bool ret = impl->parse_imported_metadata(mapped, s.st_size);
if (ret)
close(fd);
else
munmap(mapped, s.st_size);
return ret;
#endif
}
struct DumbDirectoryDatabase : DatabaseInterface
{
DumbDirectoryDatabase(const string &base, DatabaseMode mode_)
: DatabaseInterface(mode_), base_directory(base), mode(mode_)
{
if (mode == DatabaseMode::ExclusiveOverWrite)
mode = DatabaseMode::OverWrite;
}
void flush() override
{
}
bool prepare() override
{
if (mode == DatabaseMode::OverWrite)
return true;
DIR *dp = opendir(base_directory.c_str());
if (!dp)
return false;
while (auto *pEntry = readdir(dp))
{
if (shutdown_requested.load(std::memory_order_relaxed))
return false;
if (pEntry->d_type != DT_REG)
continue;
unsigned tag;
uint64_t value;
if (sscanf(pEntry->d_name, "%x.%" SCNx64 ".json", &tag, &value) != 2)
continue;
if (tag >= RESOURCE_COUNT)
continue;
if (test_resource_filter(static_cast<ResourceTag>(tag), value))
seen_blobs[tag].insert(value);
}
closedir(dp);
return true;
}
bool has_entry(ResourceTag tag, Hash hash) override
{
if (!test_resource_filter(tag, hash))
return false;
return seen_blobs[tag].count(hash) != 0;
}
bool read_entry(ResourceTag tag, Hash hash, size_t *blob_size, void *blob, PayloadReadFlags flags) override
{
if ((flags & PAYLOAD_READ_RAW_FOSSILIZE_DB_BIT) != 0)
return false;
if (mode != DatabaseMode::ReadOnly)
return false;
if (!has_entry(tag, hash))
return false;
if (!blob_size)
return false;
char filename[25]; // 2 digits + "." + 16 digits + ".json" + null
sprintf(filename, "%02x.%016" PRIx64 ".json", static_cast<unsigned>(tag), hash);
auto path = Path::join(base_directory, filename);
FILE *file = fopen(path.c_str(), "rb");
if (!file)
{
LOGE_LEVEL("Failed to open file: %s\n", path.c_str());
return false;
}
if (fseek(file, 0, SEEK_END) < 0)
{
fclose(file);
LOGE_LEVEL("Failed to seek in file: %s\n", path.c_str());
return false;
}
size_t file_size = size_t(ftell(file));
rewind(file);
if (blob && *blob_size < file_size)
{
fclose(file);
return false;
}
*blob_size = file_size;
if (blob)
{
if (fread(blob, 1, file_size, file) != file_size)
{
fclose(file);
return false;
}
}
fclose(file);
return true;
}
bool write_entry(ResourceTag tag, Hash hash, const void *blob, size_t size, PayloadWriteFlags flags) override
{
if ((flags & PAYLOAD_WRITE_RAW_FOSSILIZE_DB_BIT) != 0)
return false;
if (mode == DatabaseMode::ReadOnly)
return false;
if (has_entry(tag, hash))
return true;
char filename[25]; // 2 digits + "." + 16 digits + ".json" + null
sprintf(filename, "%02x.%016" PRIx64 ".json", static_cast<unsigned>(tag), hash);
auto path = Path::join(base_directory, filename);
FILE *file = fopen(path.c_str(), "wb");
if (!file)
{
LOGE_LEVEL("Failed to write serialized state to disk (%s).\n", path.c_str());
return false;
}
if (fwrite(blob, 1, size, file) != size)
{
LOGE_LEVEL("Failed to write serialized state to disk.\n");
fclose(file);
return false;
}
fclose(file);
return true;
}
bool get_hash_list_for_resource_tag(ResourceTag tag, size_t *hash_count, Hash *hashes) override
{
size_t size = seen_blobs[tag].size();
if (hashes)
{
if (size != *hash_count)
return false;
}
else
*hash_count = size;
if (hashes)
{
Hash *iter = hashes;
for (auto &blob : seen_blobs[tag])
*iter++ = blob;
// Make replay more deterministic.
sort(hashes, hashes + size);
}
return true;
}
const char *get_db_path_for_hash(ResourceTag tag, Hash hash) override
{
if (!has_entry(tag, hash))
return nullptr;
return base_directory.c_str();
}
string base_directory;
DatabaseMode mode;
unordered_set<Hash> seen_blobs[RESOURCE_COUNT];
};
DatabaseInterface *create_dumb_folder_database(const char *directory_path, DatabaseMode mode)
{
auto *db = new DumbDirectoryDatabase(directory_path, mode);
return db;
}
struct ZipDatabase : DatabaseInterface
{
ZipDatabase(const string &path_, DatabaseMode mode_)
: DatabaseInterface(mode_), path(path_), mode(mode_)
{
if (mode == DatabaseMode::ExclusiveOverWrite)
mode = DatabaseMode::OverWrite;
mz_zip_zero_struct(&mz);
}
~ZipDatabase()
{
if (alive)
{
if (mode != DatabaseMode::ReadOnly)
{
if (!mz_zip_writer_finalize_archive(&mz))
LOGE_LEVEL("Failed to finalize archive.\n");
}
if (!mz_zip_end(&mz))
LOGE_LEVEL("mz_zip_end failed!\n");
}
}
void flush() override
{
}
static bool string_is_hex(const char *str)
{
while (*str)
{
if (!isxdigit(uint8_t(*str)))
return false;
str++;
}
return true;
}
bool prepare() override
{
if (mode != DatabaseMode::OverWrite && mz_zip_reader_init_file(&mz, path.c_str(), 0))
{
// We have an existing archive.
unsigned files = mz_zip_reader_get_num_files(&mz);
char filename[MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE] = {};
for (unsigned i = 0; i < files; i++)
{
if (shutdown_requested.load(std::memory_order_relaxed))
return false;
if (mz_zip_reader_is_file_a_directory(&mz, i))
continue;
mz_zip_reader_get_filename(&mz, i, filename, sizeof(filename));
size_t len = strlen(filename);
if (len != FOSSILIZE_BLOB_HASH_LENGTH)
continue;
if (!string_is_hex(filename))
continue;
mz_zip_archive_file_stat s;
if (!mz_zip_reader_file_stat(&mz, i, &s))
continue;
char tag_str[16 + 1] = {};
char value_str[16 + 1] = {};
memcpy(tag_str, filename + FOSSILIZE_BLOB_HASH_LENGTH - 32, 16);
memcpy(value_str, filename + FOSSILIZE_BLOB_HASH_LENGTH - 16, 16);
auto tag = unsigned(strtoul(tag_str, nullptr, 16));
if (tag >= RESOURCE_COUNT)
continue;
uint64_t value = strtoull(value_str, nullptr, 16);
if (test_resource_filter(static_cast<ResourceTag>(tag), value))
seen_blobs[tag].emplace(value, Entry{i, size_t(s.m_uncomp_size)});
}
// In-place update the archive. Should we consider emitting a new archive instead?
if (!mz_zip_writer_init_from_reader(&mz, path.c_str()))
{
LOGE_LEVEL("Failed to initialize ZIP writer from reader.\n");
mz_zip_end(&mz);
return false;
}
alive = true;
}
else if (mode != DatabaseMode::ReadOnly)
{
if (!mz_zip_writer_init_file(&mz, path.c_str(), 0))
{
LOGE_LEVEL("Failed to open ZIP archive for writing. Cannot serialize anything to disk.\n");
return false;
}
alive = true;
for (auto &blob : seen_blobs)
blob.clear();
}
return true;
}
bool read_entry(ResourceTag tag, Hash hash, size_t *blob_size, void *blob, PayloadReadFlags flags) override
{
if ((flags & PAYLOAD_READ_RAW_FOSSILIZE_DB_BIT) != 0)
return false;
if (!alive || mode != DatabaseMode::ReadOnly)
return false;
auto itr = seen_blobs[tag].find(hash);
if (itr == end(seen_blobs[tag]))
return false;
if (!blob_size)
return false;
if (blob && *blob_size < itr->second.size)
return false;
*blob_size = itr->second.size;
if (blob)
{
if (!mz_zip_reader_extract_to_mem(&mz, itr->second.index, blob, itr->second.size, 0))
{
LOGE_LEVEL("Failed to extract blob.\n");
return false;
}
}
return true;
}
bool write_entry(ResourceTag tag, Hash hash, const void *blob, size_t size, PayloadWriteFlags flags) override
{
if ((flags & PAYLOAD_WRITE_RAW_FOSSILIZE_DB_BIT) != 0)
return false;
if (!alive || mode == DatabaseMode::ReadOnly)
return false;
auto itr = seen_blobs[tag].find(hash);
if (itr != end(seen_blobs[tag]))
return true;
char str[FOSSILIZE_BLOB_HASH_LENGTH + 1]; // 40 digits + null
sprintf(str, "%0*x", FOSSILIZE_BLOB_HASH_LENGTH - 16, tag);
sprintf(str + FOSSILIZE_BLOB_HASH_LENGTH - 16, "%016" PRIx64, hash);
unsigned mz_flags;
if ((flags & PAYLOAD_WRITE_COMPRESS_BIT) != 0)
{
if ((flags & PAYLOAD_WRITE_BEST_COMPRESSION_BIT) != 0)
mz_flags = MZ_BEST_COMPRESSION;
else
mz_flags = MZ_BEST_SPEED;
}
else
mz_flags = MZ_NO_COMPRESSION;
if (!mz_zip_writer_add_mem(&mz, str, blob, size, mz_flags))
{
LOGE_LEVEL("Failed to add blob to cache.\n");
return false;
}
// The index is irrelevant, we're not going to read from this archive any time soon.
if (test_resource_filter(static_cast<ResourceTag>(tag), hash))
seen_blobs[tag].emplace(hash, Entry{~0u, size});
return true;
}
bool has_entry(ResourceTag tag, Hash hash) override
{
if (!test_resource_filter(tag, hash))
return false;
return seen_blobs[tag].count(hash) != 0;
}
bool get_hash_list_for_resource_tag(ResourceTag tag, size_t *hash_count, Hash *hashes) override
{
size_t size = seen_blobs[tag].size();
if (hashes)
{
if (size != *hash_count)
return false;
}
else
*hash_count = size;
if (hashes)
{
Hash *iter = hashes;
for (auto &blob : seen_blobs[tag])
*iter++ = blob.first;
// Make replay more deterministic.
sort(hashes, hashes + size);
}
return true;
}
const char *get_db_path_for_hash(ResourceTag tag, Hash hash) override
{
if (!has_entry(tag, hash))
return nullptr;
return path.c_str();
}
string path;
mz_zip_archive mz;
struct Entry
{
unsigned index;
size_t size;
};
unordered_map<Hash, Entry> seen_blobs[RESOURCE_COUNT];
DatabaseMode mode;
bool alive = false;
};
DatabaseInterface *create_zip_archive_database(const char *path, DatabaseMode mode)
{
auto *db = new ZipDatabase(path, mode);
return db;
}
/* Fossilize StreamArchive database format version 6:
*
* The file consists of a header, followed by an unlimited series of "entries".
*
* All multi-byte entities are little-endian.
*
* The file header is as follows:
*
* Field Type Description
* ----- ---- -----------
* magic_number uint8_t[12] Constant value: "\x81""FOSSILIZEDB"
* unused1 uint8_t Currently unused. Must be zero.
* unused2 uint8_t Currently unused. Must be zero.
* unused3 uint8_t Currently unused. Must be zero.
* version uint8_t StreamArchive version: 6
*
*
* Each entry follows this format:
*
* Field Type Description
* ----- ---- -----------
* tag unsigned char[40 - hash_bytes] Application-defined 'tag' which groups entry types. Stored as hexadecimal ASCII.
* hash unsigned char[hash_bytes] Application-defined 'hash' to identify this entry. Stored as hexadecimal ASCII.
* stored_size uint32_t Size of the payload as stored in this file.
* flags uint32_t Flags for this entry (e.g. compression). See below.
* crc32 uint32_t CRC32 of the payload as stored in this file. If zero, checksum is not checked when reading.
* payload_size uint32_t Size of this payload after decompression.
* payload uint8_t[stored_size] Entry data.
*
* The flags field must contain one of:
* 0x1: No compression.
* 0x2: Deflate compression.
*
* Entries should have a unique tag and hash combination. Implementations may
* ignore duplicated tag and hash combinations.
*
* It is acceptable for the last entry to be truncated. In this case, that
* entry should be ignored.
*/
static const uint8_t stream_reference_magic_and_version[16] = {
0x81, 'F', 'O', 'S',
'S', 'I', 'L', 'I',
'Z', 'E', 'D', 'B',
0, 0, 0,
FOSSILIZE_FORMAT_VERSION,
};
struct StreamArchive : DatabaseInterface
{
enum { MagicSize = sizeof(stream_reference_magic_and_version) };
enum { FOSSILIZE_COMPRESSION_NONE = 1, FOSSILIZE_COMPRESSION_DEFLATE = 2 };