Debian Codegraph @

c-ext/decompressor.c

raw
1 /**
2 * Copyright (c) 2016-present, Gregory Szorc
3 * All rights reserved.
4 *
5 * This software may be modified and distributed under the terms
6 * of the BSD license. See the LICENSE file for details.
7 */
8
9 #include "python-zstandard.h"
10
11 extern PyObject *ZstdError;
12
13 /**
14 * Ensure the ZSTD_DCtx on a decompressor is initiated and ready for a new
15 * operation.
16 */
17 int ensure_dctx(ZstdDecompressor *decompressor, int loadDict) {
18 size_t zresult;
19
20 ZSTD_DCtx_reset(decompressor->dctx, ZSTD_reset_session_only);
21
22 if (decompressor->maxWindowSize) {
23 zresult = ZSTD_DCtx_setMaxWindowSize(decompressor->dctx,
24 decompressor->maxWindowSize);
25 if (ZSTD_isError(zresult)) {
26 PyErr_Format(ZstdError, "unable to set max window size: %s",
27 ZSTD_getErrorName(zresult));
28 return 1;
29 }
30 }
31
32 zresult = ZSTD_DCtx_setParameter(decompressor->dctx, ZSTD_d_format,
33 decompressor->format);
34 if (ZSTD_isError(zresult)) {
35 PyErr_Format(ZstdError, "unable to set decoding format: %s",
36 ZSTD_getErrorName(zresult));
37 return 1;
38 }
39
40 if (loadDict && decompressor->dict) {
41 if (ensure_ddict(decompressor->dict)) {
42 return 1;
43 }
44
45 zresult =
46 ZSTD_DCtx_refDDict(decompressor->dctx, decompressor->dict->ddict);
47 if (ZSTD_isError(zresult)) {
48 PyErr_Format(ZstdError,
49 "unable to reference prepared dictionary: %s",
50 ZSTD_getErrorName(zresult));
51 return 1;
52 }
53 }
54
55 return 0;
56 }
57
58 static int Decompressor_init(ZstdDecompressor *self, PyObject *args,
59 PyObject *kwargs) {
60 static char *kwlist[] = {"dict_data", "max_window_size", "format", NULL};
61
62 PyObject *dict = NULL;
63 Py_ssize_t maxWindowSize = 0;
64 ZSTD_format_e format = ZSTD_f_zstd1;
65
66 self->dctx = NULL;
67 self->dict = NULL;
68
69 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|OnI:ZstdDecompressor",
70 kwlist, &dict, &maxWindowSize, &format)) {
71 return -1;
72 }
73
74 if (dict) {
75 if (dict == Py_None) {
76 dict = NULL;
77 }
78 else if (!PyObject_IsInstance(dict,
79 (PyObject *)ZstdCompressionDictType)) {
80 PyErr_Format(PyExc_TypeError,
81 "dict_data must be zstd.ZstdCompressionDict");
82 return -1;
83 }
84 }
85
86 self->dctx = ZSTD_createDCtx();
87 if (!self->dctx) {
88 PyErr_NoMemory();
89 goto except;
90 }
91
92 self->maxWindowSize = maxWindowSize;
93 self->format = format;
94
95 if (dict) {
96 self->dict = (ZstdCompressionDict *)dict;
97 Py_INCREF(dict);
98 }
99
100 if (ensure_dctx(self, 1)) {
101 goto except;
102 }
103
104 return 0;
105
106 except:
107 Py_CLEAR(self->dict);
108
109 if (self->dctx) {
110 ZSTD_freeDCtx(self->dctx);
111 self->dctx = NULL;
112 }
113
114 return -1;
115 }
116
117 static void Decompressor_dealloc(ZstdDecompressor *self) {
118 Py_CLEAR(self->dict);
119
120 if (self->dctx) {
121 ZSTD_freeDCtx(self->dctx);
122 self->dctx = NULL;
123 }
124
125 PyObject_Del(self);
126 }
127
128 static PyObject *Decompressor_memory_size(ZstdDecompressor *self) {
129 if (self->dctx) {
130 return PyLong_FromSize_t(ZSTD_sizeof_DCtx(self->dctx));
131 }
132 else {
133 PyErr_SetString(
134 ZstdError,
135 "no decompressor context found; this should never happen");
136 return NULL;
137 }
138 }
139
140 static PyObject *Decompressor_copy_stream(ZstdDecompressor *self,
141 PyObject *args, PyObject *kwargs) {
142 static char *kwlist[] = {"ifh", "ofh", "read_size", "write_size", NULL};
143
144 PyObject *source;
145 PyObject *dest;
146 size_t inSize = ZSTD_DStreamInSize();
147 size_t outSize = ZSTD_DStreamOutSize();
148 ZSTD_inBuffer input;
149 ZSTD_outBuffer output;
150 Py_ssize_t totalRead = 0;
151 Py_ssize_t totalWrite = 0;
152 char *readBuffer;
153 Py_ssize_t readSize;
154 PyObject *readResult = NULL;
155 PyObject *res = NULL;
156 size_t zresult = 0;
157 PyObject *writeResult;
158 PyObject *totalReadPy;
159 PyObject *totalWritePy;
160
161 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OO|kk:copy_stream", kwlist,
162 &source, &dest, &inSize, &outSize)) {
163 return NULL;
164 }
165
166 if (!PyObject_HasAttrString(source, "read")) {
167 PyErr_SetString(PyExc_ValueError,
168 "first argument must have a read() method");
169 return NULL;
170 }
171
172 if (!PyObject_HasAttrString(dest, "write")) {
173 PyErr_SetString(PyExc_ValueError,
174 "second argument must have a write() method");
175 return NULL;
176 }
177
178 /* Prevent free on uninitialized memory in finally. */
179 output.dst = NULL;
180
181 if (ensure_dctx(self, 1)) {
182 res = NULL;
183 goto finally;
184 }
185
186 output.dst = PyMem_Malloc(outSize);
187 if (!output.dst) {
188 PyErr_NoMemory();
189 res = NULL;
190 goto finally;
191 }
192 output.size = outSize;
193 output.pos = 0;
194
195 /* Read source stream until EOF */
196 while (1) {
197 readResult = PyObject_CallMethod(source, "read", "n", inSize);
198 if (!readResult) {
199 goto finally;
200 }
201
202 PyBytes_AsStringAndSize(readResult, &readBuffer, &readSize);
203
204 /* If no data was read, we're at EOF. */
205 if (0 == readSize) {
206 break;
207 }
208
209 totalRead += readSize;
210
211 /* Send data to decompressor */
212 input.src = readBuffer;
213 input.size = readSize;
214 input.pos = 0;
215
216 while (input.pos < input.size) {
217 Py_BEGIN_ALLOW_THREADS zresult =
218 ZSTD_decompressStream(self->dctx, &output, &input);
219 Py_END_ALLOW_THREADS
220
221 if (ZSTD_isError(zresult)) {
222 PyErr_Format(ZstdError, "zstd decompressor error: %s",
223 ZSTD_getErrorName(zresult));
224 res = NULL;
225 goto finally;
226 }
227
228 if (output.pos) {
229 writeResult = PyObject_CallMethod(dest, "write", "y#",
230 output.dst, output.pos);
231 if (NULL == writeResult) {
232 res = NULL;
233 goto finally;
234 }
235
236 Py_XDECREF(writeResult);
237 totalWrite += output.pos;
238 output.pos = 0;
239 }
240 }
241
242 Py_CLEAR(readResult);
243 }
244
245 /* Source stream is exhausted. Finish up. */
246
247 totalReadPy = PyLong_FromSsize_t(totalRead);
248 totalWritePy = PyLong_FromSsize_t(totalWrite);
249 res = PyTuple_Pack(2, totalReadPy, totalWritePy);
250 Py_DECREF(totalReadPy);
251 Py_DECREF(totalWritePy);
252
253 finally:
254 if (output.dst) {
255 PyMem_Free(output.dst);
256 }
257
258 Py_XDECREF(readResult);
259
260 return res;
261 }
262
263 PyObject *Decompressor_decompress(ZstdDecompressor *self, PyObject *args,
264 PyObject *kwargs) {
265 static char *kwlist[] = {
266 "data",
267 "max_output_size",
268 "read_across_frames",
269 "allow_extra_data",
270 NULL
271 };
272
273 Py_buffer source;
274 Py_ssize_t maxOutputSize = 0;
275
276 unsigned long long decompressedSize;
277 PyObject *readAcrossFrames = NULL;
278 PyObject *allowExtraData = NULL;
279 size_t destCapacity;
280 PyObject *result = NULL;
281 size_t zresult;
282 ZSTD_outBuffer outBuffer;
283 ZSTD_inBuffer inBuffer;
284 ZSTD_frameHeader frameHeader;
285
286 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "y*|nOO:decompress", kwlist,
287 &source, &maxOutputSize, &readAcrossFrames,
288 &allowExtraData)) {
289 return NULL;
290 }
291
292 if (readAcrossFrames ? PyObject_IsTrue(readAcrossFrames) : 0) {
293 PyErr_SetString(ZstdError,
294 "ZstdDecompressor.read_across_frames=True is not yet implemented"
295 );
296 goto finally;
297 }
298
299 if (ensure_dctx(self, 1)) {
300 goto finally;
301 }
302
303 if (ZSTD_getFrameHeader_advanced(&frameHeader, source.buf, source.len, self->format) != 0) {
304 PyErr_SetString(ZstdError,
305 "error determining content size from frame header");
306 goto finally;
307 }
308 decompressedSize = frameHeader.frameContentSize;
309 /* Special case of empty frame. */
310 if (0 == decompressedSize) {
311 result = PyBytes_FromStringAndSize("", 0);
312 goto finally;
313 }
314 /* Missing content size in frame header. */
315 if (ZSTD_CONTENTSIZE_UNKNOWN == decompressedSize) {
316 if (0 == maxOutputSize) {
317 PyErr_SetString(ZstdError,
318 "could not determine content size in frame header");
319 goto finally;
320 }
321
322 result = PyBytes_FromStringAndSize(NULL, maxOutputSize);
323 destCapacity = maxOutputSize;
324 decompressedSize = 0;
325 }
326 /* Size is recorded in frame header. */
327 else {
328 assert(SIZE_MAX >= PY_SSIZE_T_MAX);
329 if (decompressedSize > PY_SSIZE_T_MAX) {
330 PyErr_SetString(
331 ZstdError, "frame is too large to decompress on this platform");
332 goto finally;
333 }
334
335 result = PyBytes_FromStringAndSize(NULL, (Py_ssize_t)decompressedSize);
336 destCapacity = (size_t)decompressedSize;
337 }
338
339 if (!result) {
340 goto finally;
341 }
342
343 outBuffer.dst = PyBytes_AsString(result);
344 outBuffer.size = destCapacity;
345 outBuffer.pos = 0;
346
347 inBuffer.src = source.buf;
348 inBuffer.size = source.len;
349 inBuffer.pos = 0;
350
351 Py_BEGIN_ALLOW_THREADS zresult =
352 ZSTD_decompressStream(self->dctx, &outBuffer, &inBuffer);
353 Py_END_ALLOW_THREADS
354
355 if (ZSTD_isError(zresult)) {
356 PyErr_Format(ZstdError, "decompression error: %s",
357 ZSTD_getErrorName(zresult));
358 Py_CLEAR(result);
359 goto finally;
360 }
361 else if (zresult) {
362 PyErr_Format(ZstdError,
363 "decompression error: did not decompress full frame");
364 Py_CLEAR(result);
365 goto finally;
366 }
367 else if (decompressedSize && outBuffer.pos != decompressedSize) {
368 PyErr_Format(
369 ZstdError,
370 "decompression error: decompressed %zu bytes; expected %llu",
371 zresult, decompressedSize);
372 Py_CLEAR(result);
373 goto finally;
374 }
375 else if (outBuffer.pos < destCapacity) {
376 if (safe_pybytes_resize(&result, outBuffer.pos)) {
377 Py_CLEAR(result);
378 goto finally;
379 }
380 }
381 else if ((allowExtraData ? PyObject_IsTrue(allowExtraData) : 1) == 0
382 && inBuffer.pos < inBuffer.size) {
383 PyErr_Format(
384 ZstdError,
385 "compressed input contains %zu bytes of unused data, which is disallowed",
386 inBuffer.size - inBuffer.pos
387 );
388 Py_CLEAR(result);
389 goto finally;
390 }
391
392 finally:
393 PyBuffer_Release(&source);
394 return result;
395 }
396
397 static ZstdDecompressionObj *Decompressor_decompressobj(ZstdDecompressor *self,
398 PyObject *args,
399 PyObject *kwargs) {
400 static char *kwlist[] = {"write_size", "read_across_frames", NULL};
401
402 ZstdDecompressionObj *result = NULL;
403 size_t outSize = ZSTD_DStreamOutSize();
404 PyObject *readAcrossFrames = NULL;
405
406 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|kO:decompressobj", kwlist,
407 &outSize, &readAcrossFrames)) {
408 return NULL;
409 }
410
411 if (!outSize) {
412 PyErr_SetString(PyExc_ValueError, "write_size must be positive");
413 return NULL;
414 }
415
416 result = (ZstdDecompressionObj *)PyObject_CallObject(
417 (PyObject *)ZstdDecompressionObjType, NULL);
418 if (!result) {
419 return NULL;
420 }
421
422 if (ensure_dctx(self, 1)) {
423 Py_DECREF(result);
424 return NULL;
425 }
426
427 result->decompressor = self;
428 Py_INCREF(result->decompressor);
429 result->outSize = outSize;
430 result->readAcrossFrames =
431 readAcrossFrames ? PyObject_IsTrue(readAcrossFrames) : 0;
432
433 return result;
434 }
435
436 static ZstdDecompressorIterator *
437 Decompressor_read_to_iter(ZstdDecompressor *self, PyObject *args,
438 PyObject *kwargs) {
439 static char *kwlist[] = {"reader", "read_size", "write_size", "skip_bytes",
440 NULL};
441
442 PyObject *reader;
443 size_t inSize = ZSTD_DStreamInSize();
444 size_t outSize = ZSTD_DStreamOutSize();
445 ZstdDecompressorIterator *result;
446 size_t skipBytes = 0;
447
448 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|kkk:read_to_iter", kwlist,
449 &reader, &inSize, &outSize, &skipBytes)) {
450 return NULL;
451 }
452
453 if (skipBytes >= inSize) {
454 PyErr_SetString(PyExc_ValueError,
455 "skip_bytes must be smaller than read_size");
456 return NULL;
457 }
458
459 result = (ZstdDecompressorIterator *)PyObject_CallObject(
460 (PyObject *)ZstdDecompressorIteratorType, NULL);
461 if (!result) {
462 return NULL;
463 }
464
465 if (PyObject_HasAttrString(reader, "read")) {
466 result->reader = reader;
467 Py_INCREF(result->reader);
468 }
469 else if (1 == PyObject_CheckBuffer(reader)) {
470 /* Object claims it is a buffer. Try to get a handle to it. */
471 if (0 != PyObject_GetBuffer(reader, &result->buffer, PyBUF_CONTIG_RO)) {
472 goto except;
473 }
474 }
475 else {
476 PyErr_SetString(PyExc_ValueError,
477 "must pass an object with a read() method or conforms "
478 "to buffer protocol");
479 goto except;
480 }
481
482 result->decompressor = self;
483 Py_INCREF(result->decompressor);
484
485 result->inSize = inSize;
486 result->outSize = outSize;
487 result->skipBytes = skipBytes;
488
489 if (ensure_dctx(self, 1)) {
490 goto except;
491 }
492
493 result->input.src = PyMem_Malloc(inSize);
494 if (!result->input.src) {
495 PyErr_NoMemory();
496 goto except;
497 }
498
499 goto finally;
500
501 except:
502 Py_CLEAR(result);
503
504 finally:
505
506 return result;
507 }
508
509 static ZstdDecompressionReader *
510 Decompressor_stream_reader(ZstdDecompressor *self, PyObject *args,
511 PyObject *kwargs) {
512 static char *kwlist[] = {"source", "read_size", "read_across_frames",
513 "closefd", NULL};
514
515 PyObject *source;
516 size_t readSize = ZSTD_DStreamInSize();
517 PyObject *readAcrossFrames = NULL;
518 PyObject *closefd = NULL;
519 ZstdDecompressionReader *result;
520
521 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|kOO:stream_reader",
522 kwlist, &source, &readSize,
523 &readAcrossFrames, &closefd)) {
524 return NULL;
525 }
526
527 if (ensure_dctx(self, 1)) {
528 return NULL;
529 }
530
531 result = (ZstdDecompressionReader *)PyObject_CallObject(
532 (PyObject *)ZstdDecompressionReaderType, NULL);
533 if (NULL == result) {
534 return NULL;
535 }
536
537 result->entered = 0;
538 result->closed = 0;
539
540 if (PyObject_HasAttrString(source, "read")) {
541 result->reader = source;
542 Py_INCREF(source);
543 result->readSize = readSize;
544 }
545 else if (1 == PyObject_CheckBuffer(source)) {
546 if (0 != PyObject_GetBuffer(source, &result->buffer, PyBUF_CONTIG_RO)) {
547 Py_CLEAR(result);
548 return NULL;
549 }
550 }
551 else {
552 PyErr_SetString(PyExc_TypeError,
553 "must pass an object with a read() method or that "
554 "conforms to the buffer protocol");
555 Py_CLEAR(result);
556 return NULL;
557 }
558
559 result->decompressor = self;
560 Py_INCREF(self);
561 result->readAcrossFrames =
562 readAcrossFrames ? PyObject_IsTrue(readAcrossFrames) : 0;
563 result->closefd = closefd ? PyObject_IsTrue(closefd) : 1;
564
565 return result;
566 }
567
568 static ZstdDecompressionWriter *
569 Decompressor_stream_writer(ZstdDecompressor *self, PyObject *args,
570 PyObject *kwargs) {
571 static char *kwlist[] = {"writer", "write_size", "write_return_read",
572 "closefd", NULL};
573
574 PyObject *writer;
575 size_t outSize = ZSTD_DStreamOutSize();
576 PyObject *writeReturnRead = NULL;
577 PyObject *closefd = NULL;
578 ZstdDecompressionWriter *result;
579
580 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|kOO:stream_writer",
581 kwlist, &writer, &outSize,
582 &writeReturnRead, &closefd)) {
583 return NULL;
584 }
585
586 if (!PyObject_HasAttrString(writer, "write")) {
587 PyErr_SetString(PyExc_ValueError,
588 "must pass an object with a write() method");
589 return NULL;
590 }
591
592 if (ensure_dctx(self, 1)) {
593 return NULL;
594 }
595
596 result = (ZstdDecompressionWriter *)PyObject_CallObject(
597 (PyObject *)ZstdDecompressionWriterType, NULL);
598 if (!result) {
599 return NULL;
600 }
601
602 result->entered = 0;
603 result->closing = 0;
604 result->closed = 0;
605
606 result->decompressor = self;
607 Py_INCREF(result->decompressor);
608
609 result->writer = writer;
610 Py_INCREF(result->writer);
611
612 result->outSize = outSize;
613 result->writeReturnRead =
614 writeReturnRead ? PyObject_IsTrue(writeReturnRead) : 1;
615 result->closefd = closefd ? PyObject_IsTrue(closefd) : 1;
616
617 return result;
618 }
619
620 static PyObject *
621 Decompressor_decompress_content_dict_chain(ZstdDecompressor *self,
622 PyObject *args, PyObject *kwargs) {
623 static char *kwlist[] = {"frames", NULL};
624
625 PyObject *chunks;
626 Py_ssize_t chunksLen;
627 Py_ssize_t chunkIndex;
628 char parity = 0;
629 PyObject *chunk;
630 char *chunkData;
631 Py_ssize_t chunkSize;
632 size_t zresult;
633 ZSTD_frameHeader frameHeader;
634 void *buffer1 = NULL;
635 size_t buffer1Size = 0;
636 size_t buffer1ContentSize = 0;
637 void *buffer2 = NULL;
638 size_t buffer2Size = 0;
639 size_t buffer2ContentSize = 0;
640 void *destBuffer = NULL;
641 PyObject *result = NULL;
642 ZSTD_outBuffer outBuffer;
643 ZSTD_inBuffer inBuffer;
644
645 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
646 "O!:decompress_content_dict_chain", kwlist,
647 &PyList_Type, &chunks)) {
648 return NULL;
649 }
650
651 chunksLen = PyList_Size(chunks);
652 if (!chunksLen) {
653 PyErr_SetString(PyExc_ValueError, "empty input chain");
654 return NULL;
655 }
656
657 /* The first chunk should not be using a dictionary. We handle it specially.
658 */
659 chunk = PyList_GetItem(chunks, 0);
660 if (!PyBytes_Check(chunk)) {
661 PyErr_SetString(PyExc_ValueError, "chunk 0 must be bytes");
662 return NULL;
663 }
664
665 /* We require that all chunks be zstd frames and that they have content size
666 * set. */
667 PyBytes_AsStringAndSize(chunk, &chunkData, &chunkSize);
668 zresult = ZSTD_getFrameHeader(&frameHeader, (void *)chunkData, chunkSize);
669 if (ZSTD_isError(zresult)) {
670 PyErr_SetString(PyExc_ValueError, "chunk 0 is not a valid zstd frame");
671 return NULL;
672 }
673 else if (zresult) {
674 PyErr_SetString(PyExc_ValueError,
675 "chunk 0 is too small to contain a zstd frame");
676 return NULL;
677 }
678
679 if (ZSTD_CONTENTSIZE_UNKNOWN == frameHeader.frameContentSize) {
680 PyErr_SetString(PyExc_ValueError,
681 "chunk 0 missing content size in frame");
682 return NULL;
683 }
684
685 assert(ZSTD_CONTENTSIZE_ERROR != frameHeader.frameContentSize);
686
687 /* We check against PY_SSIZE_T_MAX here because we ultimately cast the
688 * result to a Python object and it's length can be no greater than
689 * Py_ssize_t. In theory, we could have an intermediate frame that is
690 * larger. But a) why would this API be used for frames that large b)
691 * it isn't worth the complexity to support. */
692 assert(SIZE_MAX >= PY_SSIZE_T_MAX);
693 if (frameHeader.frameContentSize > PY_SSIZE_T_MAX) {
694 PyErr_SetString(PyExc_ValueError,
695 "chunk 0 is too large to decompress on this platform");
696 return NULL;
697 }
698
699 if (ensure_dctx(self, 0)) {
700 goto finally;
701 }
702
703 buffer1Size = (size_t)frameHeader.frameContentSize;
704 buffer1 = PyMem_Malloc(buffer1Size);
705 if (!buffer1) {
706 goto finally;
707 }
708
709 outBuffer.dst = buffer1;
710 outBuffer.size = buffer1Size;
711 outBuffer.pos = 0;
712
713 inBuffer.src = chunkData;
714 inBuffer.size = chunkSize;
715 inBuffer.pos = 0;
716
717 Py_BEGIN_ALLOW_THREADS zresult =
718 ZSTD_decompressStream(self->dctx, &outBuffer, &inBuffer);
719 Py_END_ALLOW_THREADS if (ZSTD_isError(zresult)) {
720 PyErr_Format(ZstdError, "could not decompress chunk 0: %s",
721 ZSTD_getErrorName(zresult));
722 goto finally;
723 }
724 else if (zresult) {
725 PyErr_Format(ZstdError, "chunk 0 did not decompress full frame");
726 goto finally;
727 }
728
729 buffer1ContentSize = outBuffer.pos;
730
731 /* Special case of a simple chain. */
732 if (1 == chunksLen) {
733 result = PyBytes_FromStringAndSize(buffer1, buffer1Size);
734 goto finally;
735 }
736
737 /* This should ideally look at next chunk. But this is slightly simpler. */
738 buffer2Size = (size_t)frameHeader.frameContentSize;
739 buffer2 = PyMem_Malloc(buffer2Size);
740 if (!buffer2) {
741 goto finally;
742 }
743
744 /* For each subsequent chunk, use the previous fulltext as a content
745 dictionary. Our strategy is to have 2 buffers. One holds the previous
746 fulltext (to be used as a content dictionary) and the other holds the new
747 fulltext. The buffers grow when needed but never decrease in size. This
748 limits the memory allocator overhead.
749 */
750 for (chunkIndex = 1; chunkIndex < chunksLen; chunkIndex++) {
751 chunk = PyList_GetItem(chunks, chunkIndex);
752 if (!PyBytes_Check(chunk)) {
753 PyErr_Format(PyExc_ValueError, "chunk %zd must be bytes",
754 chunkIndex);
755 goto finally;
756 }
757
758 PyBytes_AsStringAndSize(chunk, &chunkData, &chunkSize);
759 zresult =
760 ZSTD_getFrameHeader(&frameHeader, (void *)chunkData, chunkSize);
761 if (ZSTD_isError(zresult)) {
762 PyErr_Format(PyExc_ValueError,
763 "chunk %zd is not a valid zstd frame", chunkIndex);
764 goto finally;
765 }
766 else if (zresult) {
767 PyErr_Format(PyExc_ValueError,
768 "chunk %zd is too small to contain a zstd frame",
769 chunkIndex);
770 goto finally;
771 }
772
773 if (ZSTD_CONTENTSIZE_UNKNOWN == frameHeader.frameContentSize) {
774 PyErr_Format(PyExc_ValueError,
775 "chunk %zd missing content size in frame", chunkIndex);
776 goto finally;
777 }
778
779 assert(ZSTD_CONTENTSIZE_ERROR != frameHeader.frameContentSize);
780
781 if (frameHeader.frameContentSize > PY_SSIZE_T_MAX) {
782 PyErr_Format(
783 PyExc_ValueError,
784 "chunk %zd is too large to decompress on this platform",
785 chunkIndex);
786 goto finally;
787 }
788
789 inBuffer.src = chunkData;
790 inBuffer.size = chunkSize;
791 inBuffer.pos = 0;
792
793 parity = chunkIndex % 2;
794
795 /* This could definitely be abstracted to reduce code duplication. */
796 if (parity) {
797 /* Resize destination buffer to hold larger content. */
798 if (buffer2Size < frameHeader.frameContentSize) {
799 buffer2Size = (size_t)frameHeader.frameContentSize;
800 destBuffer = PyMem_Realloc(buffer2, buffer2Size);
801 if (!destBuffer) {
802 goto finally;
803 }
804 buffer2 = destBuffer;
805 }
806
807 Py_BEGIN_ALLOW_THREADS zresult = ZSTD_DCtx_refPrefix_advanced(
808 self->dctx, buffer1, buffer1ContentSize, ZSTD_dct_rawContent);
809 Py_END_ALLOW_THREADS if (ZSTD_isError(zresult)) {
810 PyErr_Format(ZstdError,
811 "failed to load prefix dictionary at chunk %zd",
812 chunkIndex);
813 goto finally;
814 }
815
816 outBuffer.dst = buffer2;
817 outBuffer.size = buffer2Size;
818 outBuffer.pos = 0;
819
820 Py_BEGIN_ALLOW_THREADS zresult =
821 ZSTD_decompressStream(self->dctx, &outBuffer, &inBuffer);
822 Py_END_ALLOW_THREADS if (ZSTD_isError(zresult)) {
823 PyErr_Format(ZstdError, "could not decompress chunk %zd: %s",
824 chunkIndex, ZSTD_getErrorName(zresult));
825 goto finally;
826 }
827 else if (zresult) {
828 PyErr_Format(ZstdError,
829 "chunk %zd did not decompress full frame",
830 chunkIndex);
831 goto finally;
832 }
833
834 buffer2ContentSize = outBuffer.pos;
835 }
836 else {
837 if (buffer1Size < frameHeader.frameContentSize) {
838 buffer1Size = (size_t)frameHeader.frameContentSize;
839 destBuffer = PyMem_Realloc(buffer1, buffer1Size);
840 if (!destBuffer) {
841 goto finally;
842 }
843 buffer1 = destBuffer;
844 }
845
846 Py_BEGIN_ALLOW_THREADS zresult = ZSTD_DCtx_refPrefix_advanced(
847 self->dctx, buffer2, buffer2ContentSize, ZSTD_dct_rawContent);
848 Py_END_ALLOW_THREADS if (ZSTD_isError(zresult)) {
849 PyErr_Format(ZstdError,
850 "failed to load prefix dictionary at chunk %zd",
851 chunkIndex);
852 goto finally;
853 }
854
855 outBuffer.dst = buffer1;
856 outBuffer.size = buffer1Size;
857 outBuffer.pos = 0;
858
859 Py_BEGIN_ALLOW_THREADS zresult =
860 ZSTD_decompressStream(self->dctx, &outBuffer, &inBuffer);
861 Py_END_ALLOW_THREADS if (ZSTD_isError(zresult)) {
862 PyErr_Format(ZstdError, "could not decompress chunk %zd: %s",
863 chunkIndex, ZSTD_getErrorName(zresult));
864 goto finally;
865 }
866 else if (zresult) {
867 PyErr_Format(ZstdError,
868 "chunk %zd did not decompress full frame",
869 chunkIndex);
870 goto finally;
871 }
872
873 buffer1ContentSize = outBuffer.pos;
874 }
875 }
876
877 result = PyBytes_FromStringAndSize(parity ? buffer2 : buffer1,
878 parity ? buffer2ContentSize
879 : buffer1ContentSize);
880
881 finally:
882 if (buffer2) {
883 PyMem_Free(buffer2);
884 }
885 if (buffer1) {
886 PyMem_Free(buffer1);
887 }
888
889 return result;
890 }
891
892 typedef struct {
893 void *sourceData;
894 size_t sourceSize;
895 size_t destSize;
896 } FramePointer;
897
898 typedef struct {
899 FramePointer *frames;
900 Py_ssize_t framesSize;
901 unsigned long long compressedSize;
902 } FrameSources;
903
904 typedef struct {
905 void *dest;
906 Py_ssize_t destSize;
907 BufferSegment *segments;
908 Py_ssize_t segmentsSize;
909 } DecompressorDestBuffer;
910
911 typedef enum {
912 DecompressorWorkerError_none = 0,
913 DecompressorWorkerError_zstd = 1,
914 DecompressorWorkerError_memory = 2,
915 DecompressorWorkerError_sizeMismatch = 3,
916 DecompressorWorkerError_unknownSize = 4,
917 } DecompressorWorkerError;
918
919 typedef struct {
920 /* Source records and length */
921 FramePointer *framePointers;
922 /* Which records to process. */
923 Py_ssize_t startOffset;
924 Py_ssize_t endOffset;
925 unsigned long long totalSourceSize;
926
927 /* Compression state and settings. */
928 ZSTD_DCtx *dctx;
929 int requireOutputSizes;
930
931 /* Output storage. */
932 DecompressorDestBuffer *destBuffers;
933 Py_ssize_t destCount;
934
935 /* Item that error occurred on. */
936 Py_ssize_t errorOffset;
937 /* If an error occurred. */
938 DecompressorWorkerError error;
939 /* result from zstd decompression operation */
940 size_t zresult;
941 } DecompressorWorkerState;
942
943 #ifdef HAVE_ZSTD_POOL_APIS
944 static void decompress_worker(DecompressorWorkerState *state) {
945 size_t allocationSize;
946 DecompressorDestBuffer *destBuffer;
947 Py_ssize_t frameIndex;
948 Py_ssize_t localOffset = 0;
949 Py_ssize_t currentBufferStartIndex = state->startOffset;
950 Py_ssize_t remainingItems = state->endOffset - state->startOffset + 1;
951 void *tmpBuf;
952 Py_ssize_t destOffset = 0;
953 FramePointer *framePointers = state->framePointers;
954 size_t zresult;
955
956 assert(NULL == state->destBuffers);
957 assert(0 == state->destCount);
958 assert(state->endOffset - state->startOffset >= 0);
959
960 /* We could get here due to the way work is allocated. Ideally we wouldn't
961 get here. But that would require a bit of a refactor in the caller. */
962 if (state->totalSourceSize > SIZE_MAX) {
963 state->error = DecompressorWorkerError_memory;
964 state->errorOffset = 0;
965 return;
966 }
967
968 /*
969 * We need to allocate a buffer to hold decompressed data. How we do this
970 * depends on what we know about the output. The following scenarios are
971 * possible:
972 *
973 * 1. All structs defining frames declare the output size.
974 * 2. The decompressed size is embedded within the zstd frame.
975 * 3. The decompressed size is not stored anywhere.
976 *
977 * For now, we only support #1 and #2.
978 */
979
980 /* Resolve ouput segments. */
981 for (frameIndex = state->startOffset; frameIndex <= state->endOffset;
982 frameIndex++) {
983 FramePointer *fp = &framePointers[frameIndex];
984 unsigned long long decompressedSize;
985
986 if (0 == fp->destSize) {
987 decompressedSize =
988 ZSTD_getFrameContentSize(fp->sourceData, fp->sourceSize);
989
990 if (ZSTD_CONTENTSIZE_ERROR == decompressedSize) {
991 state->error = DecompressorWorkerError_unknownSize;
992 state->errorOffset = frameIndex;
993 return;
994 }
995 else if (ZSTD_CONTENTSIZE_UNKNOWN == decompressedSize) {
996 if (state->requireOutputSizes) {
997 state->error = DecompressorWorkerError_unknownSize;
998 state->errorOffset = frameIndex;
999 return;
1000 }
1001
1002 /* This will fail the assert for .destSize > 0 below. */
1003 decompressedSize = 0;
1004 }
1005
1006 if (decompressedSize > SIZE_MAX) {
1007 state->error = DecompressorWorkerError_memory;
1008 state->errorOffset = frameIndex;
1009 return;
1010 }
1011
1012 fp->destSize = (size_t)decompressedSize;
1013 }
1014 }
1015
1016 state->destBuffers = calloc(1, sizeof(DecompressorDestBuffer));
1017 if (NULL == state->destBuffers) {
1018 state->error = DecompressorWorkerError_memory;
1019 return;
1020 }
1021
1022 state->destCount = 1;
1023
1024 destBuffer = &state->destBuffers[state->destCount - 1];
1025
1026 assert(framePointers[state->startOffset].destSize > 0); /* For now. */
1027
1028 allocationSize = roundpow2((size_t)state->totalSourceSize);
1029
1030 if (framePointers[state->startOffset].destSize > allocationSize) {
1031 allocationSize = roundpow2(framePointers[state->startOffset].destSize);
1032 }
1033
1034 destBuffer->dest = malloc(allocationSize);
1035 if (NULL == destBuffer->dest) {
1036 state->error = DecompressorWorkerError_memory;
1037 return;
1038 }
1039
1040 destBuffer->destSize = allocationSize;
1041
1042 destBuffer->segments = calloc(remainingItems, sizeof(BufferSegment));
1043 if (NULL == destBuffer->segments) {
1044 /* Caller will free state->dest as part of cleanup. */
1045 state->error = DecompressorWorkerError_memory;
1046 return;
1047 }
1048
1049 destBuffer->segmentsSize = remainingItems;
1050
1051 for (frameIndex = state->startOffset; frameIndex <= state->endOffset;
1052 frameIndex++) {
1053 ZSTD_outBuffer outBuffer;
1054 ZSTD_inBuffer inBuffer;
1055 const void *source = framePointers[frameIndex].sourceData;
1056 const size_t sourceSize = framePointers[frameIndex].sourceSize;
1057 void *dest;
1058 const size_t decompressedSize = framePointers[frameIndex].destSize;
1059 size_t destAvailable = destBuffer->destSize - destOffset;
1060
1061 assert(decompressedSize > 0); /* For now. */
1062
1063 /*
1064 * Not enough space in current buffer. Finish current before and
1065 * allocate and switch to a new one.
1066 */
1067 if (decompressedSize > destAvailable) {
1068 /*
1069 * Shrinking the destination buffer is optional. But it should be
1070 * cheap, so we just do it.
1071 */
1072 if (destAvailable) {
1073 tmpBuf = realloc(destBuffer->dest, destOffset);
1074 if (NULL == tmpBuf) {
1075 state->error = DecompressorWorkerError_memory;
1076 return;
1077 }
1078
1079 destBuffer->dest = tmpBuf;
1080 destBuffer->destSize = destOffset;
1081 }
1082
1083 /* Truncate segments buffer. */
1084 tmpBuf = realloc(destBuffer->segments,
1085 (frameIndex - currentBufferStartIndex) *
1086 sizeof(BufferSegment));
1087 if (NULL == tmpBuf) {
1088 state->error = DecompressorWorkerError_memory;
1089 return;
1090 }
1091
1092 destBuffer->segments = tmpBuf;
1093 destBuffer->segmentsSize = frameIndex - currentBufferStartIndex;
1094
1095 /* Grow space for new DestBuffer. */
1096 tmpBuf =
1097 realloc(state->destBuffers, (state->destCount + 1) *
1098 sizeof(DecompressorDestBuffer));
1099 if (NULL == tmpBuf) {
1100 state->error = DecompressorWorkerError_memory;
1101 return;
1102 }
1103
1104 state->destBuffers = tmpBuf;
1105 state->destCount++;
1106
1107 destBuffer = &state->destBuffers[state->destCount - 1];
1108
1109 /* Don't take any chances will non-NULL pointers. */
1110 memset(destBuffer, 0, sizeof(DecompressorDestBuffer));
1111
1112 allocationSize = roundpow2((size_t)state->totalSourceSize);
1113
1114 if (decompressedSize > allocationSize) {
1115 allocationSize = roundpow2(decompressedSize);
1116 }
1117
1118 destBuffer->dest = malloc(allocationSize);
1119 if (NULL == destBuffer->dest) {
1120 state->error = DecompressorWorkerError_memory;
1121 return;
1122 }
1123
1124 destBuffer->destSize = allocationSize;
1125 destAvailable = allocationSize;
1126 destOffset = 0;
1127 localOffset = 0;
1128
1129 destBuffer->segments =
1130 calloc(remainingItems, sizeof(BufferSegment));
1131 if (NULL == destBuffer->segments) {
1132 state->error = DecompressorWorkerError_memory;
1133 return;
1134 }
1135
1136 destBuffer->segmentsSize = remainingItems;
1137 currentBufferStartIndex = frameIndex;
1138 }
1139
1140 dest = (char *)destBuffer->dest + destOffset;
1141
1142 outBuffer.dst = dest;
1143 outBuffer.size = decompressedSize;
1144 outBuffer.pos = 0;
1145
1146 inBuffer.src = source;
1147 inBuffer.size = sourceSize;
1148 inBuffer.pos = 0;
1149
1150 zresult = ZSTD_decompressStream(state->dctx, &outBuffer, &inBuffer);
1151 if (ZSTD_isError(zresult)) {
1152 state->error = DecompressorWorkerError_zstd;
1153 state->zresult = zresult;
1154 state->errorOffset = frameIndex;
1155 return;
1156 }
1157 else if (zresult || outBuffer.pos != decompressedSize) {
1158 state->error = DecompressorWorkerError_sizeMismatch;
1159 state->zresult = outBuffer.pos;
1160 state->errorOffset = frameIndex;
1161 return;
1162 }
1163
1164 destBuffer->segments[localOffset].offset = destOffset;
1165 destBuffer->segments[localOffset].length = outBuffer.pos;
1166 destOffset += outBuffer.pos;
1167 localOffset++;
1168 remainingItems--;
1169 }
1170
1171 if (destBuffer->destSize > destOffset) {
1172 tmpBuf = realloc(destBuffer->dest, destOffset);
1173 if (NULL == tmpBuf) {
1174 state->error = DecompressorWorkerError_memory;
1175 return;
1176 }
1177
1178 destBuffer->dest = tmpBuf;
1179 destBuffer->destSize = destOffset;
1180 }
1181 }
1182 #endif
1183
1184 #ifdef HAVE_ZSTD_POOL_APIS
1185 ZstdBufferWithSegmentsCollection *
1186 decompress_from_framesources(ZstdDecompressor *decompressor,
1187 FrameSources *frames, Py_ssize_t threadCount) {
1188 Py_ssize_t i = 0;
1189 int errored = 0;
1190 Py_ssize_t segmentsCount;
1191 ZstdBufferWithSegments *bws = NULL;
1192 PyObject *resultArg = NULL;
1193 Py_ssize_t resultIndex;
1194 ZstdBufferWithSegmentsCollection *result = NULL;
1195 FramePointer *framePointers = frames->frames;
1196 unsigned long long workerBytes = 0;
1197 Py_ssize_t currentThread = 0;
1198 Py_ssize_t workerStartOffset = 0;
1199 POOL_ctx *pool = NULL;
1200 DecompressorWorkerState *workerStates = NULL;
1201 unsigned long long bytesPerWorker;
1202
1203 /* Caller should normalize 0 and negative values to 1 or larger. */
1204 assert(threadCount >= 1);
1205
1206 /* More threads than inputs makes no sense under any conditions. */
1207 threadCount =
1208 frames->framesSize < threadCount ? frames->framesSize : threadCount;
1209
1210 /* TODO lower thread count if input size is too small and threads would just
1211 add overhead. */
1212
1213 if (decompressor->dict) {
1214 if (ensure_ddict(decompressor->dict)) {
1215 return NULL;
1216 }
1217 }
1218
1219 /* If threadCount==1, we don't start a thread pool. But we do leverage the
1220 same API for dispatching work. */
1221 workerStates = PyMem_Malloc(threadCount * sizeof(DecompressorWorkerState));
1222 if (NULL == workerStates) {
1223 PyErr_NoMemory();
1224 goto finally;
1225 }
1226
1227 memset(workerStates, 0, threadCount * sizeof(DecompressorWorkerState));
1228
1229 if (threadCount > 1) {
1230 pool = POOL_create(threadCount, 1);
1231 if (NULL == pool) {
1232 PyErr_SetString(ZstdError, "could not initialize zstd thread pool");
1233 goto finally;
1234 }
1235 }
1236
1237 bytesPerWorker = frames->compressedSize / threadCount;
1238
1239 if (bytesPerWorker > SIZE_MAX) {
1240 PyErr_SetString(ZstdError,
1241 "too much data per worker for this platform");
1242 goto finally;
1243 }
1244
1245 for (i = 0; i < threadCount; i++) {
1246 size_t zresult;
1247
1248 workerStates[i].dctx = ZSTD_createDCtx();
1249 if (NULL == workerStates[i].dctx) {
1250 PyErr_NoMemory();
1251 goto finally;
1252 }
1253
1254 if (decompressor->dict) {
1255 zresult = ZSTD_DCtx_refDDict(workerStates[i].dctx,
1256 decompressor->dict->ddict);
1257 if (zresult) {
1258 PyErr_Format(ZstdError,
1259 "unable to reference prepared dictionary: %s",
1260 ZSTD_getErrorName(zresult));
1261 goto finally;
1262 }
1263 }
1264
1265 workerStates[i].framePointers = framePointers;
1266 workerStates[i].requireOutputSizes = 1;
1267 }
1268
1269 Py_BEGIN_ALLOW_THREADS
1270 /* There are many ways to split work among workers.
1271
1272 For now, we take a simple approach of splitting work so each worker
1273 gets roughly the same number of input bytes. This will result in more
1274 starvation than running N>threadCount jobs. But it avoids
1275 complications around state tracking, which could involve extra
1276 locking.
1277 */
1278 for (i = 0; i < frames->framesSize; i++) {
1279 workerBytes += frames->frames[i].sourceSize;
1280
1281 /*
1282 * The last worker/thread needs to handle all remaining work. Don't
1283 * trigger it prematurely. Defer to the block outside of the loop.
1284 * (But still process this loop so workerBytes is correct.
1285 */
1286 if (currentThread == threadCount - 1) {
1287 continue;
1288 }
1289
1290 if (workerBytes >= bytesPerWorker) {
1291 workerStates[currentThread].startOffset = workerStartOffset;
1292 workerStates[currentThread].endOffset = i;
1293 workerStates[currentThread].totalSourceSize = workerBytes;
1294
1295 if (threadCount > 1) {
1296 POOL_add(pool, (POOL_function)decompress_worker,
1297 &workerStates[currentThread]);
1298 }
1299 else {
1300 decompress_worker(&workerStates[currentThread]);
1301 }
1302 currentThread++;
1303 workerStartOffset = i + 1;
1304 workerBytes = 0;
1305 }
1306 }
1307
1308 if (workerBytes) {
1309 workerStates[currentThread].startOffset = workerStartOffset;
1310 workerStates[currentThread].endOffset = frames->framesSize - 1;
1311 workerStates[currentThread].totalSourceSize = workerBytes;
1312
1313 if (threadCount > 1) {
1314 POOL_add(pool, (POOL_function)decompress_worker,
1315 &workerStates[currentThread]);
1316 }
1317 else {
1318 decompress_worker(&workerStates[currentThread]);
1319 }
1320 }
1321
1322 if (threadCount > 1) {
1323 POOL_free(pool);
1324 pool = NULL;
1325 }
1326 Py_END_ALLOW_THREADS
1327
1328 for (i = 0; i < threadCount; i++) {
1329 switch (workerStates[i].error) {
1330 case DecompressorWorkerError_none:
1331 break;
1332
1333 case DecompressorWorkerError_zstd:
1334 PyErr_Format(ZstdError, "error decompressing item %zd: %s",
1335 workerStates[i].errorOffset,
1336 ZSTD_getErrorName(workerStates[i].zresult));
1337 errored = 1;
1338 break;
1339
1340 case DecompressorWorkerError_memory:
1341 PyErr_NoMemory();
1342 errored = 1;
1343 break;
1344
1345 case DecompressorWorkerError_sizeMismatch:
1346 PyErr_Format(ZstdError,
1347 "error decompressing item %zd: decompressed %zu "
1348 "bytes; expected %zu",
1349 workerStates[i].errorOffset, workerStates[i].zresult,
1350 framePointers[workerStates[i].errorOffset].destSize);
1351 errored = 1;
1352 break;
1353
1354 case DecompressorWorkerError_unknownSize:
1355 PyErr_Format(PyExc_ValueError,
1356 "could not determine decompressed size of item %zd",
1357 workerStates[i].errorOffset);
1358 errored = 1;
1359 break;
1360
1361 default:
1362 PyErr_Format(ZstdError, "unhandled error type: %d; this is a bug",
1363 workerStates[i].error);
1364 errored = 1;
1365 break;
1366 }
1367
1368 if (errored) {
1369 break;
1370 }
1371 }
1372
1373 if (errored) {
1374 goto finally;
1375 }
1376
1377 segmentsCount = 0;
1378 for (i = 0; i < threadCount; i++) {
1379 segmentsCount += workerStates[i].destCount;
1380 }
1381
1382 resultArg = PyTuple_New(segmentsCount);
1383 if (NULL == resultArg) {
1384 goto finally;
1385 }
1386
1387 resultIndex = 0;
1388
1389 for (i = 0; i < threadCount; i++) {
1390 Py_ssize_t bufferIndex;
1391 DecompressorWorkerState *state = &workerStates[i];
1392
1393 for (bufferIndex = 0; bufferIndex < state->destCount; bufferIndex++) {
1394 DecompressorDestBuffer *destBuffer =
1395 &state->destBuffers[bufferIndex];
1396
1397 bws = BufferWithSegments_FromMemory(
1398 destBuffer->dest, destBuffer->destSize, destBuffer->segments,
1399 destBuffer->segmentsSize);
1400 if (NULL == bws) {
1401 goto finally;
1402 }
1403
1404 /*
1405 * Memory for buffer and segments was allocated using malloc() in
1406 * worker and the memory is transferred to the BufferWithSegments
1407 * instance. So tell instance to use free() and NULL the reference
1408 * in the state struct so it isn't freed below.
1409 */
1410 bws->useFree = 1;
1411 destBuffer->dest = NULL;
1412 destBuffer->segments = NULL;
1413
1414 PyTuple_SET_ITEM(resultArg, resultIndex++, (PyObject *)bws);
1415 }
1416 }
1417
1418 result = (ZstdBufferWithSegmentsCollection *)PyObject_CallObject(
1419 (PyObject *)ZstdBufferWithSegmentsCollectionType, resultArg);
1420
1421 finally:
1422 Py_CLEAR(resultArg);
1423
1424 if (workerStates) {
1425 for (i = 0; i < threadCount; i++) {
1426 Py_ssize_t bufferIndex;
1427 DecompressorWorkerState *state = &workerStates[i];
1428
1429 if (state->dctx) {
1430 ZSTD_freeDCtx(state->dctx);
1431 }
1432
1433 for (bufferIndex = 0; bufferIndex < state->destCount;
1434 bufferIndex++) {
1435 if (state->destBuffers) {
1436 /*
1437 * Will be NULL if memory transfered to a
1438 * BufferWithSegments. Otherwise it is left over after an
1439 * error occurred.
1440 */
1441 free(state->destBuffers[bufferIndex].dest);
1442 free(state->destBuffers[bufferIndex].segments);
1443 }
1444 }
1445
1446 free(state->destBuffers);
1447 }
1448
1449 PyMem_Free(workerStates);
1450 }
1451
1452 POOL_free(pool);
1453
1454 return result;
1455 }
1456 #endif
1457
1458 #ifdef HAVE_ZSTD_POOL_APIS
1459 static ZstdBufferWithSegmentsCollection *
1460 Decompressor_multi_decompress_to_buffer(ZstdDecompressor *self, PyObject *args,
1461 PyObject *kwargs) {
1462 static char *kwlist[] = {"frames", "decompressed_sizes", "threads", NULL};
1463
1464 PyObject *frames;
1465 Py_buffer frameSizes;
1466 int threads = 0;
1467 Py_ssize_t frameCount;
1468 Py_buffer *frameBuffers = NULL;
1469 FramePointer *framePointers = NULL;
1470 unsigned long long *frameSizesP = NULL;
1471 unsigned long long totalInputSize = 0;
1472 FrameSources frameSources;
1473 ZstdBufferWithSegmentsCollection *result = NULL;
1474 Py_ssize_t i;
1475
1476 memset(&frameSizes, 0, sizeof(frameSizes));
1477
1478 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
1479 "O|y*i:multi_decompress_to_buffer", kwlist,
1480 &frames, &frameSizes, &threads)) {
1481 return NULL;
1482 }
1483
1484 if (frameSizes.buf) {
1485 frameSizesP = (unsigned long long *)frameSizes.buf;
1486 }
1487
1488 if (threads < 0) {
1489 threads = cpu_count();
1490 }
1491
1492 if (threads < 2) {
1493 threads = 1;
1494 }
1495
1496 if (PyObject_TypeCheck(frames, ZstdBufferWithSegmentsType)) {
1497 ZstdBufferWithSegments *buffer = (ZstdBufferWithSegments *)frames;
1498 frameCount = buffer->segmentCount;
1499
1500 if (frameSizes.buf &&
1501 frameSizes.len !=
1502 frameCount * (Py_ssize_t)sizeof(unsigned long long)) {
1503 PyErr_Format(
1504 PyExc_ValueError,
1505 "decompressed_sizes size mismatch; expected %zd, got %zd",
1506 frameCount * sizeof(unsigned long long), frameSizes.len);
1507 goto finally;
1508 }
1509
1510 framePointers = PyMem_Malloc(frameCount * sizeof(FramePointer));
1511 if (!framePointers) {
1512 PyErr_NoMemory();
1513 goto finally;
1514 }
1515
1516 for (i = 0; i < frameCount; i++) {
1517 void *sourceData;
1518 unsigned long long sourceSize;
1519 unsigned long long decompressedSize = 0;
1520
1521 if (buffer->segments[i].offset + buffer->segments[i].length >
1522 buffer->dataSize) {
1523 PyErr_Format(PyExc_ValueError,
1524 "item %zd has offset outside memory area", i);
1525 goto finally;
1526 }
1527
1528 sourceData = (char *)buffer->data + buffer->segments[i].offset;
1529 sourceSize = buffer->segments[i].length;
1530 totalInputSize += sourceSize;
1531
1532 if (frameSizesP) {
1533 decompressedSize = frameSizesP[i];
1534 }
1535
1536 if (sourceSize > SIZE_MAX) {
1537 PyErr_Format(PyExc_ValueError,
1538 "item %zd is too large for this platform", i);
1539 goto finally;
1540 }
1541
1542 if (decompressedSize > SIZE_MAX) {
1543 PyErr_Format(PyExc_ValueError,
1544 "decompressed size of item %zd is too large for "
1545 "this platform",
1546 i);
1547 goto finally;
1548 }
1549
1550 framePointers[i].sourceData = sourceData;
1551 framePointers[i].sourceSize = (size_t)sourceSize;
1552 framePointers[i].destSize = (size_t)decompressedSize;
1553 }
1554 }
1555 else if (PyObject_TypeCheck(frames, ZstdBufferWithSegmentsCollectionType)) {
1556 Py_ssize_t offset = 0;
1557 ZstdBufferWithSegments *buffer;
1558 ZstdBufferWithSegmentsCollection *collection =
1559 (ZstdBufferWithSegmentsCollection *)frames;
1560
1561 frameCount = BufferWithSegmentsCollection_length(collection);
1562
1563 if (frameSizes.buf && frameSizes.len != frameCount) {
1564 PyErr_Format(
1565 PyExc_ValueError,
1566 "decompressed_sizes size mismatch; expected %zd; got %zd",
1567 frameCount * sizeof(unsigned long long), frameSizes.len);
1568 goto finally;
1569 }
1570
1571 framePointers = PyMem_Malloc(frameCount * sizeof(FramePointer));
1572 if (NULL == framePointers) {
1573 PyErr_NoMemory();
1574 goto finally;
1575 }
1576
1577 /* Iterate the data structure directly because it is faster. */
1578 for (i = 0; i < collection->bufferCount; i++) {
1579 Py_ssize_t segmentIndex;
1580 buffer = collection->buffers[i];
1581
1582 for (segmentIndex = 0; segmentIndex < buffer->segmentCount;
1583 segmentIndex++) {
1584 unsigned long long decompressedSize =
1585 frameSizesP ? frameSizesP[offset] : 0;
1586
1587 if (buffer->segments[segmentIndex].offset +
1588 buffer->segments[segmentIndex].length >
1589 buffer->dataSize) {
1590 PyErr_Format(PyExc_ValueError,
1591 "item %zd has offset outside memory area",
1592 offset);
1593 goto finally;
1594 }
1595
1596 if (buffer->segments[segmentIndex].length > SIZE_MAX) {
1597 PyErr_Format(
1598 PyExc_ValueError,
1599 "item %zd in buffer %zd is too large for this platform",
1600 segmentIndex, i);
1601 goto finally;
1602 }
1603
1604 if (decompressedSize > SIZE_MAX) {
1605 PyErr_Format(PyExc_ValueError,
1606 "decompressed size of item %zd in buffer %zd "
1607 "is too large for this platform",
1608 segmentIndex, i);
1609 goto finally;
1610 }
1611
1612 totalInputSize += buffer->segments[segmentIndex].length;
1613
1614 framePointers[offset].sourceData =
1615 (char *)buffer->data +
1616 buffer->segments[segmentIndex].offset;
1617 framePointers[offset].sourceSize =
1618 (size_t)buffer->segments[segmentIndex].length;
1619 framePointers[offset].destSize = (size_t)decompressedSize;
1620
1621 offset++;
1622 }
1623 }
1624 }
1625 else if (PyList_Check(frames)) {
1626 frameCount = PyList_GET_SIZE(frames);
1627
1628 if (frameSizes.buf &&
1629 frameSizes.len !=
1630 frameCount * (Py_ssize_t)sizeof(unsigned long long)) {
1631 PyErr_Format(
1632 PyExc_ValueError,
1633 "decompressed_sizes size mismatch; expected %zd, got %zd",
1634 frameCount * sizeof(unsigned long long), frameSizes.len);
1635 goto finally;
1636 }
1637
1638 framePointers = PyMem_Malloc(frameCount * sizeof(FramePointer));
1639 if (!framePointers) {
1640 PyErr_NoMemory();
1641 goto finally;
1642 }
1643
1644 frameBuffers = PyMem_Malloc(frameCount * sizeof(Py_buffer));
1645 if (NULL == frameBuffers) {
1646 PyErr_NoMemory();
1647 goto finally;
1648 }
1649
1650 memset(frameBuffers, 0, frameCount * sizeof(Py_buffer));
1651
1652 /* Do a pass to assemble info about our input buffers and output sizes.
1653 */
1654 for (i = 0; i < frameCount; i++) {
1655 unsigned long long decompressedSize =
1656 frameSizesP ? frameSizesP[i] : 0;
1657
1658 if (0 != PyObject_GetBuffer(PyList_GET_ITEM(frames, i),
1659 &frameBuffers[i], PyBUF_CONTIG_RO)) {
1660 PyErr_Clear();
1661 PyErr_Format(PyExc_TypeError,
1662 "item %zd not a bytes like object", i);
1663 goto finally;
1664 }
1665
1666 if (decompressedSize > SIZE_MAX) {
1667 PyErr_Format(PyExc_ValueError,
1668 "decompressed size of item %zd is too large for "
1669 "this platform",
1670 i);
1671 goto finally;
1672 }
1673
1674 totalInputSize += frameBuffers[i].len;
1675
1676 framePointers[i].sourceData = frameBuffers[i].buf;
1677 framePointers[i].sourceSize = frameBuffers[i].len;
1678 framePointers[i].destSize = (size_t)decompressedSize;
1679 }
1680 }
1681 else {
1682 PyErr_SetString(PyExc_TypeError,
1683 "argument must be list or BufferWithSegments");
1684 goto finally;
1685 }
1686
1687 /* We now have an array with info about our inputs and outputs. Feed it into
1688 our generic decompression function. */
1689 frameSources.frames = framePointers;
1690 frameSources.framesSize = frameCount;
1691 frameSources.compressedSize = totalInputSize;
1692
1693 result = decompress_from_framesources(self, &frameSources, threads);
1694
1695 finally:
1696 if (frameSizes.buf) {
1697 PyBuffer_Release(&frameSizes);
1698 }
1699 PyMem_Free(framePointers);
1700
1701 if (frameBuffers) {
1702 for (i = 0; i < frameCount; i++) {
1703 PyBuffer_Release(&frameBuffers[i]);
1704 }
1705
1706 PyMem_Free(frameBuffers);
1707 }
1708
1709 return result;
1710 }
1711 #endif
1712
1713 static PyMethodDef Decompressor_methods[] = {
1714 {"copy_stream", (PyCFunction)Decompressor_copy_stream,
1715 METH_VARARGS | METH_KEYWORDS, NULL},
1716 {"decompress", (PyCFunction)Decompressor_decompress,
1717 METH_VARARGS | METH_KEYWORDS, NULL},
1718 {"decompressobj", (PyCFunction)Decompressor_decompressobj,
1719 METH_VARARGS | METH_KEYWORDS, NULL},
1720 {"read_to_iter", (PyCFunction)Decompressor_read_to_iter,
1721 METH_VARARGS | METH_KEYWORDS, NULL},
1722 {"stream_reader", (PyCFunction)Decompressor_stream_reader,
1723 METH_VARARGS | METH_KEYWORDS, NULL},
1724 {"stream_writer", (PyCFunction)Decompressor_stream_writer,
1725 METH_VARARGS | METH_KEYWORDS, NULL},
1726 {"decompress_content_dict_chain",
1727 (PyCFunction)Decompressor_decompress_content_dict_chain,
1728 METH_VARARGS | METH_KEYWORDS, NULL},
1729 #ifdef HAVE_ZSTD_POOL_APIS
1730 {"multi_decompress_to_buffer",
1731 (PyCFunction)Decompressor_multi_decompress_to_buffer,
1732 METH_VARARGS | METH_KEYWORDS, NULL},
1733 #endif
1734 {"memory_size", (PyCFunction)Decompressor_memory_size, METH_NOARGS, NULL},
1735 {NULL, NULL}};
1736
1737 PyType_Slot ZstdDecompressorSlots[] = {
1738 {Py_tp_dealloc, Decompressor_dealloc},
1739 {Py_tp_methods, Decompressor_methods},
1740 {Py_tp_init, Decompressor_init},
1741 {Py_tp_new, PyType_GenericNew},
1742 {0, NULL},
1743 };
1744
1745 PyType_Spec ZstdDecompressorSpec = {
1746 "zstandard.backend_c.ZstdDecompressor",
1747 sizeof(ZstdDecompressor),
1748 0,
1749 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
1750 ZstdDecompressorSlots,
1751 };
1752
1753 PyTypeObject *ZstdDecompressorType;
1754
1755 void decompressor_module_init(PyObject *mod) {
1756 ZstdDecompressorType =
1757 (PyTypeObject *)PyType_FromSpec(&ZstdDecompressorSpec);
1758 if (PyType_Ready(ZstdDecompressorType) < 0) {
1759 return;
1760 }
1761
1762 Py_INCREF((PyObject *)ZstdDecompressorType);
1763 PyModule_AddObject(mod, "ZstdDecompressor",
1764 (PyObject *)ZstdDecompressorType);
1765 }