VeraCrypt
aboutsummaryrefslogtreecommitdiff
path: root/src/Common/libzip/zip_close.c
blob: b5eca67a463fc101f266a5c4617590fe8cd53ca1 (plain)
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
/*
  zip_close.c -- close zip archive and update changes
  Copyright (C) 1999-2015 Dieter Baron and Thomas Klausner

  This file is part of libzip, a library to manipulate ZIP archives.
  The authors can be contacted at <libzip@nih.at>

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions
  are met:
  1. Redistributions of source code must retain the above copyright
     notice, this list of conditions and the following disclaimer.
  2. Redistributions in binary form must reproduce the above copyright
     notice, this list of conditions and the following disclaimer in
     the documentation and/or other materials provided with the
     distribution.
  3. The names of the authors may not be used to endorse or promote
     products derived from this software without specific prior
     written permission.
 
  THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS
  OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
  GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
  IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
  OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
  IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/


#include "zipint.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef HAVE_STRINGS_H
#include <strings.h>
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <sys/types.h>
#include <sys/stat.h>
#ifdef _WIN32
#include <io.h>
#include <fcntl.h>
#endif


/* max deflate size increase: size + ceil(size/16k)*5+6 */
#define MAX_DEFLATE_SIZE_32	4293656963u

static int add_data(zip_t *, zip_source_t *, zip_dirent_t *);
static int copy_data(zip_t *, zip_uint64_t);
static int copy_source(zip_t *, zip_source_t *);
static int write_cdir(zip_t *, const zip_filelist_t *, zip_uint64_t);


ZIP_EXTERN int
zip_close(zip_t *za)
{
    zip_uint64_t i, j, survivors;
    zip_int64_t off;
    int error;
    zip_filelist_t *filelist;
    int changed;

    if (za == NULL)
	return -1;

    changed = _zip_changed(za, &survivors);

    /* don't create zip files with no entries */
    if (survivors == 0) {
	if ((za->open_flags & ZIP_TRUNCATE) || changed) {
	    if (zip_source_remove(za->src) < 0) {
		_zip_error_set_from_source(&za->error, za->src);
		return -1;
	    }
	}
	zip_discard(za);
	return 0;
    }	       

    if (!changed) {
	zip_discard(za);
	return 0;
    }

    if (survivors > za->nentry) {
        zip_error_set(&za->error, ZIP_ER_INTERNAL, 0);
        return -1;
    }
    
    if ((filelist=(zip_filelist_t *)malloc(sizeof(filelist[0])*(size_t)survivors)) == NULL)
	return -1;

    /* create list of files with index into original archive  */
    for (i=j=0; i<za->nentry; i++) {
	if (za->entry[i].deleted)
	    continue;

        if (j >= survivors) {
            free(filelist);
            zip_error_set(&za->error, ZIP_ER_INTERNAL, 0);
            return -1;
        }
        
	filelist[j].idx = i;
	j++;
    }
    if (j < survivors) {
        free(filelist);
        zip_error_set(&za->error, ZIP_ER_INTERNAL, 0);
        return -1;
    }

    if (zip_source_begin_write(za->src) < 0) {
	_zip_error_set_from_source(&za->error, za->src);
	free(filelist);
	return -1;
    }
    
    error = 0;
    for (j=0; j<survivors; j++) {
	int new_data;
	zip_entry_t *entry;
	zip_dirent_t *de;

	i = filelist[j].idx;
	entry = za->entry+i;

	new_data = (ZIP_ENTRY_DATA_CHANGED(entry) || ZIP_ENTRY_CHANGED(entry, ZIP_DIRENT_COMP_METHOD));

	/* create new local directory entry */
	if (entry->changes == NULL) {
	    if ((entry->changes=_zip_dirent_clone(entry->orig)) == NULL) {
                zip_error_set(&za->error, ZIP_ER_MEMORY, 0);
                error = 1;
                break;
	    }
	}
	de = entry->changes;

	if (_zip_read_local_ef(za, i) < 0) {
	    error = 1;
	    break;
	}

        if ((off = zip_source_tell_write(za->src)) < 0) {
            error = 1;
            break;
        }
        de->offset = (zip_uint64_t)off;

	if (new_data) {
	    zip_source_t *zs;

	    zs = NULL;
	    if (!ZIP_ENTRY_DATA_CHANGED(entry)) {
		if ((zs=_zip_source_zip_new(za, za, i, ZIP_FL_UNCHANGED, 0, 0, NULL)) == NULL) {
		    error = 1;
		    break;
		}
	    }

	    /* add_data writes dirent */
	    if (add_data(za, zs ? zs : entry->source, de) < 0) {
		error = 1;
		if (zs)
		    zip_source_free(zs);
		break;
	    }
	    if (zs)
		zip_source_free(zs);
	}
	else {
	    zip_uint64_t offset;

	    /* when copying data, all sizes are known -> no data descriptor needed */
	    de->bitflags &= (zip_uint16_t)~ZIP_GPBF_DATA_DESCRIPTOR;
	    if (_zip_dirent_write(za, de, ZIP_FL_LOCAL) < 0) {
		error = 1;
		break;
	    }
	    if ((offset=_zip_file_get_offset(za, i, &za->error)) == 0) {
		error = 1;
		break;
	    }
	    if (zip_source_seek(za->src, (zip_int64_t)offset, SEEK_SET) < 0) {
		_zip_error_set_from_source(&za->error, za->src);
		error = 1;
		break;
	    }
	    if (copy_data(za, de->comp_size) < 0) {
		error = 1;
		break;
	    }
	}
    }

    if (!error) {
	if (write_cdir(za, filelist, survivors) < 0)
	    error = 1;
    }

    free(filelist);

    if (!error) {
	if (zip_source_commit_write(za->src) != 0) {
	    _zip_error_set_from_source(&za->error, za->src);
	    error = 1;
	}
    }

    if (error) {
	zip_source_rollback_write(za->src);
	return -1;
    }

    zip_discard(za);
    
    return 0;
}


static int
add_data(zip_t *za, zip_source_t *src, zip_dirent_t *de)
{
    zip_int64_t offstart, offdata, offend;
    struct zip_stat st;
    zip_source_t *s2;
    int ret;
    int is_zip64;
    zip_flags_t flags;
    
    if (zip_source_stat(src, &st) < 0) {
	_zip_error_set_from_source(&za->error, src);
	return -1;
    }

    if ((st.valid & ZIP_STAT_COMP_METHOD) == 0) {
	st.valid |= ZIP_STAT_COMP_METHOD;
	st.comp_method = ZIP_CM_STORE;
    }

    if (ZIP_CM_IS_DEFAULT(de->comp_method) && st.comp_method != ZIP_CM_STORE)
	de->comp_method = st.comp_method;
    else if (de->comp_method == ZIP_CM_STORE && (st.valid & ZIP_STAT_SIZE)) {
	st.valid |= ZIP_STAT_COMP_SIZE;
	st.comp_size = st.size;
    }
    else {
	/* we'll recompress */
	st.valid &= ~ZIP_STAT_COMP_SIZE;
    }


    flags = ZIP_EF_LOCAL;

    if ((st.valid & ZIP_STAT_SIZE) == 0)
	flags |= ZIP_FL_FORCE_ZIP64;
    else {
	de->uncomp_size = st.size;
	
	if ((st.valid & ZIP_STAT_COMP_SIZE) == 0) {
	    if (( ((de->comp_method == ZIP_CM_DEFLATE || ZIP_CM_IS_DEFAULT(de->comp_method)) && st.size > MAX_DEFLATE_SIZE_32)
		  || (de->comp_method != ZIP_CM_STORE && de->comp_method != ZIP_CM_DEFLATE && !ZIP_CM_IS_DEFAULT(de->comp_method))))
		flags |= ZIP_FL_FORCE_ZIP64;
	}
	else
	    de->comp_size = st.comp_size;
    }

    if ((offstart = zip_source_tell_write(za->src)) < 0) {
        return -1;
    }

    /* as long as we don't support non-seekable output, clear data descriptor bit */
    de->bitflags &= (zip_uint16_t)~ZIP_GPBF_DATA_DESCRIPTOR;
    if ((is_zip64=_zip_dirent_write(za, de, flags)) < 0)
	return -1;


    if (st.comp_method == ZIP_CM_STORE || (ZIP_CM_IS_DEFAULT(de->comp_method) && st.comp_method != de->comp_method)) {
	zip_source_t *s_store, *s_crc;
	zip_compression_implementation comp_impl;
	
	if (st.comp_method != ZIP_CM_STORE) {
	    if ((comp_impl=_zip_get_compression_implementation(st.comp_method)) == NULL) {
		zip_error_set(&za->error, ZIP_ER_COMPNOTSUPP, 0);
		return -1;
	    }
	    if ((s_store=comp_impl(za, src, st.comp_method, ZIP_CODEC_DECODE)) == NULL) {
		/* error set by comp_impl */
		return -1;
	    }
	}
	else {
	    /* to have the same reference count to src as in the case where it's not stored */
	    zip_source_keep(src);
	    s_store = src;
	}

	s_crc = zip_source_crc(za, s_store, 0);
	zip_source_free(s_store);
	if (s_crc == NULL) {
	    return -1;
	}

	if (de->comp_method != ZIP_CM_STORE && ((st.valid & ZIP_STAT_SIZE) == 0 || st.size != 0)) {
	    if ((comp_impl=_zip_get_compression_implementation(de->comp_method)) == NULL) {
		zip_error_set(&za->error, ZIP_ER_COMPNOTSUPP, 0);
		zip_source_free(s_crc);
		return -1;
	    }
	    s2 = comp_impl(za, s_crc, de->comp_method, ZIP_CODEC_ENCODE);
	    zip_source_free(s_crc);
	    if (s2 == NULL) {
		return -1;
	    }
	}
	else {
	    s2 = s_crc;
	}
    }
    else {
	zip_source_keep(src);
	s2 = src;
    }

    if ((offdata = zip_source_tell_write(za->src)) < 0) {
        return -1;
    }

    ret = copy_source(za, s2);
	
    if (zip_source_stat(s2, &st) < 0)
	ret = -1;

    zip_source_free(s2);

    if (ret < 0)
	return -1;

    if ((offend = zip_source_tell_write(za->src)) < 0) {
        return -1;
    }

    if (zip_source_seek_write(za->src, offstart, SEEK_SET) < 0) {
	_zip_error_set_from_source(&za->error, za->src);
	return -1;
    }

    if ((st.valid & (ZIP_STAT_COMP_METHOD|ZIP_STAT_CRC|ZIP_STAT_SIZE)) != (ZIP_STAT_COMP_METHOD|ZIP_STAT_CRC|ZIP_STAT_SIZE)) {
	zip_error_set(&za->error, ZIP_ER_INTERNAL, 0);
	return -1;
    }

    if ((de->changed & ZIP_DIRENT_LAST_MOD) == 0) {
        if (st.valid & ZIP_STAT_MTIME)
            de->last_mod = st.mtime;
        else
            time(&de->last_mod);
    }
    de->comp_method = st.comp_method;
    de->crc = st.crc;
    de->uncomp_size = st.size;
    de->comp_size = (zip_uint64_t)(offend - offdata);

    if ((ret=_zip_dirent_write(za, de, flags)) < 0)
	return -1;
 
    if (is_zip64 != ret) {
	/* Zip64 mismatch between preliminary file header written before data and final file header written afterwards */
	zip_error_set(&za->error, ZIP_ER_INTERNAL, 0);
	return -1;
    }

   
    if (zip_source_seek_write(za->src, offend, SEEK_SET) < 0) {
	_zip_error_set_from_source(&za->error, za->src);
	return -1;
    }

    return 0;
}


static int
copy_data(zip_t *za, zip_uint64_t len)
{
    zip_uint8_t buf[BUFSIZE];
    size_t n;

    while (len > 0) {
	n = len > sizeof(buf) ? sizeof(buf) : len;
	if (_zip_read(za->src, buf, n, &za->error) < 0) {
	    return -1;
	}

	if (_zip_write(za, buf, n) < 0) {
	    return -1;
	}
	
	len -= n;
    }

    return 0;
}


static int
copy_source(zip_t *za, zip_source_t *src)
{
    zip_uint8_t buf[BUFSIZE];
    zip_int64_t n;
    int ret;

    if (zip_source_open(src) < 0) {
	_zip_error_set_from_source(&za->error, src);
	return -1;
    }

    ret = 0;
    while ((n=zip_source_read(src, buf, sizeof(buf))) > 0) {
	if (_zip_write(za, buf, (zip_uint64_t)n) < 0) {
	    ret = -1;
	    break;
	}
    }
    
    if (n < 0) {
	_zip_error_set_from_source(&za->error, src);
	ret = -1;
    }

    zip_source_close(src);
    
    return ret;
}


static int
write_cdir(zip_t *za, const zip_filelist_t *filelist, zip_uint64_t survivors)
{
    zip_int64_t cd_start, end, size;
    
    if ((cd_start = zip_source_tell_write(za->src)) < 0) {
        return -1;
    }

    if ((size=_zip_cdir_write(za, filelist, survivors)) < 0) {
	return -1;
    }
    
    if ((end = zip_source_tell_write(za->src)) < 0) {
        return -1;
    }

    return 0;
}


int
_zip_changed(const zip_t *za, zip_uint64_t *survivorsp)
{
    int changed;
    zip_uint64_t i, survivors;

    changed = 0;
    survivors = 0;

    if (za->comment_changed || za->ch_flags != za->flags)
	changed = 1;

    for (i=0; i<za->nentry; i++) {
	if (za->entry[i].deleted || za->entry[i].source || (za->entry[i].changes && za->entry[i].changes->changed != 0))
	    changed = 1;
	if (!za->entry[i].deleted)
	    survivors++;
    }

    if (survivorsp)
	*survivorsp = survivors;

    return changed;
}
/span> if (p->streamEndWasReached || p->result != SZ_OK) return 0; return ((size_t)(p->bufBase + p->blockSize - p->buffer) <= p->keepSizeAfter); } void MatchFinder_ReadIfRequired(CMatchFinder *p) { if (p->keepSizeAfter >= GET_AVAIL_BYTES(p)) MatchFinder_ReadBlock(p); } static void MatchFinder_SetDefaultSettings(CMatchFinder *p) { p->cutValue = 32; p->btMode = 1; p->numHashBytes = 4; p->numHashBytes_Min = 2; p->numHashOutBits = 0; p->bigHash = 0; } #define kCrcPoly 0xEDB88320 void MatchFinder_Construct(CMatchFinder *p) { unsigned i; p->buffer = NULL; p->bufBase = NULL; p->directInput = 0; p->stream = NULL; p->hash = NULL; p->expectedDataSize = (UInt64)(Int64)-1; MatchFinder_SetDefaultSettings(p); for (i = 0; i < 256; i++) { UInt32 r = (UInt32)i; unsigned j; for (j = 0; j < 8; j++) r = (r >> 1) ^ (kCrcPoly & ((UInt32)0 - (r & 1))); p->crc[i] = r; } } #undef kCrcPoly static void MatchFinder_FreeThisClassMemory(CMatchFinder *p, ISzAllocPtr alloc) { ISzAlloc_Free(alloc, p->hash); p->hash = NULL; } void MatchFinder_Free(CMatchFinder *p, ISzAllocPtr alloc) { MatchFinder_FreeThisClassMemory(p, alloc); LzInWindow_Free(p, alloc); } static CLzRef* AllocRefs(size_t num, ISzAllocPtr alloc) { const size_t sizeInBytes = (size_t)num * sizeof(CLzRef); if (sizeInBytes / sizeof(CLzRef) != num) return NULL; return (CLzRef *)ISzAlloc_Alloc(alloc, sizeInBytes); } #if (kBlockSizeReserveMin < kBlockSizeAlign * 2) #error Stop_Compiling_Bad_Reserve #endif static UInt32 GetBlockSize(CMatchFinder *p, UInt32 historySize) { UInt32 blockSize = (p->keepSizeBefore + p->keepSizeAfter); /* if (historySize > kMaxHistorySize) return 0; */ // printf("\nhistorySize == 0x%x\n", historySize); if (p->keepSizeBefore < historySize || blockSize < p->keepSizeBefore) // if 32-bit overflow return 0; { const UInt32 kBlockSizeMax = (UInt32)0 - (UInt32)kBlockSizeAlign; const UInt32 rem = kBlockSizeMax - blockSize; const UInt32 reserve = (blockSize >> (blockSize < ((UInt32)1 << 30) ? 1 : 2)) + (1 << 12) + kBlockMoveAlign + kBlockSizeAlign; // do not overflow 32-bit here if (blockSize >= kBlockSizeMax || rem < kBlockSizeReserveMin) // we reject settings that will be slow return 0; if (reserve >= rem) blockSize = kBlockSizeMax; else { blockSize += reserve; blockSize &= ~(UInt32)(kBlockSizeAlign - 1); } } // printf("\n LzFind_blockSize = %x\n", blockSize); // printf("\n LzFind_blockSize = %d\n", blockSize >> 20); return blockSize; } // input is historySize static UInt32 MatchFinder_GetHashMask2(CMatchFinder *p, UInt32 hs) { if (p->numHashBytes == 2) return (1 << 16) - 1; if (hs != 0) hs--; hs |= (hs >> 1); hs |= (hs >> 2); hs |= (hs >> 4); hs |= (hs >> 8); // we propagated 16 bits in (hs). Low 16 bits must be set later if (hs >= (1 << 24)) { if (p->numHashBytes == 3) hs = (1 << 24) - 1; /* if (bigHash) mode, GetHeads4b() in LzFindMt.c needs (hs >= ((1 << 24) - 1))) */ } // (hash_size >= (1 << 16)) : Required for (numHashBytes > 2) hs |= (1 << 16) - 1; /* don't change it! */ // bt5: we adjust the size with recommended minimum size if (p->numHashBytes >= 5) hs |= (256 << kLzHash_CrcShift_2) - 1; return hs; } // input is historySize static UInt32 MatchFinder_GetHashMask(CMatchFinder *p, UInt32 hs) { if (p->numHashBytes == 2) return (1 << 16) - 1; if (hs != 0) hs--; hs |= (hs >> 1); hs |= (hs >> 2); hs |= (hs >> 4); hs |= (hs >> 8); // we propagated 16 bits in (hs). Low 16 bits must be set later hs >>= 1; if (hs >= (1 << 24)) { if (p->numHashBytes == 3) hs = (1 << 24) - 1; else hs >>= 1; /* if (bigHash) mode, GetHeads4b() in LzFindMt.c needs (hs >= ((1 << 24) - 1))) */ } // (hash_size >= (1 << 16)) : Required for (numHashBytes > 2) hs |= (1 << 16) - 1; /* don't change it! */ // bt5: we adjust the size with recommended minimum size if (p->numHashBytes >= 5) hs |= (256 << kLzHash_CrcShift_2) - 1; return hs; } int MatchFinder_Create(CMatchFinder *p, UInt32 historySize, UInt32 keepAddBufferBefore, UInt32 matchMaxLen, UInt32 keepAddBufferAfter, ISzAllocPtr alloc) { /* we need one additional byte in (p->keepSizeBefore), since we use MoveBlock() after (p->pos++) and before dictionary using */ // keepAddBufferBefore = (UInt32)0xFFFFFFFF - (1 << 22); // for debug p->keepSizeBefore = historySize + keepAddBufferBefore + 1; keepAddBufferAfter += matchMaxLen; /* we need (p->keepSizeAfter >= p->numHashBytes) */ if (keepAddBufferAfter < p->numHashBytes) keepAddBufferAfter = p->numHashBytes; // keepAddBufferAfter -= 2; // for debug p->keepSizeAfter = keepAddBufferAfter; if (p->directInput) p->blockSize = 0; if (p->directInput || LzInWindow_Create2(p, GetBlockSize(p, historySize), alloc)) { size_t hashSizeSum; { UInt32 hs; UInt32 hsCur; if (p->numHashOutBits != 0) { unsigned numBits = p->numHashOutBits; const unsigned nbMax = (p->numHashBytes == 2 ? 16 : (p->numHashBytes == 3 ? 24 : 32)); if (numBits > nbMax) numBits = nbMax; if (numBits >= 32) hs = (UInt32)0 - 1; else hs = ((UInt32)1 << numBits) - 1; // (hash_size >= (1 << 16)) : Required for (numHashBytes > 2) hs |= (1 << 16) - 1; /* don't change it! */ if (p->numHashBytes >= 5) hs |= (256 << kLzHash_CrcShift_2) - 1; { const UInt32 hs2 = MatchFinder_GetHashMask2(p, historySize); if (hs > hs2) hs = hs2; } hsCur = hs; if (p->expectedDataSize < historySize) { const UInt32 hs2 = MatchFinder_GetHashMask2(p, (UInt32)p->expectedDataSize); if (hsCur > hs2) hsCur = hs2; } } else { hs = MatchFinder_GetHashMask(p, historySize); hsCur = hs; if (p->expectedDataSize < historySize) { hsCur = MatchFinder_GetHashMask(p, (UInt32)p->expectedDataSize); if (hsCur > hs) // is it possible? hsCur = hs; } } p->hashMask = hsCur; hashSizeSum = hs; hashSizeSum++; if (hashSizeSum < hs) return 0; { UInt32 fixedHashSize = 0; if (p->numHashBytes > 2 && p->numHashBytes_Min <= 2) fixedHashSize += kHash2Size; if (p->numHashBytes > 3 && p->numHashBytes_Min <= 3) fixedHashSize += kHash3Size; // if (p->numHashBytes > 4) p->fixedHashSize += hs4; // kHash4Size; hashSizeSum += fixedHashSize; p->fixedHashSize = fixedHashSize; } } p->matchMaxLen = matchMaxLen; { size_t newSize; size_t numSons; const UInt32 newCyclicBufferSize = historySize + 1; // do not change it p->historySize = historySize; p->cyclicBufferSize = newCyclicBufferSize; // it must be = (historySize + 1) numSons = newCyclicBufferSize; if (p->btMode) numSons <<= 1; newSize = hashSizeSum + numSons; if (numSons < newCyclicBufferSize || newSize < numSons) return 0; // aligned size is not required here, but it can be better for some loops #define NUM_REFS_ALIGN_MASK 0xF newSize = (newSize + NUM_REFS_ALIGN_MASK) & ~(size_t)NUM_REFS_ALIGN_MASK; // 22.02: we don't reallocate buffer, if old size is enough if (p->hash && p->numRefs >= newSize) return 1; MatchFinder_FreeThisClassMemory(p, alloc); p->numRefs = newSize; p->hash = AllocRefs(newSize, alloc); if (p->hash) { p->son = p->hash + hashSizeSum; return 1; } } } MatchFinder_Free(p, alloc); return 0; } static void MatchFinder_SetLimits(CMatchFinder *p) { UInt32 k; UInt32 n = kMaxValForNormalize - p->pos; if (n == 0) n = (UInt32)(Int32)-1; // we allow (pos == 0) at start even with (kMaxValForNormalize == 0) k = p->cyclicBufferSize - p->cyclicBufferPos; if (k < n) n = k; k = GET_AVAIL_BYTES(p); { const UInt32 ksa = p->keepSizeAfter; UInt32 mm = p->matchMaxLen; if (k > ksa) k -= ksa; // we must limit exactly to keepSizeAfter for ReadBlock else if (k >= mm) { // the limitation for (p->lenLimit) update k -= mm; // optimization : to reduce the number of checks k++; // k = 1; // non-optimized version : for debug } else { mm = k; if (k != 0) k = 1; } p->lenLimit = mm; } if (k < n) n = k; p->posLimit = p->pos + n; } void MatchFinder_Init_LowHash(CMatchFinder *p) { size_t i; CLzRef *items = p->hash; const size_t numItems = p->fixedHashSize; for (i = 0; i < numItems; i++) items[i] = kEmptyHashValue; } void MatchFinder_Init_HighHash(CMatchFinder *p) { size_t i; CLzRef *items = p->hash + p->fixedHashSize; const size_t numItems = (size_t)p->hashMask + 1; for (i = 0; i < numItems; i++) items[i] = kEmptyHashValue; } void MatchFinder_Init_4(CMatchFinder *p) { if (!p->directInput) p->buffer = p->bufBase; { /* kEmptyHashValue = 0 (Zero) is used in hash tables as NO-VALUE marker. the code in CMatchFinderMt expects (pos = 1) */ p->pos = p->streamPos = 1; // it's smallest optimal value. do not change it // 0; // for debug } p->result = SZ_OK; p->streamEndWasReached = 0; } // (CYC_TO_POS_OFFSET == 0) is expected by some optimized code #define CYC_TO_POS_OFFSET 0 // #define CYC_TO_POS_OFFSET 1 // for debug void MatchFinder_Init(CMatchFinder *p) { MatchFinder_Init_HighHash(p); MatchFinder_Init_LowHash(p); MatchFinder_Init_4(p); // if (readData) MatchFinder_ReadBlock(p); /* if we init (cyclicBufferPos = pos), then we can use one variable instead of both (cyclicBufferPos) and (pos) : only before (cyclicBufferPos) wrapping */ p->cyclicBufferPos = (p->pos - CYC_TO_POS_OFFSET); // init with relation to (pos) // p->cyclicBufferPos = 0; // smallest value // p->son[0] = p->son[1] = 0; // unused: we can init skipped record for speculated accesses. MatchFinder_SetLimits(p); } #ifdef MY_CPU_X86_OR_AMD64 #if defined(__clang__) && (__clang_major__ >= 4) \ || defined(Z7_GCC_VERSION) && (Z7_GCC_VERSION >= 40701) // || defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 1900) #define USE_LZFIND_SATUR_SUB_128 #define USE_LZFIND_SATUR_SUB_256 #define LZFIND_ATTRIB_SSE41 __attribute__((__target__("sse4.1"))) #define LZFIND_ATTRIB_AVX2 __attribute__((__target__("avx2"))) #elif defined(_MSC_VER) #if (_MSC_VER >= 1600) #define USE_LZFIND_SATUR_SUB_128 #endif #if (_MSC_VER >= 1900) #define USE_LZFIND_SATUR_SUB_256 #endif #endif // #elif defined(MY_CPU_ARM_OR_ARM64) #elif defined(MY_CPU_ARM64) #if defined(__clang__) && (__clang_major__ >= 8) \ || defined(__GNUC__) && (__GNUC__ >= 8) #define USE_LZFIND_SATUR_SUB_128 #ifdef MY_CPU_ARM64 // #define LZFIND_ATTRIB_SSE41 __attribute__((__target__(""))) #else // #define LZFIND_ATTRIB_SSE41 __attribute__((__target__("fpu=crypto-neon-fp-armv8"))) #endif #elif defined(_MSC_VER) #if (_MSC_VER >= 1910) #define USE_LZFIND_SATUR_SUB_128 #endif #endif #if defined(_MSC_VER) && defined(MY_CPU_ARM64) #include <arm64_neon.h> #else #include <arm_neon.h> #endif #endif #ifdef USE_LZFIND_SATUR_SUB_128 // #define Z7_SHOW_HW_STATUS #ifdef Z7_SHOW_HW_STATUS #include <stdio.h> #define PRF(x) x PRF(;) #else #define PRF(x) #endif #ifdef MY_CPU_ARM_OR_ARM64 #ifdef MY_CPU_ARM64 // #define FORCE_LZFIND_SATUR_SUB_128 #endif typedef uint32x4_t LzFind_v128; #define SASUB_128_V(v, s) \ vsubq_u32(vmaxq_u32(v, s), s) #else // MY_CPU_ARM_OR_ARM64 #include <smmintrin.h> // sse4.1 typedef __m128i LzFind_v128; // SSE 4.1 #define SASUB_128_V(v, s) \ _mm_sub_epi32(_mm_max_epu32(v, s), s) #endif // MY_CPU_ARM_OR_ARM64 #define SASUB_128(i) \ *( LzFind_v128 *)( void *)(items + (i) * 4) = SASUB_128_V( \ *(const LzFind_v128 *)(const void *)(items + (i) * 4), sub2); Z7_NO_INLINE static #ifdef LZFIND_ATTRIB_SSE41 LZFIND_ATTRIB_SSE41 #endif void Z7_FASTCALL LzFind_SaturSub_128(UInt32 subValue, CLzRef *items, const CLzRef *lim) { const LzFind_v128 sub2 = #ifdef MY_CPU_ARM_OR_ARM64 vdupq_n_u32(subValue); #else _mm_set_epi32((Int32)subValue, (Int32)subValue, (Int32)subValue, (Int32)subValue); #endif Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE do { SASUB_128(0) SASUB_128(1) items += 2 * 4; SASUB_128(0) SASUB_128(1) items += 2 * 4; } while (items != lim); } #ifdef USE_LZFIND_SATUR_SUB_256 #include <immintrin.h> // avx /* clang :immintrin.h uses #if !(defined(_MSC_VER) || defined(__SCE__)) || __has_feature(modules) || \ defined(__AVX2__) #include <avx2intrin.h> #endif so we need <avxintrin.h> for clang-cl */ #if defined(__clang__) #include <avxintrin.h> #include <avx2intrin.h> #endif // AVX2: #define SASUB_256(i) \ *( __m256i *)( void *)(items + (i) * 8) = \ _mm256_sub_epi32(_mm256_max_epu32( \ *(const __m256i *)(const void *)(items + (i) * 8), sub2), sub2); Z7_NO_INLINE static #ifdef LZFIND_ATTRIB_AVX2 LZFIND_ATTRIB_AVX2 #endif void Z7_FASTCALL LzFind_SaturSub_256(UInt32 subValue, CLzRef *items, const CLzRef *lim) { const __m256i sub2 = _mm256_set_epi32( (Int32)subValue, (Int32)subValue, (Int32)subValue, (Int32)subValue, (Int32)subValue, (Int32)subValue, (Int32)subValue, (Int32)subValue); Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE do { SASUB_256(0) SASUB_256(1) items += 2 * 8; SASUB_256(0) SASUB_256(1) items += 2 * 8; } while (items != lim); } #endif // USE_LZFIND_SATUR_SUB_256 #ifndef FORCE_LZFIND_SATUR_SUB_128 typedef void (Z7_FASTCALL *LZFIND_SATUR_SUB_CODE_FUNC)( UInt32 subValue, CLzRef *items, const CLzRef *lim); static LZFIND_SATUR_SUB_CODE_FUNC g_LzFind_SaturSub; #endif // FORCE_LZFIND_SATUR_SUB_128 #endif // USE_LZFIND_SATUR_SUB_128 // kEmptyHashValue must be zero // #define SASUB_32(i) { UInt32 v = items[i]; UInt32 m = v - subValue; if (v < subValue) m = kEmptyHashValue; items[i] = m; } #define SASUB_32(i) { UInt32 v = items[i]; if (v < subValue) v = subValue; items[i] = v - subValue; } #ifdef FORCE_LZFIND_SATUR_SUB_128 #define DEFAULT_SaturSub LzFind_SaturSub_128 #else #define DEFAULT_SaturSub LzFind_SaturSub_32 Z7_NO_INLINE static void Z7_FASTCALL LzFind_SaturSub_32(UInt32 subValue, CLzRef *items, const CLzRef *lim) { Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE do { SASUB_32(0) SASUB_32(1) items += 2; SASUB_32(0) SASUB_32(1) items += 2; SASUB_32(0) SASUB_32(1) items += 2; SASUB_32(0) SASUB_32(1) items += 2; } while (items != lim); } #endif Z7_NO_INLINE void MatchFinder_Normalize3(UInt32 subValue, CLzRef *items, size_t numItems) { #define LZFIND_NORM_ALIGN_BLOCK_SIZE (1 << 7) Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE for (; numItems != 0 && ((unsigned)(ptrdiff_t)items & (LZFIND_NORM_ALIGN_BLOCK_SIZE - 1)) != 0; numItems--) { SASUB_32(0) items++; } { const size_t k_Align_Mask = (LZFIND_NORM_ALIGN_BLOCK_SIZE / 4 - 1); CLzRef *lim = items + (numItems & ~(size_t)k_Align_Mask); numItems &= k_Align_Mask; if (items != lim) { #if defined(USE_LZFIND_SATUR_SUB_128) && !defined(FORCE_LZFIND_SATUR_SUB_128) if (g_LzFind_SaturSub) g_LzFind_SaturSub(subValue, items, lim); else #endif DEFAULT_SaturSub(subValue, items, lim); } items = lim; } Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE for (; numItems != 0; numItems--) { SASUB_32(0) items++; } } // call MatchFinder_CheckLimits() only after (p->pos++) update Z7_NO_INLINE static void MatchFinder_CheckLimits(CMatchFinder *p) { if (// !p->streamEndWasReached && p->result == SZ_OK && p->keepSizeAfter == GET_AVAIL_BYTES(p)) { // we try to read only in exact state (p->keepSizeAfter == GET_AVAIL_BYTES(p)) if (MatchFinder_NeedMove(p)) MatchFinder_MoveBlock(p); MatchFinder_ReadBlock(p); } if (p->pos == kMaxValForNormalize) if (GET_AVAIL_BYTES(p) >= p->numHashBytes) // optional optimization for last bytes of data. /* if we disable normalization for last bytes of data, and if (data_size == 4 GiB), we don't call wastfull normalization, but (pos) will be wrapped over Zero (0) in that case. And we cannot resume later to normal operation */ { // MatchFinder_Normalize(p); /* after normalization we need (p->pos >= p->historySize + 1); */ /* we can reduce subValue to aligned value, if want to keep alignment of (p->pos) and (p->buffer) for speculated accesses. */ const UInt32 subValue = (p->pos - p->historySize - 1) /* & ~(UInt32)(kNormalizeAlign - 1) */; // const UInt32 subValue = (1 << 15); // for debug // printf("\nMatchFinder_Normalize() subValue == 0x%x\n", subValue); MatchFinder_REDUCE_OFFSETS(p, subValue) MatchFinder_Normalize3(subValue, p->hash, (size_t)p->hashMask + 1 + p->fixedHashSize); { size_t numSonRefs = p->cyclicBufferSize; if (p->btMode) numSonRefs <<= 1; MatchFinder_Normalize3(subValue, p->son, numSonRefs); } } if (p->cyclicBufferPos == p->cyclicBufferSize) p->cyclicBufferPos = 0; MatchFinder_SetLimits(p); } /* (lenLimit > maxLen) */ Z7_FORCE_INLINE static UInt32 * Hc_GetMatchesSpec(size_t lenLimit, UInt32 curMatch, UInt32 pos, const Byte *cur, CLzRef *son, size_t _cyclicBufferPos, UInt32 _cyclicBufferSize, UInt32 cutValue, UInt32 *d, unsigned maxLen) { /* son[_cyclicBufferPos] = curMatch; for (;;) { UInt32 delta = pos - curMatch; if (cutValue-- == 0 || delta >= _cyclicBufferSize) return d; { const Byte *pb = cur - delta; curMatch = son[_cyclicBufferPos - delta + ((delta > _cyclicBufferPos) ? _cyclicBufferSize : 0)]; if (pb[maxLen] == cur[maxLen] && *pb == *cur) { UInt32 len = 0; while (++len != lenLimit) if (pb[len] != cur[len]) break; if (maxLen < len) { maxLen = len; *d++ = len; *d++ = delta - 1; if (len == lenLimit) return d; } } } } */ const Byte *lim = cur + lenLimit; son[_cyclicBufferPos] = curMatch; do { UInt32 delta; if (curMatch == 0) break; // if (curMatch2 >= curMatch) return NULL; delta = pos - curMatch; if (delta >= _cyclicBufferSize) break; { ptrdiff_t diff; curMatch = son[_cyclicBufferPos - delta + ((delta > _cyclicBufferPos) ? _cyclicBufferSize : 0)]; diff = (ptrdiff_t)0 - (ptrdiff_t)delta; if (cur[maxLen] == cur[(ptrdiff_t)maxLen + diff]) { const Byte *c = cur; while (*c == c[diff]) { if (++c == lim) { d[0] = (UInt32)(lim - cur); d[1] = delta - 1; return d + 2; } } { const unsigned len = (unsigned)(c - cur); if (maxLen < len) { maxLen = len; d[0] = (UInt32)len; d[1] = delta - 1; d += 2; } } } } } while (--cutValue); return d; } Z7_FORCE_INLINE UInt32 * GetMatchesSpec1(UInt32 lenLimit, UInt32 curMatch, UInt32 pos, const Byte *cur, CLzRef *son, size_t _cyclicBufferPos, UInt32 _cyclicBufferSize, UInt32 cutValue, UInt32 *d, UInt32 maxLen) { CLzRef *ptr0 = son + ((size_t)_cyclicBufferPos << 1) + 1; CLzRef *ptr1 = son + ((size_t)_cyclicBufferPos << 1); unsigned len0 = 0, len1 = 0; UInt32 cmCheck; // if (curMatch >= pos) { *ptr0 = *ptr1 = kEmptyHashValue; return NULL; } cmCheck = (UInt32)(pos - _cyclicBufferSize); if ((UInt32)pos <= _cyclicBufferSize) cmCheck = 0; if (cmCheck < curMatch) do { const UInt32 delta = pos - curMatch; { CLzRef *pair = son + ((size_t)(_cyclicBufferPos - delta + ((delta > _cyclicBufferPos) ? _cyclicBufferSize : 0)) << 1); const Byte *pb = cur - delta; unsigned len = (len0 < len1 ? len0 : len1); const UInt32 pair0 = pair[0]; if (pb[len] == cur[len]) { if (++len != lenLimit && pb[len] == cur[len]) while (++len != lenLimit) if (pb[len] != cur[len]) break; if (maxLen < len) { maxLen = (UInt32)len; *d++ = (UInt32)len; *d++ = delta - 1; if (len == lenLimit) { *ptr1 = pair0; *ptr0 = pair[1]; return d; } } } if (pb[len] < cur[len]) { *ptr1 = curMatch; // const UInt32 curMatch2 = pair[1]; // if (curMatch2 >= curMatch) { *ptr0 = *ptr1 = kEmptyHashValue; return NULL; } // curMatch = curMatch2; curMatch = pair[1]; ptr1 = pair + 1; len1 = len; } else { *ptr0 = curMatch; curMatch = pair[0]; ptr0 = pair; len0 = len; } } } while(--cutValue && cmCheck < curMatch); *ptr0 = *ptr1 = kEmptyHashValue; return d; } static void SkipMatchesSpec(UInt32 lenLimit, UInt32 curMatch, UInt32 pos, const Byte *cur, CLzRef *son, size_t _cyclicBufferPos, UInt32 _cyclicBufferSize, UInt32 cutValue) { CLzRef *ptr0 = son + ((size_t)_cyclicBufferPos << 1) + 1; CLzRef *ptr1 = son + ((size_t)_cyclicBufferPos << 1); unsigned len0 = 0, len1 = 0; UInt32 cmCheck; cmCheck = (UInt32)(pos - _cyclicBufferSize); if ((UInt32)pos <= _cyclicBufferSize) cmCheck = 0; if (// curMatch >= pos || // failure cmCheck < curMatch) do { const UInt32 delta = pos - curMatch; { CLzRef *pair = son + ((size_t)(_cyclicBufferPos - delta + ((delta > _cyclicBufferPos) ? _cyclicBufferSize : 0)) << 1); const Byte *pb = cur - delta; unsigned len = (len0 < len1 ? len0 : len1); if (pb[len] == cur[len]) { while (++len != lenLimit) if (pb[len] != cur[len]) break; { if (len == lenLimit) { *ptr1 = pair[0]; *ptr0 = pair[1]; return; } } } if (pb[len] < cur[len]) { *ptr1 = curMatch; curMatch = pair[1]; ptr1 = pair + 1; len1 = len; } else { *ptr0 = curMatch; curMatch = pair[0]; ptr0 = pair; len0 = len; } } } while(--cutValue && cmCheck < curMatch); *ptr0 = *ptr1 = kEmptyHashValue; return; } #define MOVE_POS \ ++p->cyclicBufferPos; \ p->buffer++; \ { const UInt32 pos1 = p->pos + 1; p->pos = pos1; if (pos1 == p->posLimit) MatchFinder_CheckLimits(p); } #define MOVE_POS_RET MOVE_POS return distances; Z7_NO_INLINE static void MatchFinder_MovePos(CMatchFinder *p) { /* we go here at the end of stream data, when (avail < num_hash_bytes) We don't update sons[cyclicBufferPos << btMode]. So (sons) record will contain junk. And we cannot resume match searching to normal operation, even if we will provide more input data in buffer. p->sons[p->cyclicBufferPos << p->btMode] = 0; // kEmptyHashValue if (p->btMode) p->sons[(p->cyclicBufferPos << p->btMode) + 1] = 0; // kEmptyHashValue */ MOVE_POS } #define GET_MATCHES_HEADER2(minLen, ret_op) \ unsigned lenLimit; UInt32 hv; const Byte *cur; UInt32 curMatch; \ lenLimit = (unsigned)p->lenLimit; { if (lenLimit < minLen) { MatchFinder_MovePos(p); ret_op; }} \ cur = p->buffer; #define GET_MATCHES_HEADER(minLen) GET_MATCHES_HEADER2(minLen, return distances) #define SKIP_HEADER(minLen) do { GET_MATCHES_HEADER2(minLen, continue) #define MF_PARAMS(p) lenLimit, curMatch, p->pos, p->buffer, p->son, p->cyclicBufferPos, p->cyclicBufferSize, p->cutValue #define SKIP_FOOTER SkipMatchesSpec(MF_PARAMS(p)); MOVE_POS } while (--num); #define GET_MATCHES_FOOTER_BASE(_maxLen_, func) \ distances = func(MF_PARAMS(p), \ distances, (UInt32)_maxLen_); MOVE_POS_RET #define GET_MATCHES_FOOTER_BT(_maxLen_) \ GET_MATCHES_FOOTER_BASE(_maxLen_, GetMatchesSpec1) #define GET_MATCHES_FOOTER_HC(_maxLen_) \ GET_MATCHES_FOOTER_BASE(_maxLen_, Hc_GetMatchesSpec) #define UPDATE_maxLen { \ const ptrdiff_t diff = (ptrdiff_t)0 - (ptrdiff_t)d2; \ const Byte *c = cur + maxLen; \ const Byte *lim = cur + lenLimit; \ for (; c != lim; c++) if (*(c + diff) != *c) break; \ maxLen = (unsigned)(c - cur); } static UInt32* Bt2_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) { GET_MATCHES_HEADER(2) HASH2_CALC curMatch = p->hash[hv]; p->hash[hv] = p->pos; GET_MATCHES_FOOTER_BT(1) } UInt32* Bt3Zip_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) { GET_MATCHES_HEADER(3) HASH_ZIP_CALC curMatch = p->hash[hv]; p->hash[hv] = p->pos; GET_MATCHES_FOOTER_BT(2) } #define SET_mmm \ mmm = p->cyclicBufferSize; \ if (pos < mmm) \ mmm = pos; static UInt32* Bt3_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) { UInt32 mmm; UInt32 h2, d2, pos; unsigned maxLen; UInt32 *hash; GET_MATCHES_HEADER(3) HASH3_CALC hash = p->hash; pos = p->pos; d2 = pos - hash[h2]; curMatch = (hash + kFix3HashSize)[hv]; hash[h2] = pos; (hash + kFix3HashSize)[hv] = pos; SET_mmm maxLen = 2; if (d2 < mmm && *(cur - d2) == *cur) { UPDATE_maxLen distances[0] = (UInt32)maxLen; distances[1] = d2 - 1; distances += 2; if (maxLen == lenLimit) { SkipMatchesSpec(MF_PARAMS(p)); MOVE_POS_RET } } GET_MATCHES_FOOTER_BT(maxLen) } static UInt32* Bt4_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) { UInt32 mmm; UInt32 h2, h3, d2, d3, pos; unsigned maxLen; UInt32 *hash; GET_MATCHES_HEADER(4) HASH4_CALC hash = p->hash; pos = p->pos; d2 = pos - hash [h2]; d3 = pos - (hash + kFix3HashSize)[h3]; curMatch = (hash + kFix4HashSize)[hv]; hash [h2] = pos; (hash + kFix3HashSize)[h3] = pos; (hash + kFix4HashSize)[hv] = pos; SET_mmm maxLen = 3; for (;;) { if (d2 < mmm && *(cur - d2) == *cur) { distances[0] = 2; distances[1] = d2 - 1; distances += 2; if (*(cur - d2 + 2) == cur[2]) { // distances[-2] = 3; } else if (d3 < mmm && *(cur - d3) == *cur) { d2 = d3; distances[1] = d3 - 1; distances += 2; } else break; } else if (d3 < mmm && *(cur - d3) == *cur) { d2 = d3; distances[1] = d3 - 1; distances += 2; } else break; UPDATE_maxLen distances[-2] = (UInt32)maxLen; if (maxLen == lenLimit) { SkipMatchesSpec(MF_PARAMS(p)); MOVE_POS_RET } break; } GET_MATCHES_FOOTER_BT(maxLen) } static UInt32* Bt5_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) { UInt32 mmm; UInt32 h2, h3, d2, d3, maxLen, pos; UInt32 *hash; GET_MATCHES_HEADER(5) HASH5_CALC hash = p->hash; pos = p->pos; d2 = pos - hash [h2]; d3 = pos - (hash + kFix3HashSize)[h3]; // d4 = pos - (hash + kFix4HashSize)[h4]; curMatch = (hash + kFix5HashSize)[hv]; hash [h2] = pos; (hash + kFix3HashSize)[h3] = pos; // (hash + kFix4HashSize)[h4] = pos; (hash + kFix5HashSize)[hv] = pos; SET_mmm maxLen = 4; for (;;) { if (d2 < mmm && *(cur - d2) == *cur) { distances[0] = 2; distances[1] = d2 - 1; distances += 2; if (*(cur - d2 + 2) == cur[2]) { } else if (d3 < mmm && *(cur - d3) == *cur) { distances[1] = d3 - 1; distances += 2; d2 = d3; } else break; } else if (d3 < mmm && *(cur - d3) == *cur) { distances[1] = d3 - 1; distances += 2; d2 = d3; } else break; distances[-2] = 3; if (*(cur - d2 + 3) != cur[3]) break; UPDATE_maxLen distances[-2] = (UInt32)maxLen; if (maxLen == lenLimit) { SkipMatchesSpec(MF_PARAMS(p)); MOVE_POS_RET } break; } GET_MATCHES_FOOTER_BT(maxLen) } static UInt32* Hc4_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) { UInt32 mmm; UInt32 h2, h3, d2, d3, pos; unsigned maxLen; UInt32 *hash; GET_MATCHES_HEADER(4) HASH4_CALC hash = p->hash; pos = p->pos; d2 = pos - hash [h2]; d3 = pos - (hash + kFix3HashSize)[h3]; curMatch = (hash + kFix4HashSize)[hv]; hash [h2] = pos; (hash + kFix3HashSize)[h3] = pos; (hash + kFix4HashSize)[hv] = pos; SET_mmm maxLen = 3; for (;;) { if (d2 < mmm && *(cur - d2) == *cur) { distances[0] = 2; distances[1] = d2 - 1; distances += 2; if (*(cur - d2 + 2) == cur[2]) { // distances[-2] = 3; } else if (d3 < mmm && *(cur - d3) == *cur) { d2 = d3; distances[1] = d3 - 1; distances += 2; } else break; } else if (d3 < mmm && *(cur - d3) == *cur) { d2 = d3; distances[1] = d3 - 1; distances += 2; } else break; UPDATE_maxLen distances[-2] = (UInt32)maxLen; if (maxLen == lenLimit) { p->son[p->cyclicBufferPos] = curMatch; MOVE_POS_RET } break; } GET_MATCHES_FOOTER_HC(maxLen) } static UInt32 * Hc5_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) { UInt32 mmm; UInt32 h2, h3, d2, d3, maxLen, pos; UInt32 *hash; GET_MATCHES_HEADER(5) HASH5_CALC hash = p->hash; pos = p->pos; d2 = pos - hash [h2]; d3 = pos - (hash + kFix3HashSize)[h3]; // d4 = pos - (hash + kFix4HashSize)[h4]; curMatch = (hash + kFix5HashSize)[hv]; hash [h2] = pos; (hash + kFix3HashSize)[h3] = pos; // (hash + kFix4HashSize)[h4] = pos; (hash + kFix5HashSize)[hv] = pos; SET_mmm maxLen = 4; for (;;) { if (d2 < mmm && *(cur - d2) == *cur) { distances[0] = 2; distances[1] = d2 - 1; distances += 2; if (*(cur - d2 + 2) == cur[2]) { } else if (d3 < mmm && *(cur - d3) == *cur) { distances[1] = d3 - 1; distances += 2; d2 = d3; } else break; } else if (d3 < mmm && *(cur - d3) == *cur) { distances[1] = d3 - 1; distances += 2; d2 = d3; } else break; distances[-2] = 3; if (*(cur - d2 + 3) != cur[3]) break; UPDATE_maxLen distances[-2] = maxLen; if (maxLen == lenLimit) { p->son[p->cyclicBufferPos] = curMatch; MOVE_POS_RET } break; } GET_MATCHES_FOOTER_HC(maxLen) } UInt32* Hc3Zip_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) { GET_MATCHES_HEADER(3) HASH_ZIP_CALC curMatch = p->hash[hv]; p->hash[hv] = p->pos; GET_MATCHES_FOOTER_HC(2) } static void Bt2_MatchFinder_Skip(CMatchFinder *p, UInt32 num) { SKIP_HEADER(2) { HASH2_CALC curMatch = p->hash[hv]; p->hash[hv] = p->pos; } SKIP_FOOTER } void Bt3Zip_MatchFinder_Skip(CMatchFinder *p, UInt32 num) { SKIP_HEADER(3) { HASH_ZIP_CALC curMatch = p->hash[hv]; p->hash[hv] = p->pos; } SKIP_FOOTER } static void Bt3_MatchFinder_Skip(CMatchFinder *p, UInt32 num) { SKIP_HEADER(3) { UInt32 h2; UInt32 *hash; HASH3_CALC hash = p->hash; curMatch = (hash + kFix3HashSize)[hv]; hash[h2] = (hash + kFix3HashSize)[hv] = p->pos; } SKIP_FOOTER } static void Bt4_MatchFinder_Skip(CMatchFinder *p, UInt32 num) { SKIP_HEADER(4) { UInt32 h2, h3; UInt32 *hash; HASH4_CALC hash = p->hash; curMatch = (hash + kFix4HashSize)[hv]; hash [h2] = (hash + kFix3HashSize)[h3] = (hash + kFix4HashSize)[hv] = p->pos; } SKIP_FOOTER } static void Bt5_MatchFinder_Skip(CMatchFinder *p, UInt32 num) { SKIP_HEADER(5) { UInt32 h2, h3; UInt32 *hash; HASH5_CALC hash = p->hash; curMatch = (hash + kFix5HashSize)[hv]; hash [h2] = (hash + kFix3HashSize)[h3] = // (hash + kFix4HashSize)[h4] = (hash + kFix5HashSize)[hv] = p->pos; } SKIP_FOOTER } #define HC_SKIP_HEADER(minLen) \ do { if (p->lenLimit < minLen) { MatchFinder_MovePos(p); num--; continue; } { \ const Byte *cur; \ UInt32 *hash; \ UInt32 *son; \ UInt32 pos = p->pos; \ UInt32 num2 = num; \ /* (p->pos == p->posLimit) is not allowed here !!! */ \ { const UInt32 rem = p->posLimit - pos; if (num2 > rem) num2 = rem; } \ num -= num2; \ { const UInt32 cycPos = p->cyclicBufferPos; \ son = p->son + cycPos; \ p->cyclicBufferPos = cycPos + num2; } \ cur = p->buffer; \ hash = p->hash; \ do { \ UInt32 curMatch; \ UInt32 hv; #define HC_SKIP_FOOTER \ cur++; pos++; *son++ = curMatch; \ } while (--num2); \ p->buffer = cur; \ p->pos = pos; \ if (pos == p->posLimit) MatchFinder_CheckLimits(p); \ }} while(num); \ static void Hc4_MatchFinder_Skip(CMatchFinder *p, UInt32 num) { HC_SKIP_HEADER(4) UInt32 h2, h3; HASH4_CALC curMatch = (hash + kFix4HashSize)[hv]; hash [h2] = (hash + kFix3HashSize)[h3] = (hash + kFix4HashSize)[hv] = pos; HC_SKIP_FOOTER } static void Hc5_MatchFinder_Skip(CMatchFinder *p, UInt32 num) { HC_SKIP_HEADER(5) UInt32 h2, h3; HASH5_CALC curMatch = (hash + kFix5HashSize)[hv]; hash [h2] = (hash + kFix3HashSize)[h3] = // (hash + kFix4HashSize)[h4] = (hash + kFix5HashSize)[hv] = pos; HC_SKIP_FOOTER } void Hc3Zip_MatchFinder_Skip(CMatchFinder *p, UInt32 num) { HC_SKIP_HEADER(3) HASH_ZIP_CALC curMatch = hash[hv]; hash[hv] = pos; HC_SKIP_FOOTER } void MatchFinder_CreateVTable(CMatchFinder *p, IMatchFinder2 *vTable) { vTable->Init = (Mf_Init_Func)MatchFinder_Init; vTable->GetNumAvailableBytes = (Mf_GetNumAvailableBytes_Func)MatchFinder_GetNumAvailableBytes; vTable->GetPointerToCurrentPos = (Mf_GetPointerToCurrentPos_Func)MatchFinder_GetPointerToCurrentPos; if (!p->btMode) { if (p->numHashBytes <= 4) { vTable->GetMatches = (Mf_GetMatches_Func)Hc4_MatchFinder_GetMatches; vTable->Skip = (Mf_Skip_Func)Hc4_MatchFinder_Skip; } else { vTable->GetMatches = (Mf_GetMatches_Func)Hc5_MatchFinder_GetMatches; vTable->Skip = (Mf_Skip_Func)Hc5_MatchFinder_Skip; } } else if (p->numHashBytes == 2) { vTable->GetMatches = (Mf_GetMatches_Func)Bt2_MatchFinder_GetMatches; vTable->Skip = (Mf_Skip_Func)Bt2_MatchFinder_Skip; } else if (p->numHashBytes == 3) { vTable->GetMatches = (Mf_GetMatches_Func)Bt3_MatchFinder_GetMatches; vTable->Skip = (Mf_Skip_Func)Bt3_MatchFinder_Skip; } else if (p->numHashBytes == 4) { vTable->GetMatches = (Mf_GetMatches_Func)Bt4_MatchFinder_GetMatches; vTable->Skip = (Mf_Skip_Func)Bt4_MatchFinder_Skip; } else { vTable->GetMatches = (Mf_GetMatches_Func)Bt5_MatchFinder_GetMatches; vTable->Skip = (Mf_Skip_Func)Bt5_MatchFinder_Skip; } } void LzFindPrepare(void) { #ifndef FORCE_LZFIND_SATUR_SUB_128 #ifdef USE_LZFIND_SATUR_SUB_128 LZFIND_SATUR_SUB_CODE_FUNC f = NULL; #ifdef MY_CPU_ARM_OR_ARM64 { if (CPU_IsSupported_NEON()) { // #pragma message ("=== LzFind NEON") PRF(printf("\n=== LzFind NEON\n")); f = LzFind_SaturSub_128; } // f = 0; // for debug } #else // MY_CPU_ARM_OR_ARM64 if (CPU_IsSupported_SSE41()) { // #pragma message ("=== LzFind SSE41") PRF(printf("\n=== LzFind SSE41\n")); f = LzFind_SaturSub_128; #ifdef USE_LZFIND_SATUR_SUB_256 if (CPU_IsSupported_AVX2()) { // #pragma message ("=== LzFind AVX2") PRF(printf("\n=== LzFind AVX2\n")); f = LzFind_SaturSub_256; } #endif } #endif // MY_CPU_ARM_OR_ARM64 g_LzFind_SaturSub = f; #endif // USE_LZFIND_SATUR_SUB_128 #endif // FORCE_LZFIND_SATUR_SUB_128 } #undef MOVE_POS #undef MOVE_POS_RET #undef PRF