-
Notifications
You must be signed in to change notification settings - Fork 61
/
Copy pathcommon.c
590 lines (491 loc) · 15.9 KB
/
common.c
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
#include "pixz.h"
#include <errno.h>
#include <stdarg.h>
#include <math.h>
#if HAVE__GET_OSFHANDLE
#include <windows.h>
#endif
#pragma mark UTILS
FILE *gInFile = NULL, *gOutFile = NULL;
lzma_stream gStream = LZMA_STREAM_INIT;
void die(const char *fmt, ...) {
va_list args;
va_start(args, fmt);
vfprintf(stderr, fmt, args);
fprintf(stderr, "\n");
fflush(stderr);
va_end(args);
exit(1);
}
char *xstrdup(const char *s) {
if (!s)
return NULL;
size_t len = strlen(s);
char *r = malloc(len + 1);
if (!r)
return NULL;
return memcpy(r, s, len + 1);
}
bool is_multi_header(const char *name) {
size_t i = strlen(name);
while (i != 0 && name[i - 1] != '/')
--i;
return strncmp(name + i, "._", 2) == 0;
}
#pragma mark INDEX
lzma_index *gIndex = NULL;
file_index_t *gFileIndex = NULL, *gLastFile = NULL;
static uint8_t *gFileIndexBuf = NULL;
static size_t gFIBSize = CHUNKSIZE, gFIBPos = 0;
static lzma_ret gFIBErr = LZMA_OK;
static uint8_t gFIBInputBuf[CHUNKSIZE];
static size_t gMoved = 0;
static void *decode_file_index_start(off_t block_seek, lzma_check check);
static lzma_vli find_file_index(void **bdatap);
static char *read_file_index_name(void);
static void read_file_index_make_space(void);
static void read_file_index_data(void);
void dump_file_index(FILE *out, bool verbose) {
for (file_index_t *f = gFileIndex; f != NULL; f = f->next) {
if (verbose) {
fprintf(out, "%10"PRIuMAX" %s\n", (uintmax_t)f->offset,
f->name ? f->name : "");
} else {
if (f->name)
fprintf(out, "%s\n", f->name);
}
}
}
void free_file_index(void) {
for (file_index_t *f = gFileIndex; f != NULL; ) {
file_index_t *next = f->next;
free(f->name);
free(f);
f = next;
}
gFileIndex = gLastFile = NULL;
}
typedef struct {
lzma_block block;
lzma_filter filters[LZMA_FILTERS_MAX + 1];
} block_wrapper_t;
static void *decode_file_index_start(off_t block_seek, lzma_check check) {
if (fseeko(gInFile, block_seek, SEEK_SET) == -1)
die("Error seeking to block");
// Some memory in which to keep the discovered filters safe
block_wrapper_t *bw = malloc(sizeof(block_wrapper_t));
bw->block = (lzma_block){ .check = check, .filters = bw->filters,
.version = 0 };
int b = fgetc(gInFile);
if (b == EOF || b == 0)
die("Error reading block size");
bw->block.header_size = lzma_block_header_size_decode(b);
uint8_t hdrbuf[bw->block.header_size];
hdrbuf[0] = (uint8_t)b;
if (fread(hdrbuf + 1, bw->block.header_size - 1, 1, gInFile) != 1)
die("Error reading block header");
if (lzma_block_header_decode(&bw->block, NULL, hdrbuf) != LZMA_OK)
die("Error decoding file index block header");
if (lzma_block_decoder(&gStream, &bw->block) != LZMA_OK)
die("Error initializing file index stream");
return bw;
}
static lzma_vli find_file_index(void **bdatap) {
if (!gIndex)
decode_index();
// find the last block
lzma_index_iter iter;
lzma_index_iter_init(&iter, gIndex);
lzma_vli loc = lzma_index_uncompressed_size(gIndex) - 1;
if (lzma_index_iter_locate(&iter, loc))
die("Can't locate file index block");
if (iter.stream.number != 1)
return 0; // Too many streams for one file index
void *bdata = decode_file_index_start(iter.block.compressed_file_offset,
iter.stream.flags->check);
gFileIndexBuf = malloc(gFIBSize);
gStream.avail_out = gFIBSize;
gStream.avail_in = 0;
// Check if this is really an index
read_file_index_data();
lzma_vli ret = iter.block.compressed_file_offset;
if (xle64dec(gFileIndexBuf + gFIBPos) != PIXZ_INDEX_MAGIC)
ret = 0;
gFIBPos += sizeof(uint64_t);
if (bdatap && ret) {
*bdatap = bdata;
} else {
// Just looking, don't keep things around
if (bdatap)
*bdatap = NULL;
free(bdata);
free(gFileIndexBuf);
gLastFile = gFileIndex = NULL;
lzma_end(&gStream);
}
return ret;
}
lzma_vli read_file_index() {
void *bdata = NULL;
lzma_vli offset = find_file_index(&bdata);
if (!offset)
return 0;
while (true) {
char *name = read_file_index_name();
if (!name)
break;
file_index_t *f = malloc(sizeof(file_index_t));
f->name = strlen(name) ? xstrdup(name) : NULL;
f->offset = xle64dec(gFileIndexBuf + gFIBPos);
gFIBPos += sizeof(uint64_t);
if (gLastFile) {
gLastFile->next = f;
} else {
gFileIndex = f;
}
gLastFile = f;
}
free(gFileIndexBuf);
lzma_end(&gStream);
free(bdata);
return offset;
}
static char *read_file_index_name(void) {
while (true) {
// find a nul that ends a name
uint8_t *eos, *haystack = gFileIndexBuf + gFIBPos;
ssize_t len = gFIBSize - gStream.avail_out - gFIBPos - sizeof(uint64_t);
if (len > 0 && (eos = memchr(haystack, '\0', len))) { // found it
gFIBPos += eos - haystack + 1;
return (char*)haystack;
} else if (gFIBErr == LZMA_STREAM_END) { // nothing left
return NULL;
} else { // need more data
if (gStream.avail_out == 0)
read_file_index_make_space();
read_file_index_data();
}
}
}
static void read_file_index_make_space(void) {
bool expand = (gFIBPos == 0);
if (gFIBPos != 0) { // clear more space
size_t move = gFIBSize - gStream.avail_out - gFIBPos;
memmove(gFileIndexBuf, gFileIndexBuf + gFIBPos, move);
gMoved += move;
gStream.avail_out += gFIBPos;
gFIBPos = 0;
}
// Try to reduce number of moves by expanding proactively
if (expand || gMoved >= gFIBSize) { // malloc more space
gStream.avail_out += gFIBSize;
gFIBSize *= 2;
uint8_t *new_gFileIndexBuf = realloc(gFileIndexBuf, gFIBSize);
if (new_gFileIndexBuf == NULL) {
// TODO is recovery possible? does it even make sense?
// @see https://github.com/vasi/pixz/issues/8#issuecomment-134113347
die("memory re-allocation failure: %s", strerror(errno));
} else {
gFileIndexBuf = new_gFileIndexBuf;
}
}
}
static void read_file_index_data(void) {
gStream.next_out = gFileIndexBuf + gFIBSize - gStream.avail_out;
while (gFIBErr != LZMA_STREAM_END && gStream.avail_out) {
if (gStream.avail_in == 0) {
// It's ok to read past the end of the block, we'll still
// get LZMA_STREAM_END at the right place
gStream.avail_in = fread(gFIBInputBuf, 1, CHUNKSIZE, gInFile);
if (ferror(gInFile))
die("Error reading file index data");
gStream.next_in = gFIBInputBuf;
}
gFIBErr = lzma_code(&gStream, LZMA_RUN);
if (gFIBErr != LZMA_OK && gFIBErr != LZMA_STREAM_END)
die("Error decoding file index data");
}
}
#define BWCHUNK 512
typedef struct {
uint8_t buf[BWCHUNK];
off_t pos;
size_t size;
} bw;
static uint32_t *bw_read(bw *b) {
size_t sz = sizeof(uint32_t);
if (b->size < sz) {
if (b->pos < sz)
return NULL; // EOF
b->size = (b->pos > BWCHUNK) ? BWCHUNK : b->pos;
b->pos -= b->size;
if (fseeko(gInFile, b->pos, SEEK_SET) == -1)
return NULL;
if (fread(b->buf, b->size, 1, gInFile) != 1)
return NULL;
}
b->size -= sz;
return &((uint32_t*)b->buf)[b->size / sz];
}
static off_t stream_padding(bw *b, off_t pos) {
b->pos = pos;
b->size = 0;
for (off_t pad = 0; true; pad += sizeof(uint32_t)) {
uint32_t *i = bw_read(b);
if (!i)
die("Error reading stream padding");
if (*i != 0) {
b->size += sizeof(uint32_t);
return pad;
}
}
}
static void stream_footer(bw *b, lzma_stream_flags *flags) {
uint8_t ftr[LZMA_STREAM_HEADER_SIZE];
for (int i = sizeof(ftr) / sizeof(uint32_t) - 1; i >= 0; --i) {
uint32_t *p = bw_read(b);
if (!p)
die("Error reading stream footer");
*((uint32_t*)ftr + i) = *p;
}
if (lzma_stream_footer_decode(flags, ftr) != LZMA_OK)
die("Error decoding stream footer");
}
static lzma_index *next_index(off_t *pos) {
bw b;
off_t pad = stream_padding(&b, *pos);
off_t eos = *pos - pad;
lzma_stream_flags flags;
stream_footer(&b, &flags);
*pos = eos - LZMA_STREAM_HEADER_SIZE - flags.backward_size;
if (fseeko(gInFile, *pos, SEEK_SET) == -1)
die("Error seeking to index");
lzma_stream strm = LZMA_STREAM_INIT;
lzma_index *index;
if (lzma_index_decoder(&strm, &index, MEMLIMIT) != LZMA_OK)
die("Error creating index decoder");
uint8_t ibuf[CHUNKSIZE];
strm.avail_in = 0;
lzma_ret err = LZMA_OK;
while (err != LZMA_STREAM_END) {
if (strm.avail_in == 0) {
strm.avail_in = fread(ibuf, 1, CHUNKSIZE, gInFile);
if (ferror(gInFile))
die("Error reading index");
strm.next_in = ibuf;
}
err = lzma_code(&strm, LZMA_RUN);
if (err != LZMA_OK && err != LZMA_STREAM_END)
die("Error decoding index");
}
*pos = eos - lzma_index_stream_size(index);
if (fseeko(gInFile, *pos, SEEK_SET) == -1)
die("Error seeking to beginning of stream");
if (lzma_index_stream_flags(index, &flags) != LZMA_OK)
die("Error setting stream flags");
if (lzma_index_stream_padding(index, pad) != LZMA_OK)
die("Error setting stream padding");
return index;
}
bool decode_index(void) {
#if HAVE__GET_OSFHANDLE
// windows pretends that seeking works on pipes, but then it doesn't
// try to check that this is a "regular" file with win api
intptr_t hdl = _get_osfhandle(_fileno(gInFile));
DWORD ftype = GetFileType((HANDLE)hdl);
if (ftype != FILE_TYPE_DISK) {
fprintf(stderr, "can not seek in input\n");
return false;
}
#endif
if (fseeko(gInFile, 0, SEEK_END) == -1) {
fprintf(stderr, "can not seek in input: %s\n", strerror(errno));
return false; // not seekable
}
off_t pos = ftello(gInFile);
gIndex = NULL;
while (pos > 0) {
lzma_index *index = next_index(&pos);
if (gIndex && lzma_index_cat(index, gIndex, NULL) != LZMA_OK)
die("Error concatenating indices");
gIndex = index;
}
return (gIndex != NULL);
}
#pragma mark QUEUE
queue_t *queue_new(queue_free_t freer) {
queue_t *q = malloc(sizeof(queue_t));
q->first = q->last = NULL;
q->freer = freer;
pthread_mutex_init(&q->mutex, NULL);
pthread_cond_init(&q->pop_cond, NULL);
return q;
}
void queue_free(queue_t *q) {
for (queue_item_t *i = q->first; i; ) {
queue_item_t *tmp = i->next;
if (q->freer)
q->freer(i->type, i->data);
free(i);
i = tmp;
}
pthread_mutex_destroy(&q->mutex);
pthread_cond_destroy(&q->pop_cond);
free(q);
}
void queue_push(queue_t *q, int type, void *data) {
queue_item_t *i = malloc(sizeof(queue_item_t));
i->type = type;
i->data = data;
i->next = NULL;
pthread_mutex_lock(&q->mutex);
if (q->last) {
q->last->next = i;
} else {
q->first = i;
}
q->last = i;
pthread_cond_signal(&q->pop_cond);
pthread_mutex_unlock(&q->mutex);
}
int queue_pop(queue_t *q, void **datap) {
pthread_mutex_lock(&q->mutex);
while (!q->first)
pthread_cond_wait(&q->pop_cond, &q->mutex);
queue_item_t *i = q->first;
q->first = i->next;
if (!q->first)
q->last = NULL;
pthread_mutex_unlock(&q->mutex);
*datap = i->data;
int type = i->type;
free(i);
return type;
}
#pragma mark PIPELINE
queue_t *gPipelineStartQ = NULL,
*gPipelineSplitQ = NULL,
*gPipelineMergeQ = NULL;
size_t gPipelineProcessMax = 0;
size_t gPipelineQSize = 0;
pipeline_data_free_t gPLFreer = NULL;
pipeline_split_t gPLSplit = NULL;
pipeline_process_t gPLProcess = NULL;
size_t gPLProcessCount = 0;
pthread_t *gPLProcessThreads = NULL;
pthread_t gPLSplitThread;
ssize_t gPLSplitSeq = 0;
ssize_t gPLMergeSeq = 0;
pipeline_item_t *gPLMergedItems = NULL;
static void pipeline_qfree(int type, void *p);
static void *pipeline_thread_split(void *);
static void *pipeline_thread_process(void *arg);
void pipeline_create(
pipeline_data_create_t create,
pipeline_data_free_t destroy,
pipeline_split_t split,
pipeline_process_t process) {
gPLFreer = destroy;
gPLSplit = split;
gPLProcess = process;
gPipelineStartQ = queue_new(pipeline_qfree);
gPipelineSplitQ = queue_new(pipeline_qfree);
gPipelineMergeQ = queue_new(pipeline_qfree);
gPLSplitSeq = 0;
gPLMergeSeq = 0;
gPLMergedItems = NULL;
gPLProcessCount = num_threads();
if (gPipelineProcessMax > 0 && gPipelineProcessMax < gPLProcessCount)
gPLProcessCount = gPipelineProcessMax;
gPLProcessThreads = malloc(gPLProcessCount * sizeof(pthread_t));
int qsize = gPipelineQSize ? gPipelineQSize
: ceil(gPLProcessCount * 1.3 + 1);
if (qsize < gPLProcessCount) {
fprintf(stderr, "Warning: queue size is less than thread count, "
"performance will suffer!\n");
}
for (size_t i = 0; i < qsize; ++i) {
// create blocks, including a margin of error
pipeline_item_t *item = malloc(sizeof(pipeline_item_t));
item->data = create();
// seq and next are garbage
queue_push(gPipelineStartQ, PIPELINE_ITEM, item);
}
for (size_t i = 0; i < gPLProcessCount; ++i) {
if (pthread_create(&gPLProcessThreads[i], NULL,
&pipeline_thread_process, (void*)(uintptr_t)i))
die("Error creating encode thread");
}
if (pthread_create(&gPLSplitThread, NULL, &pipeline_thread_split, NULL))
die("Error creating read thread");
}
static void pipeline_qfree(int type, void *p) {
switch (type) {
case PIPELINE_ITEM: {
pipeline_item_t *item = (pipeline_item_t*)p;
gPLFreer(item->data);
free(item);
break;
}
case PIPELINE_STOP:
break;
default:
die("Unknown msg type %d", type);
}
}
static void *pipeline_thread_split(void *ignore) {
gPLSplit();
return NULL;
}
static void *pipeline_thread_process(void *arg) {
size_t thnum = (uintptr_t)arg;
gPLProcess(thnum);
return NULL;
}
void pipeline_stop(void) {
// ask the other threads to stop
for (size_t i = 0; i < gPLProcessCount; ++i)
queue_push(gPipelineSplitQ, PIPELINE_STOP, NULL);
for (size_t i = 0; i < gPLProcessCount; ++i) {
if (pthread_join(gPLProcessThreads[i], NULL))
die("Error joining processing thread");
}
queue_push(gPipelineMergeQ, PIPELINE_STOP, NULL);
}
void pipeline_destroy(void) {
if (pthread_join(gPLSplitThread, NULL))
die("Error joining splitter thread");
queue_free(gPipelineStartQ);
queue_free(gPipelineSplitQ);
queue_free(gPipelineMergeQ);
free(gPLProcessThreads);
}
void pipeline_dispatch(pipeline_item_t *item, queue_t *q) {
item->seq = gPLSplitSeq++;
item->next = NULL;
queue_push(q, PIPELINE_ITEM, item);
}
void pipeline_split(pipeline_item_t *item) {
pipeline_dispatch(item, gPipelineSplitQ);
}
pipeline_item_t *pipeline_merged() {
pipeline_item_t *item;
while (!gPLMergedItems || gPLMergedItems->seq != gPLMergeSeq) {
// We don't have the next item, wait for a new one
pipeline_tag_t tag = queue_pop(gPipelineMergeQ, (void**)&item);
if (tag == PIPELINE_STOP)
return NULL; // Done processing items
// Insert the item into the queue
pipeline_item_t **prev = &gPLMergedItems;
while (*prev && (*prev)->seq < item->seq) {
prev = &(*prev)->next;
}
item->next = *prev;
*prev = item;
}
// Got the next item
item = gPLMergedItems;
gPLMergedItems = item->next;
++gPLMergeSeq;
return item;
}