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
1678 lines (1454 loc) · 56 KB
/
patchfile.cxx
File metadata and controls
1678 lines (1454 loc) · 56 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
// Filename: patchfile.cxx
// Created by: darren, mike (09Jan97)
//
////////////////////////////////////////////////////////////////////
//
// 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."
//
////////////////////////////////////////////////////////////////////
#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
#ifdef HAVE_TAR
#include "libtar.h"
#include <fcntl.h> // for O_RDONLY
#endif // HAVE_TAR
#ifdef HAVE_TAR
istream *Patchfile::_tar_istream = NULL;
#endif // HAVE_TAR
////////////////////////////////////////////////////////////////////
// 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;
//
// [ ADD/COPY 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 PN_uint32 Patchfile::_v0_magic_number = 0xfeebfaab;
const PN_uint32 Patchfile::_magic_number = 0xfeebfaac;
// Created version 1 on 11/2/02 to store length and MD5 of original file.
// To version 2 on 11/2/02 to store copy offsets as relative.
const PN_uint16 Patchfile::_current_version = 2;
const PN_uint32 Patchfile::_HASH_BITS = 24;
const PN_uint32 Patchfile::_HASHTABLESIZE = PN_uint32(1) << Patchfile::_HASH_BITS;
const PN_uint32 Patchfile::_DEFAULT_FOOTPRINT_LENGTH = 9; // this produced the smallest patch file for libpanda.dll when tested, 12/20/2000
const PN_uint32 Patchfile::_NULL_VALUE = PN_uint32(0) - 1;
const PN_uint32 Patchfile::_MAX_RUN_LENGTH = (PN_uint32(1) << 16) - 1;
const PN_uint32 Patchfile::_HASH_MASK = (PN_uint32(1) << Patchfile::_HASH_BITS) - 1;
////////////////////////////////////////////////////////////////////
// Function: Patchfile::Constructor
// Access: Public
// Description: Create a patch file and initializes internal data
////////////////////////////////////////////////////////////////////
Patchfile::
Patchfile() {
PT(Buffer) buffer = new Buffer(patchfile_buffer_size);
init(buffer);
}
////////////////////////////////////////////////////////////////////
// Function: Patchfile::Constructor
// Access: Public
// Description: Create patch file with buffer to patch
////////////////////////////////////////////////////////////////////
Patchfile::
Patchfile(PT(Buffer) buffer) {
init(buffer);
}
////////////////////////////////////////////////////////////////////
// Function: Patchfile::init
// Access: Private
// Description:
////////////////////////////////////////////////////////////////////
void Patchfile::
init(PT(Buffer) buffer) {
_rename_output_to_orig = false;
_delete_patchfile = false;
_hash_table = NULL;
_initiated = false;
nassertv(!buffer.is_null());
_buffer = buffer;
_version_number = 0;
_allow_multifile = true;
_patch_stream = NULL;
_origfile_stream = NULL;
reset_footprint_length();
}
////////////////////////////////////////////////////////////////////
// Function: Patchfile::Destructor
// Access: Public
// Description:
////////////////////////////////////////////////////////////////////
Patchfile::
~Patchfile() {
if (_hash_table != (PN_uint32 *)NULL) {
PANDA_FREE_ARRAY(_hash_table);
}
if (_initiated) {
cleanup();
}
nassertv(_patch_stream == NULL);
nassertv(_origfile_stream == NULL);
}
////////////////////////////////////////////////////////////////////
// Function: Patchfile::cleanup
// Access: Private
// Description: 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 != NULL) {
vfs->close_read_file(_origfile_stream);
_origfile_stream = NULL;
}
if (_patch_stream != NULL) {
vfs->close_read_file(_patch_stream);
_patch_stream = NULL;
}
_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)
////////////////////
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
// Function: Patchfile::initiate
// Access: Published
// Description: 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;
}
////////////////////////////////////////////////////////////////////
// Function: Patchfile::initiate
// Access: Published
// Description: 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 == NULL, EU_error_abort);
_orig_file = orig_file;
_orig_file.set_binary();
_origfile_stream = vfs->open_read_file(_orig_file, false);
if (_origfile_stream == NULL) {
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;
}
////////////////////////////////////////////////////////////////////
// Function: Patchfile::read_header
// Access: Published
// Description: 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 != NULL) {
VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr();
vfs->close_read_file(_patch_stream);
_patch_stream = NULL;
}
return result;
}
////////////////////////////////////////////////////////////////////
// Function: Patchfile::run
// Access: Published
// Description: 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;
PN_uint16 ADD_length;
PN_uint16 COPY_length;
PN_int32 COPY_offset;
if (_initiated == false) {
express_cat.error()
<< "Patchfile::run() - Patching has not been initiated"
<< endl;
return EU_error_abort;
}
nassertr(_patch_stream != NULL, EU_error_abort);
nassertr(_origfile_stream != NULL, 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;
}
PN_uint32 bytes_left = (PN_uint32)ADD_length;
while (bytes_left > 0) {
PN_uint32 bytes_this_time = (PN_uint32) min(bytes_left, (PN_uint32) 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
PN_uint32 bytes_left = (PN_uint32)COPY_length;
while (bytes_left > 0) {
PN_uint32 bytes_this_time = (PN_uint32) min(bytes_left, (PN_uint32) 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 != NULL) {
VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr();
vfs->close_read_file(_origfile_stream);
_origfile_stream = NULL;
}
_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;
}
////////////////////////////////////////////////////////////////////
// Function: Patchfile::apply
// Access: Public
// Description: 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;
}
////////////////////////////////////////////////////////////////////
// Function: Patchfile::apply
// Access: Public
// Description: 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;
}
////////////////////////////////////////////////////////////////////
// Function: Patchfile::internal_read_header
// Access: Private
// Description: 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 == NULL, EU_error_abort);
_patch_file = patch_file;
_patch_file.set_binary();
_patch_stream = vfs->open_read_file(_patch_file, true);
if (_patch_stream == NULL) {
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);
PN_uint32 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.
/*PN_uint32 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);
express_cat.debug()
<< "Patchfile::initiate() - valid patchfile" << endl;
return EU_success;
}
////////////////////////////////////////////////////////////////////
///// PATCH FILE BUILDING MEMBER FUNCTIONS
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
// Function: Patchfile::calc_hash
// Access: Private
// Description:
////////////////////////////////////////////////////////////////////
PN_uint32 Patchfile::
calc_hash(const char *buffer) {
#ifdef USE_MD5_FOR_HASHTABLE_INDEX_VALUES
HashVal hash;
hash.hash_buffer(buffer, _footprint_length);
//cout << PN_uint16(hash.get_value(0)) << " ";
return PN_uint16(hash.get_value(0));
#else
PN_uint32 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 ^= PN_uint32(*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
}
////////////////////////////////////////////////////////////////////
// Function: Patchfile::build_hash_link_tables
// Access: Private
// Description:
// 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, PN_uint32 length_orig,
PN_uint32 *hash_table, PN_uint32 *link_table) {
PN_uint32 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++) {
PN_uint32 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
PN_uint32 link_offset = hash_table[hash_value];
while (_NULL_VALUE != link_table[link_offset]) {
link_offset = link_table[link_offset];
}
link_table[link_offset] = i;
}
*/
}
}
////////////////////////////////////////////////////////////////////
// Function: Patchfile::calc_match_length
// Access: Private
// Description:
// This function calculates the length of a match between
// two strings of bytes
////////////////////////////////////////////////////////////////////
PN_uint32 Patchfile::
calc_match_length(const char* buf1, const char* buf2, PN_uint32 max_length,
PN_uint32 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;
}
}
PN_uint32 length = 0;
while ((length < max_length) && (*buf1 == *buf2)) {
buf1++, buf2++, length++;
}
return length;
}
////////////////////////////////////////////////////////////////////
// Function: Patchfile::find_longest_match
// Access: Private
// Description:
// This function will find the longest string in the
// original file that matches a string in the new file.
////////////////////////////////////////////////////////////////////
void Patchfile::
find_longest_match(PN_uint32 new_pos, PN_uint32 ©_pos, PN_uint16 ©_length,
PN_uint32 *hash_table, PN_uint32 *link_table, const char* buffer_orig,
PN_uint32 length_orig, const char* buffer_new, PN_uint32 length_new) {
// set length to a safe value
copy_length = 0;
// get offset of matching string (in orig file) from hash table
PN_uint32 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 = (PN_uint16)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
PN_uint32 match_offset;
PN_uint16 match_length;
match_offset = link_table[copy_pos];
while (match_offset != _NULL_VALUE) {
match_length = (PN_uint16)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];
}
}
////////////////////////////////////////////////////////////////////
// Function: Patchfile::emit_ADD
// Access: Private
// Description:
////////////////////////////////////////////////////////////////////
void Patchfile::
emit_ADD(ostream &write_stream, PN_uint32 length, const char* buffer) {
nassertv(length == (PN_uint16)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((PN_uint16)length);
// if there are bytes to add, add them
if (length > 0) {
patch_writer.append_data(buffer, (PN_uint16)length);
}
_add_pos += length;
}
////////////////////////////////////////////////////////////////////
// Function: Patchfile::emit_COPY
// Access: Private
// Description:
////////////////////////////////////////////////////////////////////
void Patchfile::
emit_COPY(ostream &write_stream, PN_uint32 length, PN_uint32 copy_pos) {
nassertv(length == (PN_uint16)length); //we only write a uint16
PN_int32 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((PN_uint16)length);
if ((PN_uint16)length != 0) {
// write COPY offset
patch_writer.add_int32(offset);
_last_copy_pos = copy_pos + length;
}
_add_pos += length;
}
////////////////////////////////////////////////////////////////////
// Function: Patchfile::emit_add_and_copy
// Access: Private
// Description: 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,
PN_uint32 add_length, const char *add_buffer,
PN_uint32 copy_length, PN_uint32 copy_pos) {
if (add_length == 0 && copy_length == 0) {
// Don't accidentally emit a termination code.
return;
}
static const PN_uint16 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, NULL);
}
emit_COPY(write_stream, copy_length, copy_pos);
}
////////////////////////////////////////////////////////////////////
// Function: Patchfile::cache_add_and_copy
// Access: Private
// Description: 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,
PN_uint32 add_length, const char *add_buffer,
PN_uint32 copy_length, PN_uint32 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;
}
}
}
////////////////////////////////////////////////////////////////////
// Function: Patchfile::cache_flush
// Access: Private
// Description: 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;
}
////////////////////////////////////////////////////////////////////
// Function: Patchfile::write_header
// Access: Private
// Description:
// 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);