forked from panda3d/panda3d
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpatchfile.cxx
More file actions
1337 lines (1142 loc) · 40.1 KB
/
patchfile.cxx
File metadata and controls
1337 lines (1142 loc) · 40.1 KB
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
/**
* PANDA 3D SOFTWARE
* Copyright (c) Carnegie Mellon University. All rights reserved.
*
* All use of this software is subject to the terms of the revised BSD
* license. You should have received a copy of this license along
* with this source code in a file named "LICENSE."
*
* @file patchfile.cxx
* @author darren, mike
* @date 1997-01-09
*/
#include "pandabase.h"
#ifdef HAVE_OPENSSL
#include "config_express.h"
#include "error_utils.h"
#include "patchfile.h"
#include "streamReader.h"
#include "streamWriter.h"
#include "multifile.h"
#include "hashVal.h"
#include "virtualFileSystem.h"
#include <string.h> // for strstr
using std::endl;
using std::ios;
using std::istream;
using std::min;
using std::ostream;
using std::streampos;
using std::string;
// this actually slows things down... #define
// USE_MD5_FOR_HASHTABLE_INDEX_VALUES
/*
* Patch File Format IF THIS CHANGES, UPDATE installerApplyPatch.cxx IN THE
* INSTALLER [ HEADER ] 4 bytes 0xfeebfaac ("magic number") (older patch
* files have a magic number 0xfeebfaab, indicating they are version number
* 0.) 2 bytes version number (if magic number == 0xfeebfaac) 4 bytes length
* of starting file (if version >= 1) 16 bytes MD5 of starting file (if
* version >= 1) 4 bytes length of resulting patched file 16 bytes MD5 of
* resultant patched file Note that MD5 hashes are written in the order
* observed by HashVal::read_stream() and HashVal::write_stream(), which is
* not the normal linear order. (Each group of four bytes is reversed.)
*/
const int _v0_header_length = 4 + 4 + 16;
const int _v1_header_length = 4 + 2 + 4 + 16 + 4 + 16;
/*
* [ ADDCOPY pairs; repeated N times ] 2 bytes AL = ADD length AL bytes
* bytes to add 2 bytes CL = COPY length 4 bytes offset of data to copy from
* original file, if CL != 0. If version >= 2, offset is relative to end of
* previous copy block; if version < 2, offset is relative to beginning of
* file. [ TERMINATOR ] 2 bytes zero-length ADD 2 bytes zero-length COPY
*/
// Defines
const uint32_t Patchfile::_v0_magic_number = 0xfeebfaab;
const uint32_t Patchfile::_magic_number = 0xfeebfaac;
// Created version 1 on 11202 to store length and MD5 of original file. To
// version 2 on 11202 to store copy offsets as relative.
const uint16_t Patchfile::_current_version = 2;
const uint32_t Patchfile::_HASH_BITS = 24;
const uint32_t Patchfile::_HASHTABLESIZE = uint32_t(1) << Patchfile::_HASH_BITS;
const uint32_t Patchfile::_DEFAULT_FOOTPRINT_LENGTH = 9; // this produced the smallest patch file for libpanda.dll when tested, 12/20/2000
const uint32_t Patchfile::_NULL_VALUE = uint32_t(0) - 1;
const uint32_t Patchfile::_MAX_RUN_LENGTH = (uint32_t(1) << 16) - 1;
const uint32_t Patchfile::_HASH_MASK = (uint32_t(1) << Patchfile::_HASH_BITS) - 1;
/**
* Create a patch file and initializes internal data
*/
Patchfile::
Patchfile() {
PT(Buffer) buffer = new Buffer(patchfile_buffer_size);
init(buffer);
}
/**
* Create patch file with buffer to patch
*/
Patchfile::
Patchfile(PT(Buffer) buffer) {
init(buffer);
}
/**
*
*/
void Patchfile::
init(PT(Buffer) buffer) {
_rename_output_to_orig = false;
_delete_patchfile = false;
_hash_table = nullptr;
_initiated = false;
nassertv(!buffer.is_null());
_buffer = buffer;
_version_number = 0;
_allow_multifile = true;
_patch_stream = nullptr;
_origfile_stream = nullptr;
reset_footprint_length();
}
/**
*
*/
Patchfile::
~Patchfile() {
if (_hash_table != nullptr) {
PANDA_FREE_ARRAY(_hash_table);
}
if (_initiated) {
cleanup();
}
nassertv(_patch_stream == nullptr);
nassertv(_origfile_stream == nullptr);
}
/**
* Closes and clean up internal data structures
*/
void Patchfile::
cleanup() {
if (!_initiated) {
express_cat.error()
<< "Patchfile::cleanup() - Patching has not been initiated"
<< endl;
return;
}
// close files
VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr();
if (_origfile_stream != nullptr) {
vfs->close_read_file(_origfile_stream);
_origfile_stream = nullptr;
}
if (_patch_stream != nullptr) {
vfs->close_read_file(_patch_stream);
_patch_stream = nullptr;
}
_write_stream.close();
_initiated = false;
}
// PATCH FILE APPLY MEMBER FUNCTIONS
// NOTE: this patch-application functionality unfortunately has to be
// duplicated in the Installer. It is contained in the file
// installerApplyPatch.cxx PLEASE MAKE SURE THAT THAT FILE GETS UPDATED IF ANY
// OF THIS LOGIC CHANGES! (i.e. if the patch file format changes)
/**
* Set up to apply the patch to the file (original file and patch are
* destroyed in the process).
*/
int Patchfile::
initiate(const Filename &patch_file, const Filename &file) {
int result = initiate(patch_file, file, Filename::temporary("", "patch_"));
_rename_output_to_orig = true;
_delete_patchfile = !keep_temporary_files;
return result;
}
/**
* Set up to apply the patch to the file. In this form, neither the original
* file nor the patch file are destroyed.
*/
int Patchfile::
initiate(const Filename &patch_file, const Filename &orig_file,
const Filename &target_file) {
if (_initiated) {
express_cat.error()
<< "Patchfile::initiate() - Patching has already been initiated"
<< endl;
return EU_error_abort;
}
nassertr(orig_file != target_file, EU_error_abort);
VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr();
// Open the original file for read
nassertr(_origfile_stream == nullptr, EU_error_abort);
_orig_file = orig_file;
_orig_file.set_binary();
_origfile_stream = vfs->open_read_file(_orig_file, false);
if (_origfile_stream == nullptr) {
express_cat.error()
<< "Patchfile::initiate() - Failed to open file: " << _orig_file << endl;
return get_write_error();
}
// Open the temp file for write
_output_file = target_file;
_output_file.set_binary();
if (!_output_file.open_write(_write_stream)) {
express_cat.error()
<< "Patchfile::initiate() - Failed to open file: " << _output_file << endl;
return get_write_error();
}
if (express_cat.is_debug()) {
express_cat.debug()
<< "Patchfile using output file " << _output_file << "\n";
}
int result = internal_read_header(patch_file);
_total_bytes_processed = 0;
_initiated = true;
return result;
}
/**
* Opens the patch file for reading, and gets the header information from the
* file but does not begin to do any real work. This can be used to query the
* data stored in the patch.
*/
int Patchfile::
read_header(const Filename &patch_file) {
if (_initiated) {
express_cat.error()
<< "Patchfile::initiate() - Patching has already been initiated"
<< endl;
return EU_error_abort;
}
int result = internal_read_header(patch_file);
if (_patch_stream != nullptr) {
VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr();
vfs->close_read_file(_patch_stream);
_patch_stream = nullptr;
}
return result;
}
/**
* Perform one buffer's worth of patching Returns EU_ok while patching Returns
* EU_success when done If error happens will return one of: EU_error_abort :
* Patching has not been initiated EU_error_file_invalid : file is corrupted
* EU_error_invalid_checksum : incompatible patch file
* EU_error_write_file_rename : could not rename file
*/
int Patchfile::
run() {
// Now patch the file using the given buffer
int buflen;
int bytes_read;
uint16_t ADD_length;
uint16_t COPY_length;
int32_t COPY_offset;
if (_initiated == false) {
express_cat.error()
<< "Patchfile::run() - Patching has not been initiated"
<< endl;
return EU_error_abort;
}
nassertr(_patch_stream != nullptr, EU_error_abort);
nassertr(_origfile_stream != nullptr, EU_error_abort);
StreamReader patch_reader(*_patch_stream);
buflen = _buffer->get_length();
bytes_read = 0;
while (bytes_read < buflen) {
// read # of ADD bytes
nassertr(_buffer->get_length() >= (int)sizeof(ADD_length), false);
ADD_length = patch_reader.get_uint16();
if (_patch_stream->fail()) {
express_cat.error()
<< "Truncated patch file.\n";
return EU_error_file_invalid;
}
bytes_read += (int)ADD_length;
_total_bytes_processed += (int)ADD_length;
if (_total_bytes_processed > _total_bytes_to_process) {
express_cat.error()
<< "Runaway patch file.\n";
return EU_error_file_invalid;
}
// if there are bytes to add, read them from patch file and write them to
// output
if (express_cat.is_spam() && ADD_length != 0) {
express_cat.spam()
<< "ADD: " << ADD_length << " (to "
<< _write_stream.tellp() << ")" << endl;
}
uint32_t bytes_left = (uint32_t)ADD_length;
while (bytes_left > 0) {
uint32_t bytes_this_time = (uint32_t) min(bytes_left, (uint32_t) buflen);
_patch_stream->read(_buffer->_buffer, bytes_this_time);
if (_patch_stream->fail()) {
express_cat.error()
<< "Truncated patch file.\n";
return EU_error_file_invalid;
}
_write_stream.write(_buffer->_buffer, bytes_this_time);
bytes_left -= bytes_this_time;
}
// read # of COPY bytes
nassertr(_buffer->get_length() >= (int)sizeof(COPY_length), false);
COPY_length = patch_reader.get_uint16();
if (_patch_stream->fail()) {
express_cat.error()
<< "Truncated patch file.\n";
return EU_error_file_invalid;
}
bytes_read += (int)COPY_length;
_total_bytes_processed += (int)COPY_length;
if (_total_bytes_processed > _total_bytes_to_process) {
express_cat.error()
<< "Runaway patch file.\n";
return EU_error_file_invalid;
}
// if there are bytes to copy, read them from original file and write them
// to output
if (0 != COPY_length) {
// read copy offset
nassertr(_buffer->get_length() >= (int)sizeof(COPY_offset), false);
COPY_offset = patch_reader.get_int32();
if (_patch_stream->fail()) {
express_cat.error()
<< "Truncated patch file.\n";
return EU_error_file_invalid;
}
// seek to the copy source pos
if (_version_number < 2) {
_origfile_stream->seekg(COPY_offset, ios::beg);
} else {
_origfile_stream->seekg(COPY_offset, ios::cur);
}
if (_origfile_stream->fail()) {
express_cat.error()
<< "Invalid copy offset in patch file.\n";
return EU_error_file_invalid;
}
if (express_cat.is_spam()) {
express_cat.spam()
<< "COPY: " << COPY_length << " bytes from offset "
<< COPY_offset << " (from " << _origfile_stream->tellg()
<< " to " << _write_stream.tellp() << ")"
<< endl;
}
// read the copy bytes from original file and write them to output
uint32_t bytes_left = (uint32_t)COPY_length;
while (bytes_left > 0) {
uint32_t bytes_this_time = (uint32_t) min(bytes_left, (uint32_t) buflen);
_origfile_stream->read(_buffer->_buffer, bytes_this_time);
if (_origfile_stream->fail()) {
express_cat.error()
<< "Invalid copy length in patch file.\n";
return EU_error_file_invalid;
}
_write_stream.write(_buffer->_buffer, bytes_this_time);
bytes_left -= bytes_this_time;
}
}
// if we got a pair of zero-length ADD and COPY blocks, we're done
if ((0 == ADD_length) && (0 == COPY_length)) {
cleanup();
if (express_cat.is_debug()) {
express_cat.debug()
// << "result file = " << _result_file_length
<< " total bytes = " << _total_bytes_processed << endl;
}
// check the MD5 from the patch file against the newly patched file
{
HashVal MD5_actual;
MD5_actual.hash_file(_output_file);
if (_MD5_ofResult != MD5_actual) {
// Whoops, patching screwed up somehow.
if (_origfile_stream != nullptr) {
VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr();
vfs->close_read_file(_origfile_stream);
_origfile_stream = nullptr;
}
_write_stream.close();
express_cat.info()
<< "Patching produced incorrect checksum. Got:\n"
<< " " << MD5_actual
<< "\nExpected:\n"
<< " " << _MD5_ofResult
<< "\n";
// This is a fine time to double-check the starting checksum.
if (!has_source_hash()) {
express_cat.info()
<< "No source hash in patch file to verify.\n";
} else {
HashVal MD5_orig;
MD5_orig.hash_file(_orig_file);
if (MD5_orig != get_source_hash()) {
express_cat.info()
<< "Started from incorrect source file. Got:\n"
<< " " << MD5_orig
<< "\nExpected:\n"
<< " " << get_source_hash()
<< "\n";
} else {
express_cat.info()
<< "Started from correct source file:\n"
<< " " << MD5_orig
<< "\n";
}
}
// delete the temp file and the patch file
if (_rename_output_to_orig) {
_output_file.unlink();
}
if (_delete_patchfile) {
_patch_file.unlink();
}
// return "invalid checksum"
return EU_error_invalid_checksum;
}
}
// delete the patch file
if (_delete_patchfile) {
_patch_file.unlink();
}
// rename the temp file to the original file name
if (_rename_output_to_orig) {
_orig_file.unlink();
if (!_output_file.rename_to(_orig_file)) {
express_cat.error()
<< "Patchfile::run() failed to rename temp file to: " << _orig_file
<< endl;
return EU_error_write_file_rename;
}
}
return EU_success;
}
}
return EU_ok;
}
/**
* Patches the entire file in one call returns true on success and false on
* error
*
* This version will delete the patch file and overwrite the original file.
*/
bool Patchfile::
apply(Filename &patch_file, Filename &file) {
int ret = initiate(patch_file, file);
if (ret < 0)
return false;
for (;;) {
ret = run();
if (ret == EU_success)
return true;
if (ret < 0)
return false;
}
return false;
}
/**
* Patches the entire file in one call returns true on success and false on
* error
*
* This version will not delete any files.
*/
bool Patchfile::
apply(Filename &patch_file, Filename &orig_file, const Filename &target_file) {
int ret = initiate(patch_file, orig_file, target_file);
if (ret < 0)
return false;
for (;;) {
ret = run();
if (ret == EU_success)
return true;
if (ret < 0)
return false;
}
return false;
}
/**
* Reads the header and leaves the patch file open.
*/
int Patchfile::
internal_read_header(const Filename &patch_file) {
// Open the patch file for read
VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr();
nassertr(_patch_stream == nullptr, EU_error_abort);
_patch_file = patch_file;
_patch_file.set_binary();
_patch_stream = vfs->open_read_file(_patch_file, true);
if (_patch_stream == nullptr) {
express_cat.error()
<< "Patchfile::initiate() - Failed to open file: " << _patch_file << endl;
return get_write_error();
}
// read header, make sure the patch file is valid
StreamReader patch_reader(*_patch_stream);
// check the magic number
nassertr(_buffer->get_length() >= _v0_header_length, false);
uint32_t magic_number = patch_reader.get_uint32();
if (magic_number != _magic_number && magic_number != _v0_magic_number) {
express_cat.error()
<< "Invalid patch file: " << _patch_file << endl;
return EU_error_file_invalid;
}
_version_number = 0;
if (magic_number != _v0_magic_number) {
_version_number = patch_reader.get_uint16();
}
if (_version_number > _current_version) {
express_cat.error()
<< "Can't read version " << _version_number << " patch files: "
<< _patch_file << endl;
return EU_error_file_invalid;
}
if (_version_number >= 1) {
// Get the length of the source file.
/*uint32_t source_file_length =*/ patch_reader.get_uint32();
// get the MD5 of the source file.
_MD5_ofSource.read_stream(patch_reader);
}
// get the length of the patched result file
_total_bytes_to_process = patch_reader.get_uint32();
// get the MD5 of the resultant patched file
_MD5_ofResult.read_stream(patch_reader);
if (express_cat.is_debug()) {
express_cat.debug()
<< "Patchfile::initiate() - valid patchfile" << endl;
}
return EU_success;
}
// PATCH FILE BUILDING MEMBER FUNCTIONS
/**
*
*/
uint32_t Patchfile::
calc_hash(const char *buffer) {
#ifdef USE_MD5_FOR_HASHTABLE_INDEX_VALUES
HashVal hash;
hash.hash_buffer(buffer, _footprint_length);
// cout << uint16_t(hash.get_value(0)) << " ";
return uint16_t(hash.get_value(0));
#else
uint32_t hash_value = 0;
for(int i = 0; i < (int)_footprint_length; i++) {
// this is probably not such a good hash. to be replaced --> TRIED MD5,
// was not worth it for the execution-time hit on 800Mhz PC
hash_value ^= uint32_t(*buffer) << ((i * 2) % Patchfile::_HASH_BITS);
buffer++;
}
// use the bits that overflowed past the end of the hash bit range (this is
// intended for _HASH_BITS == 24)
hash_value ^= (hash_value >> Patchfile::_HASH_BITS);
// cout << hash_value << " ";
return hash_value & _HASH_MASK;
#endif
}
/**
*
* The hash and link tables allow for a quick, linear search of all locations
* in the file that begin with a particular sequence of bytes, or "footprint."
*
* The hash table is a table of offsets into the file, with one entry for
* every possible footprint hash value. For a hash of a footprint, the entry
* at the offset of the hash value provides an initial location in the file
* that has a matching footprint.
*
* The link table is a large linked list of file offsets, with one entry for
* every byte in the file. Each offset in the link table will point to
* another offset that has the same footprint at the corresponding offset in
* the actual file. Starting with an offset taken from the hash table, one
* can rapidly produce a list of offsets that all have the same footprint.
*/
void Patchfile::
build_hash_link_tables(const char *buffer_orig, uint32_t length_orig,
uint32_t *hash_table, uint32_t *link_table) {
uint32_t i;
// clear hash table
for(i = 0; i < _HASHTABLESIZE; i++) {
hash_table[i] = _NULL_VALUE;
}
// clear link table
for(i = 0; i < length_orig; i++) {
link_table[i] = _NULL_VALUE;
}
if(length_orig < _footprint_length) return;
// run through original file and hash each footprint
for(i = 0; i < (length_orig - _footprint_length); i++) {
uint32_t hash_value = calc_hash(&buffer_orig[i]);
// we must now store this file index in the hash table at the offset of
// the hash value
// to account for multiple file offsets with identical hash values, there
// is a link table with an entry for every footprint in the file. We
// create linked lists of offsets in the link table.
// first, set the value in the link table for the current offset to
// whatever the current list head is (the value in the hash table) (note
// that this only works because the hash and link tables both use
// _NULL_VALUE to indicate a null index)
link_table[i] = hash_table[hash_value];
// set the new list head; store the current offset in the hash table at
// the offset of the footprint's hash value
hash_table[hash_value] = i;
/*
if (_NULL_VALUE == hash_table[hash_value]) {
// hash entry is empty, store this offset
hash_table[hash_value] = i;
} else {
// hash entry is taken, go to the link table
uint32_t link_offset = hash_table[hash_value];
while (_NULL_VALUE != link_table[link_offset]) {
link_offset = link_table[link_offset];
}
link_table[link_offset] = i;
}
*/
}
}
/**
*
* This function calculates the length of a match between two strings of bytes
*/
uint32_t Patchfile::
calc_match_length(const char* buf1, const char* buf2, uint32_t max_length,
uint32_t min_length) {
// early out: look ahead and sample the end of the minimum range
if (min_length > 2) {
if (min_length >= max_length)
return 0;
if (buf1[min_length] != buf2[min_length] ||
buf1[min_length-1] != buf2[min_length-1] ||
buf1[min_length-2] != buf2[min_length-2]) {
return 0;
}
}
uint32_t length = 0;
while ((length < max_length) && (*buf1 == *buf2)) {
buf1++, buf2++, length++;
}
return length;
}
/**
*
* This function will find the longest string in the original file that
* matches a string in the new file.
*/
void Patchfile::
find_longest_match(uint32_t new_pos, uint32_t ©_pos, uint16_t ©_length,
uint32_t *hash_table, uint32_t *link_table, const char* buffer_orig,
uint32_t length_orig, const char* buffer_new, uint32_t length_new) {
// set length to a safe value
copy_length = 0;
// get offset of matching string (in orig file) from hash table
uint32_t hash_value = calc_hash(&buffer_new[new_pos]);
// if no match, bail
if (_NULL_VALUE == hash_table[hash_value])
return;
copy_pos = hash_table[hash_value];
// calc match length
copy_length = (uint16_t)calc_match_length(&buffer_new[new_pos],
&buffer_orig[copy_pos],
min(min((length_new - new_pos),
(length_orig - copy_pos)),
_MAX_RUN_LENGTH),
0);
// run through link table, see if we find any longer matches
uint32_t match_offset;
uint16_t match_length;
match_offset = link_table[copy_pos];
while (match_offset != _NULL_VALUE) {
match_length = (uint16_t)calc_match_length(&buffer_new[new_pos],
&buffer_orig[match_offset],
min(min((length_new - new_pos),
(length_orig - match_offset)),
_MAX_RUN_LENGTH),
copy_length);
// have we found a longer match?
if (match_length > copy_length) {
copy_pos = match_offset;
copy_length = match_length;
}
// traverse the link table
match_offset = link_table[match_offset];
}
}
/**
*
*/
void Patchfile::
emit_ADD(ostream &write_stream, uint32_t length, const char* buffer) {
nassertv(length == (uint16_t)length); //we only write a uint16
if (express_cat.is_spam()) {
express_cat.spam()
<< "ADD: " << length << " (to " << _add_pos << ")" << endl;
}
// write ADD length
StreamWriter patch_writer(write_stream);
patch_writer.add_uint16((uint16_t)length);
// if there are bytes to add, add them
if (length > 0) {
patch_writer.append_data(buffer, (uint16_t)length);
}
_add_pos += length;
}
/**
*
*/
void Patchfile::
emit_COPY(ostream &write_stream, uint32_t length, uint32_t copy_pos) {
nassertv(length == (uint16_t)length); //we only write a uint16
int32_t offset = (int)copy_pos - (int)_last_copy_pos;
if (express_cat.is_spam()) {
express_cat.spam()
<< "COPY: " << length << " bytes from offset " << offset
<< " (from " << copy_pos << " to " << _add_pos << ")" << endl;
}
// write COPY length
StreamWriter patch_writer(write_stream);
patch_writer.add_uint16((uint16_t)length);
if ((uint16_t)length != 0) {
// write COPY offset
patch_writer.add_int32(offset);
_last_copy_pos = copy_pos + length;
}
_add_pos += length;
}
/**
* Emits an add/copy pair. If necessary, repeats the pair as needed to work
* around the 16-bit chunk size limit.
*/
void Patchfile::
emit_add_and_copy(ostream &write_stream,
uint32_t add_length, const char *add_buffer,
uint32_t copy_length, uint32_t copy_pos) {
if (add_length == 0 && copy_length == 0) {
// Don't accidentally emit a termination code.
return;
}
static const uint16_t max_write = 65535;
while (add_length > max_write) {
// Overflow. This chunk is too large to fit into a single ADD block, so
// we have to write it as multiple ADDs.
emit_ADD(write_stream, max_write, add_buffer);
add_buffer += max_write;
add_length -= max_write;
emit_COPY(write_stream, 0, 0);
}
emit_ADD(write_stream, add_length, add_buffer);
while (copy_length > max_write) {
// Overflow.
emit_COPY(write_stream, max_write, copy_pos);
copy_pos += max_write;
copy_length -= max_write;
emit_ADD(write_stream, 0, nullptr);
}
emit_COPY(write_stream, copy_length, copy_pos);
}
/**
* Potentially emits one or more add/copy pairs. The current state is saved,
* so as to minimize wasted emits from consecutive adds or copies.
*/
void Patchfile::
cache_add_and_copy(ostream &write_stream,
uint32_t add_length, const char *add_buffer,
uint32_t copy_length, uint32_t copy_pos) {
if (add_length != 0) {
if (_cache_copy_length != 0) {
// Have to flush.
cache_flush(write_stream);
}
// Add the string to the current cache.
_cache_add_data += string(add_buffer, add_length);
}
if (copy_length != 0) {
if (_cache_copy_length == 0) {
// Start a new copy phase.
_cache_copy_start = copy_pos;
_cache_copy_length = copy_length;
} else if (_cache_copy_start + _cache_copy_length == copy_pos) {
// We can just tack on the copy to what we've already got.
_cache_copy_length += copy_length;
} else {
// It's a discontinuous copy. We have to flush.
cache_flush(write_stream);
_cache_copy_start = copy_pos;
_cache_copy_length = copy_length;
}
}
}
/**
* Closes any copy or add phases that are still open after a previous call to
* cache_add_and_copy().
*/
void Patchfile::
cache_flush(ostream &write_stream) {
emit_add_and_copy(write_stream,
_cache_add_data.size(), _cache_add_data.data(),
_cache_copy_length, _cache_copy_start);
_cache_add_data = string();
_cache_copy_length = 0;
}
/**
*
* Writes the patchfile header.
*/
void Patchfile::
write_header(ostream &write_stream,
istream &stream_orig, istream &stream_new) {
// prepare to write the patch file header
// write the patch file header
StreamWriter patch_writer(write_stream);
patch_writer.add_uint32(_magic_number);
patch_writer.add_uint16(_current_version);
stream_orig.seekg(0, ios::end);
streampos source_file_length = stream_orig.tellg();
patch_writer.add_uint32((uint32_t)source_file_length);
// calc MD5 of original file
_MD5_ofSource.hash_stream(stream_orig);
// add it to the header
_MD5_ofSource.write_stream(patch_writer);
if (express_cat.is_debug()) {
express_cat.debug()
<< "Orig: " << _MD5_ofSource << "\n";
}
stream_new.seekg(0, ios::end);
streampos result_file_length = stream_new.tellg();
patch_writer.add_uint32((uint32_t)result_file_length);
// calc MD5 of resultant patched file
_MD5_ofResult.hash_stream(stream_new);
// add it to the header
_MD5_ofResult.write_stream(patch_writer);
if (express_cat.is_debug()) {
express_cat.debug()
<< " New: " << _MD5_ofResult << "\n";
}
}
/**
* Writes the patchfile terminator.
*/
void Patchfile::
write_terminator(ostream &write_stream) {
cache_flush(write_stream);
// write terminator (null ADD, null COPY)
emit_ADD(write_stream, 0, nullptr);
emit_COPY(write_stream, 0, 0);
}
/**
* Computes the patches for the entire file (if it is not a multifile) or for
* a single subfile (if it is)
*
* Returns true if successful, false on error.
*/
bool Patchfile::
compute_file_patches(ostream &write_stream,
uint32_t offset_orig, uint32_t offset_new,
istream &stream_orig, istream &stream_new) {
// read in original file
stream_orig.seekg(0, ios::end);
nassertr(stream_orig, false);
uint32_t source_file_length = stream_orig.tellg();
if (express_cat.is_debug()) {
express_cat.debug()
<< "Allocating " << source_file_length << " bytes to read orig\n";
}
char *buffer_orig = (char *)PANDA_MALLOC_ARRAY(source_file_length);
stream_orig.seekg(0, ios::beg);
stream_orig.read(buffer_orig, source_file_length);
// read in new file
stream_new.seekg(0, ios::end);
uint32_t result_file_length = stream_new.tellg();
nassertr(stream_new, false);
if (express_cat.is_debug()) {
express_cat.debug()
<< "Allocating " << result_file_length << " bytes to read new\n";
}
char *buffer_new = (char *)PANDA_MALLOC_ARRAY(result_file_length);
stream_new.seekg(0, ios::beg);
stream_new.read(buffer_new, result_file_length);
// allocate hashlink tables
if (_hash_table == nullptr) {
if (express_cat.is_debug()) {
express_cat.debug()
<< "Allocating hashtable of size " << _HASHTABLESIZE << " * 4\n";
}
_hash_table = (uint32_t *)PANDA_MALLOC_ARRAY(_HASHTABLESIZE * sizeof(uint32_t));
}
if (express_cat.is_debug()) {
express_cat.debug()