blob: 1217ed4d1c091f18a5a2e538147163e56efcac06 [file] [log] [blame]
Nadeem Vawda59bb0e02011-12-01 01:18:27 +02001/* _lzma - Low-level Python interface to liblzma.
2
3 Initial implementation by Per Øyvind Karlsen.
4 Rewritten by Nadeem Vawda.
5
6*/
Nadeem Vawda3ff069e2011-11-30 00:25:06 +02007
8#define PY_SSIZE_T_CLEAN
9
10#include "Python.h"
11#include "structmember.h"
12#ifdef WITH_THREAD
13#include "pythread.h"
14#endif
15
16#include <stdarg.h>
17#include <string.h>
18
19#include <lzma.h>
20
21
22#ifndef PY_LONG_LONG
23#error "This module requires PY_LONG_LONG to be defined"
24#endif
25
26
27#ifdef WITH_THREAD
28#define ACQUIRE_LOCK(obj) do { \
29 if (!PyThread_acquire_lock((obj)->lock, 0)) { \
30 Py_BEGIN_ALLOW_THREADS \
31 PyThread_acquire_lock((obj)->lock, 1); \
32 Py_END_ALLOW_THREADS \
33 } } while (0)
34#define RELEASE_LOCK(obj) PyThread_release_lock((obj)->lock)
35#else
36#define ACQUIRE_LOCK(obj)
37#define RELEASE_LOCK(obj)
38#endif
39
40
41/* Container formats: */
42enum {
43 FORMAT_AUTO,
44 FORMAT_XZ,
45 FORMAT_ALONE,
46 FORMAT_RAW,
47};
48
49#define LZMA_CHECK_UNKNOWN (LZMA_CHECK_ID_MAX + 1)
50
51
52typedef struct {
53 PyObject_HEAD
Victor Stinner5064a522013-07-07 16:50:27 +020054 lzma_allocator alloc;
Nadeem Vawda3ff069e2011-11-30 00:25:06 +020055 lzma_stream lzs;
56 int flushed;
57#ifdef WITH_THREAD
58 PyThread_type_lock lock;
59#endif
60} Compressor;
61
62typedef struct {
63 PyObject_HEAD
Victor Stinner5064a522013-07-07 16:50:27 +020064 lzma_allocator alloc;
Nadeem Vawda3ff069e2011-11-30 00:25:06 +020065 lzma_stream lzs;
66 int check;
67 char eof;
68 PyObject *unused_data;
69#ifdef WITH_THREAD
70 PyThread_type_lock lock;
71#endif
72} Decompressor;
73
74/* LZMAError class object. */
75static PyObject *Error;
76
77/* An empty tuple, used by the filter specifier parsing code. */
78static PyObject *empty_tuple;
79
80
81/* Helper functions. */
82
83static int
84catch_lzma_error(lzma_ret lzret)
85{
86 switch (lzret) {
87 case LZMA_OK:
88 case LZMA_GET_CHECK:
89 case LZMA_NO_CHECK:
90 case LZMA_STREAM_END:
91 return 0;
92 case LZMA_UNSUPPORTED_CHECK:
93 PyErr_SetString(Error, "Unsupported integrity check");
94 return 1;
95 case LZMA_MEM_ERROR:
96 PyErr_NoMemory();
97 return 1;
98 case LZMA_MEMLIMIT_ERROR:
99 PyErr_SetString(Error, "Memory usage limit exceeded");
100 return 1;
101 case LZMA_FORMAT_ERROR:
102 PyErr_SetString(Error, "Input format not supported by decoder");
103 return 1;
104 case LZMA_OPTIONS_ERROR:
105 PyErr_SetString(Error, "Invalid or unsupported options");
106 return 1;
107 case LZMA_DATA_ERROR:
108 PyErr_SetString(Error, "Corrupt input data");
109 return 1;
110 case LZMA_BUF_ERROR:
111 PyErr_SetString(Error, "Insufficient buffer space");
112 return 1;
113 case LZMA_PROG_ERROR:
114 PyErr_SetString(Error, "Internal error");
115 return 1;
116 default:
117 PyErr_Format(Error, "Unrecognized error from liblzma: %d", lzret);
118 return 1;
119 }
120}
121
Victor Stinner5064a522013-07-07 16:50:27 +0200122static void*
123PyLzma_Malloc(void *opaque, size_t items, size_t size)
124{
125 if (items > (size_t)PY_SSIZE_T_MAX / size)
126 return NULL;
127 /* PyMem_Malloc() cannot be used:
128 the GIL is not held when lzma_code() is called */
129 return PyMem_RawMalloc(items * size);
130}
131
132static void
133PyLzma_Free(void *opaque, void *ptr)
134{
Victor Stinnerb7f1f652013-07-07 17:10:34 +0200135 PyMem_RawFree(ptr);
Victor Stinner5064a522013-07-07 16:50:27 +0200136}
137
Nadeem Vawda3ff069e2011-11-30 00:25:06 +0200138#if BUFSIZ < 8192
139#define INITIAL_BUFFER_SIZE 8192
140#else
141#define INITIAL_BUFFER_SIZE BUFSIZ
142#endif
143
144static int
145grow_buffer(PyObject **buf)
146{
147 size_t size = PyBytes_GET_SIZE(*buf);
148 return _PyBytes_Resize(buf, size + (size >> 3) + 6);
149}
150
151
152/* Some custom type conversions for PyArg_ParseTupleAndKeywords(),
153 since the predefined conversion specifiers do not suit our needs:
154
155 uint32_t - the "I" (unsigned int) specifier is the right size, but
156 silently ignores overflows on conversion.
157
Nadeem Vawdaf55b3292012-05-06 23:01:27 +0200158 lzma_vli - the "K" (unsigned PY_LONG_LONG) specifier is the right
159 size, but like "I" it silently ignores overflows on conversion.
160
Nadeem Vawda3ff069e2011-11-30 00:25:06 +0200161 lzma_mode and lzma_match_finder - these are enumeration types, and
162 so the size of each is implementation-defined. Worse, different
163 enum types can be of different sizes within the same program, so
164 to be strictly correct, we need to define two separate converters.
165 */
166
167#define INT_TYPE_CONVERTER_FUNC(TYPE, FUNCNAME) \
168 static int \
169 FUNCNAME(PyObject *obj, void *ptr) \
170 { \
Nadeem Vawdaf55b3292012-05-06 23:01:27 +0200171 unsigned PY_LONG_LONG val; \
Nadeem Vawda3ff069e2011-11-30 00:25:06 +0200172 \
Nadeem Vawdaf55b3292012-05-06 23:01:27 +0200173 val = PyLong_AsUnsignedLongLong(obj); \
Nadeem Vawda3ff069e2011-11-30 00:25:06 +0200174 if (PyErr_Occurred()) \
175 return 0; \
Nadeem Vawdaf55b3292012-05-06 23:01:27 +0200176 if ((unsigned PY_LONG_LONG)(TYPE)val != val) { \
Nadeem Vawda3ff069e2011-11-30 00:25:06 +0200177 PyErr_SetString(PyExc_OverflowError, \
178 "Value too large for " #TYPE " type"); \
179 return 0; \
180 } \
Martin v. Löwisd1b7f392012-05-15 14:06:21 +0200181 *(TYPE *)ptr = (TYPE)val; \
Nadeem Vawda3ff069e2011-11-30 00:25:06 +0200182 return 1; \
183 }
184
185INT_TYPE_CONVERTER_FUNC(uint32_t, uint32_converter)
Nadeem Vawdaf55b3292012-05-06 23:01:27 +0200186INT_TYPE_CONVERTER_FUNC(lzma_vli, lzma_vli_converter)
Nadeem Vawda3ff069e2011-11-30 00:25:06 +0200187INT_TYPE_CONVERTER_FUNC(lzma_mode, lzma_mode_converter)
188INT_TYPE_CONVERTER_FUNC(lzma_match_finder, lzma_mf_converter)
189
190#undef INT_TYPE_CONVERTER_FUNC
191
192
Nadeem Vawdaf55b3292012-05-06 23:01:27 +0200193/* Filter specifier parsing.
194
195 This code handles converting filter specifiers (Python dicts) into
196 the C lzma_filter structs expected by liblzma. */
Nadeem Vawda3ff069e2011-11-30 00:25:06 +0200197
198static void *
199parse_filter_spec_lzma(PyObject *spec)
200{
201 static char *optnames[] = {"id", "preset", "dict_size", "lc", "lp",
202 "pb", "mode", "nice_len", "mf", "depth", NULL};
203 PyObject *id;
204 PyObject *preset_obj;
205 uint32_t preset = LZMA_PRESET_DEFAULT;
206 lzma_options_lzma *options;
207
208 /* First, fill in default values for all the options using a preset.
209 Then, override the defaults with any values given by the caller. */
210
211 preset_obj = PyMapping_GetItemString(spec, "preset");
212 if (preset_obj == NULL) {
213 if (PyErr_ExceptionMatches(PyExc_KeyError))
214 PyErr_Clear();
215 else
216 return NULL;
217 } else {
218 int ok = uint32_converter(preset_obj, &preset);
219 Py_DECREF(preset_obj);
220 if (!ok)
221 return NULL;
222 }
223
224 options = (lzma_options_lzma *)PyMem_Malloc(sizeof *options);
225 if (options == NULL)
226 return PyErr_NoMemory();
227 memset(options, 0, sizeof *options);
228
229 if (lzma_lzma_preset(options, preset)) {
230 PyMem_Free(options);
Nadeem Vawda54c74ec2012-05-06 13:35:47 +0200231 PyErr_Format(Error, "Invalid compression preset: %d", preset);
Nadeem Vawda3ff069e2011-11-30 00:25:06 +0200232 return NULL;
233 }
234
235 if (!PyArg_ParseTupleAndKeywords(empty_tuple, spec,
236 "|OOO&O&O&O&O&O&O&O&", optnames,
237 &id, &preset_obj,
238 uint32_converter, &options->dict_size,
239 uint32_converter, &options->lc,
240 uint32_converter, &options->lp,
241 uint32_converter, &options->pb,
242 lzma_mode_converter, &options->mode,
243 uint32_converter, &options->nice_len,
244 lzma_mf_converter, &options->mf,
245 uint32_converter, &options->depth)) {
246 PyErr_SetString(PyExc_ValueError,
247 "Invalid filter specifier for LZMA filter");
248 PyMem_Free(options);
249 options = NULL;
250 }
251 return options;
252}
253
254static void *
255parse_filter_spec_delta(PyObject *spec)
256{
257 static char *optnames[] = {"id", "dist", NULL};
258 PyObject *id;
259 uint32_t dist = 1;
260 lzma_options_delta *options;
261
262 if (!PyArg_ParseTupleAndKeywords(empty_tuple, spec, "|OO&", optnames,
263 &id, uint32_converter, &dist)) {
264 PyErr_SetString(PyExc_ValueError,
265 "Invalid filter specifier for delta filter");
266 return NULL;
267 }
268
269 options = (lzma_options_delta *)PyMem_Malloc(sizeof *options);
270 if (options == NULL)
271 return PyErr_NoMemory();
272 memset(options, 0, sizeof *options);
273 options->type = LZMA_DELTA_TYPE_BYTE;
274 options->dist = dist;
275 return options;
276}
277
278static void *
279parse_filter_spec_bcj(PyObject *spec)
280{
281 static char *optnames[] = {"id", "start_offset", NULL};
282 PyObject *id;
283 uint32_t start_offset = 0;
284 lzma_options_bcj *options;
285
286 if (!PyArg_ParseTupleAndKeywords(empty_tuple, spec, "|OO&", optnames,
287 &id, uint32_converter, &start_offset)) {
288 PyErr_SetString(PyExc_ValueError,
289 "Invalid filter specifier for BCJ filter");
290 return NULL;
291 }
292
293 options = (lzma_options_bcj *)PyMem_Malloc(sizeof *options);
294 if (options == NULL)
295 return PyErr_NoMemory();
296 memset(options, 0, sizeof *options);
297 options->start_offset = start_offset;
298 return options;
299}
300
301static void *
302parse_filter_spec(lzma_filter *f, PyObject *spec)
303{
304 PyObject *id_obj;
305
306 if (!PyMapping_Check(spec)) {
307 PyErr_SetString(PyExc_TypeError,
308 "Filter specifier must be a dict or dict-like object");
309 return NULL;
310 }
311 id_obj = PyMapping_GetItemString(spec, "id");
312 if (id_obj == NULL) {
313 if (PyErr_ExceptionMatches(PyExc_KeyError))
314 PyErr_SetString(PyExc_ValueError,
315 "Filter specifier must have an \"id\" entry");
316 return NULL;
317 }
318 f->id = PyLong_AsUnsignedLongLong(id_obj);
319 Py_DECREF(id_obj);
320 if (PyErr_Occurred())
321 return NULL;
322
323 switch (f->id) {
324 case LZMA_FILTER_LZMA1:
325 case LZMA_FILTER_LZMA2:
326 f->options = parse_filter_spec_lzma(spec);
327 return f->options;
328 case LZMA_FILTER_DELTA:
329 f->options = parse_filter_spec_delta(spec);
330 return f->options;
331 case LZMA_FILTER_X86:
332 case LZMA_FILTER_POWERPC:
333 case LZMA_FILTER_IA64:
334 case LZMA_FILTER_ARM:
335 case LZMA_FILTER_ARMTHUMB:
336 case LZMA_FILTER_SPARC:
337 f->options = parse_filter_spec_bcj(spec);
338 return f->options;
339 default:
340 PyErr_Format(PyExc_ValueError, "Invalid filter ID: %llu", f->id);
341 return NULL;
342 }
343}
344
345static void
346free_filter_chain(lzma_filter filters[])
347{
348 int i;
349
350 for (i = 0; filters[i].id != LZMA_VLI_UNKNOWN; i++)
351 PyMem_Free(filters[i].options);
352}
353
354static int
355parse_filter_chain_spec(lzma_filter filters[], PyObject *filterspecs)
356{
357 Py_ssize_t i, num_filters;
358
359 num_filters = PySequence_Length(filterspecs);
360 if (num_filters == -1)
361 return -1;
362 if (num_filters > LZMA_FILTERS_MAX) {
363 PyErr_Format(PyExc_ValueError,
364 "Too many filters - liblzma supports a maximum of %d",
365 LZMA_FILTERS_MAX);
366 return -1;
367 }
368
369 for (i = 0; i < num_filters; i++) {
370 int ok = 1;
371 PyObject *spec = PySequence_GetItem(filterspecs, i);
372 if (spec == NULL || parse_filter_spec(&filters[i], spec) == NULL)
373 ok = 0;
374 Py_XDECREF(spec);
375 if (!ok) {
376 filters[i].id = LZMA_VLI_UNKNOWN;
377 free_filter_chain(filters);
378 return -1;
379 }
380 }
381 filters[num_filters].id = LZMA_VLI_UNKNOWN;
382 return 0;
383}
384
385
Nadeem Vawdaf55b3292012-05-06 23:01:27 +0200386/* Filter specifier construction.
387
388 This code handles converting C lzma_filter structs into
389 Python-level filter specifiers (represented as dicts). */
390
391static int
392spec_add_field(PyObject *spec, _Py_Identifier *key, unsigned PY_LONG_LONG value)
393{
394 int status;
395 PyObject *value_object;
396
397 value_object = PyLong_FromUnsignedLongLong(value);
398 if (value_object == NULL)
399 return -1;
400
401 status = _PyDict_SetItemId(spec, key, value_object);
402 Py_DECREF(value_object);
403 return status;
404}
405
406static PyObject *
407build_filter_spec(const lzma_filter *f)
408{
409 PyObject *spec;
410
411 spec = PyDict_New();
412 if (spec == NULL)
413 return NULL;
414
415#define ADD_FIELD(SOURCE, FIELD) \
416 do { \
417 _Py_IDENTIFIER(FIELD); \
418 if (spec_add_field(spec, &PyId_##FIELD, SOURCE->FIELD) == -1) \
419 goto error;\
420 } while (0)
421
422 ADD_FIELD(f, id);
423
424 switch (f->id) {
Nadeem Vawda486a0452012-05-07 00:40:57 +0200425 /* For LZMA1 filters, lzma_properties_{encode,decode}() only look at the
426 lc, lp, pb, and dict_size fields. For LZMA2 filters, only the
427 dict_size field is used. */
428 case LZMA_FILTER_LZMA1: {
Nadeem Vawdaf55b3292012-05-06 23:01:27 +0200429 lzma_options_lzma *options = f->options;
Nadeem Vawdaf55b3292012-05-06 23:01:27 +0200430 ADD_FIELD(options, lc);
431 ADD_FIELD(options, lp);
432 ADD_FIELD(options, pb);
Ross Lagerwall4d688e32012-05-12 08:30:33 +0200433 ADD_FIELD(options, dict_size);
434 break;
435 }
436 case LZMA_FILTER_LZMA2: {
437 lzma_options_lzma *options = f->options;
Nadeem Vawda486a0452012-05-07 00:40:57 +0200438 ADD_FIELD(options, dict_size);
Nadeem Vawdaf55b3292012-05-06 23:01:27 +0200439 break;
440 }
441 case LZMA_FILTER_DELTA: {
442 lzma_options_delta *options = f->options;
443 ADD_FIELD(options, dist);
444 break;
445 }
446 case LZMA_FILTER_X86:
447 case LZMA_FILTER_POWERPC:
448 case LZMA_FILTER_IA64:
449 case LZMA_FILTER_ARM:
450 case LZMA_FILTER_ARMTHUMB:
451 case LZMA_FILTER_SPARC: {
452 lzma_options_bcj *options = f->options;
453 ADD_FIELD(options, start_offset);
454 break;
455 }
456 default:
457 PyErr_Format(PyExc_ValueError, "Invalid filter ID: %llu", f->id);
458 goto error;
459 }
460
461#undef ADD_FIELD
462
463 return spec;
464
465error:
466 Py_DECREF(spec);
467 return NULL;
468}
469
470
Nadeem Vawda3ff069e2011-11-30 00:25:06 +0200471/* LZMACompressor class. */
472
473static PyObject *
474compress(Compressor *c, uint8_t *data, size_t len, lzma_action action)
475{
476 size_t data_size = 0;
477 PyObject *result;
478
479 result = PyBytes_FromStringAndSize(NULL, INITIAL_BUFFER_SIZE);
480 if (result == NULL)
481 return NULL;
482 c->lzs.next_in = data;
483 c->lzs.avail_in = len;
484 c->lzs.next_out = (uint8_t *)PyBytes_AS_STRING(result);
485 c->lzs.avail_out = PyBytes_GET_SIZE(result);
486 for (;;) {
487 lzma_ret lzret;
488
489 Py_BEGIN_ALLOW_THREADS
490 lzret = lzma_code(&c->lzs, action);
491 data_size = (char *)c->lzs.next_out - PyBytes_AS_STRING(result);
492 Py_END_ALLOW_THREADS
493 if (catch_lzma_error(lzret))
494 goto error;
495 if ((action == LZMA_RUN && c->lzs.avail_in == 0) ||
496 (action == LZMA_FINISH && lzret == LZMA_STREAM_END)) {
497 break;
498 } else if (c->lzs.avail_out == 0) {
499 if (grow_buffer(&result) == -1)
500 goto error;
501 c->lzs.next_out = (uint8_t *)PyBytes_AS_STRING(result) + data_size;
502 c->lzs.avail_out = PyBytes_GET_SIZE(result) - data_size;
503 }
504 }
505 if (data_size != PyBytes_GET_SIZE(result))
506 if (_PyBytes_Resize(&result, data_size) == -1)
507 goto error;
508 return result;
509
510error:
511 Py_XDECREF(result);
512 return NULL;
513}
514
515PyDoc_STRVAR(Compressor_compress_doc,
516"compress(data) -> bytes\n"
517"\n"
518"Provide data to the compressor object. Returns a chunk of\n"
519"compressed data if possible, or b\"\" otherwise.\n"
520"\n"
521"When you have finished providing data to the compressor, call the\n"
522"flush() method to finish the conversion process.\n");
523
524static PyObject *
525Compressor_compress(Compressor *self, PyObject *args)
526{
527 Py_buffer buffer;
528 PyObject *result = NULL;
529
530 if (!PyArg_ParseTuple(args, "y*:compress", &buffer))
531 return NULL;
532
533 ACQUIRE_LOCK(self);
534 if (self->flushed)
535 PyErr_SetString(PyExc_ValueError, "Compressor has been flushed");
536 else
537 result = compress(self, buffer.buf, buffer.len, LZMA_RUN);
538 RELEASE_LOCK(self);
539 PyBuffer_Release(&buffer);
540 return result;
541}
542
543PyDoc_STRVAR(Compressor_flush_doc,
544"flush() -> bytes\n"
545"\n"
546"Finish the compression process. Returns the compressed data left\n"
547"in internal buffers.\n"
548"\n"
549"The compressor object cannot be used after this method is called.\n");
550
551static PyObject *
552Compressor_flush(Compressor *self, PyObject *noargs)
553{
554 PyObject *result = NULL;
555
556 ACQUIRE_LOCK(self);
557 if (self->flushed) {
558 PyErr_SetString(PyExc_ValueError, "Repeated call to flush()");
559 } else {
560 self->flushed = 1;
561 result = compress(self, NULL, 0, LZMA_FINISH);
562 }
563 RELEASE_LOCK(self);
564 return result;
565}
566
Nadeem Vawda37970652013-10-28 21:35:23 +0100567static PyObject *
568Compressor_getstate(Compressor *self, PyObject *noargs)
569{
570 PyErr_Format(PyExc_TypeError, "cannot serialize '%s' object",
571 Py_TYPE(self)->tp_name);
572 return NULL;
573}
574
Nadeem Vawda3ff069e2011-11-30 00:25:06 +0200575static int
576Compressor_init_xz(lzma_stream *lzs, int check, uint32_t preset,
577 PyObject *filterspecs)
578{
579 lzma_ret lzret;
580
581 if (filterspecs == Py_None) {
582 lzret = lzma_easy_encoder(lzs, preset, check);
583 } else {
584 lzma_filter filters[LZMA_FILTERS_MAX + 1];
585
586 if (parse_filter_chain_spec(filters, filterspecs) == -1)
587 return -1;
588 lzret = lzma_stream_encoder(lzs, filters, check);
589 free_filter_chain(filters);
590 }
591 if (catch_lzma_error(lzret))
592 return -1;
593 else
594 return 0;
595}
596
597static int
598Compressor_init_alone(lzma_stream *lzs, uint32_t preset, PyObject *filterspecs)
599{
600 lzma_ret lzret;
601
602 if (filterspecs == Py_None) {
603 lzma_options_lzma options;
604
605 if (lzma_lzma_preset(&options, preset)) {
Nadeem Vawda54c74ec2012-05-06 13:35:47 +0200606 PyErr_Format(Error, "Invalid compression preset: %d", preset);
Nadeem Vawda3ff069e2011-11-30 00:25:06 +0200607 return -1;
608 }
609 lzret = lzma_alone_encoder(lzs, &options);
610 } else {
611 lzma_filter filters[LZMA_FILTERS_MAX + 1];
612
613 if (parse_filter_chain_spec(filters, filterspecs) == -1)
614 return -1;
615 if (filters[0].id == LZMA_FILTER_LZMA1 &&
616 filters[1].id == LZMA_VLI_UNKNOWN) {
617 lzret = lzma_alone_encoder(lzs, filters[0].options);
618 } else {
619 PyErr_SetString(PyExc_ValueError,
620 "Invalid filter chain for FORMAT_ALONE - "
621 "must be a single LZMA1 filter");
622 lzret = LZMA_PROG_ERROR;
623 }
624 free_filter_chain(filters);
625 }
626 if (PyErr_Occurred() || catch_lzma_error(lzret))
627 return -1;
628 else
629 return 0;
630}
631
632static int
633Compressor_init_raw(lzma_stream *lzs, PyObject *filterspecs)
634{
635 lzma_filter filters[LZMA_FILTERS_MAX + 1];
636 lzma_ret lzret;
637
638 if (filterspecs == Py_None) {
639 PyErr_SetString(PyExc_ValueError,
640 "Must specify filters for FORMAT_RAW");
641 return -1;
642 }
643 if (parse_filter_chain_spec(filters, filterspecs) == -1)
644 return -1;
645 lzret = lzma_raw_encoder(lzs, filters);
646 free_filter_chain(filters);
647 if (catch_lzma_error(lzret))
648 return -1;
649 else
650 return 0;
651}
652
653static int
654Compressor_init(Compressor *self, PyObject *args, PyObject *kwargs)
655{
656 static char *arg_names[] = {"format", "check", "preset", "filters", NULL};
657 int format = FORMAT_XZ;
658 int check = -1;
659 uint32_t preset = LZMA_PRESET_DEFAULT;
660 PyObject *preset_obj = Py_None;
661 PyObject *filterspecs = Py_None;
662
663 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
664 "|iiOO:LZMACompressor", arg_names,
665 &format, &check, &preset_obj,
666 &filterspecs))
667 return -1;
668
669 if (format != FORMAT_XZ && check != -1 && check != LZMA_CHECK_NONE) {
670 PyErr_SetString(PyExc_ValueError,
671 "Integrity checks are only supported by FORMAT_XZ");
672 return -1;
673 }
674
675 if (preset_obj != Py_None && filterspecs != Py_None) {
676 PyErr_SetString(PyExc_ValueError,
677 "Cannot specify both preset and filter chain");
678 return -1;
679 }
680
681 if (preset_obj != Py_None)
682 if (!uint32_converter(preset_obj, &preset))
683 return -1;
684
Victor Stinner5064a522013-07-07 16:50:27 +0200685 self->alloc.opaque = NULL;
686 self->alloc.alloc = PyLzma_Malloc;
687 self->alloc.free = PyLzma_Free;
688 self->lzs.allocator = &self->alloc;
689
Nadeem Vawda3ff069e2011-11-30 00:25:06 +0200690#ifdef WITH_THREAD
691 self->lock = PyThread_allocate_lock();
692 if (self->lock == NULL) {
693 PyErr_SetString(PyExc_MemoryError, "Unable to allocate lock");
694 return -1;
695 }
696#endif
697
698 self->flushed = 0;
699 switch (format) {
700 case FORMAT_XZ:
701 if (check == -1)
702 check = LZMA_CHECK_CRC64;
703 if (Compressor_init_xz(&self->lzs, check, preset, filterspecs) != 0)
704 break;
705 return 0;
706
707 case FORMAT_ALONE:
708 if (Compressor_init_alone(&self->lzs, preset, filterspecs) != 0)
709 break;
710 return 0;
711
712 case FORMAT_RAW:
713 if (Compressor_init_raw(&self->lzs, filterspecs) != 0)
714 break;
715 return 0;
716
717 default:
718 PyErr_Format(PyExc_ValueError,
719 "Invalid container format: %d", format);
720 break;
721 }
722
723#ifdef WITH_THREAD
724 PyThread_free_lock(self->lock);
725 self->lock = NULL;
726#endif
727 return -1;
728}
729
730static void
731Compressor_dealloc(Compressor *self)
732{
733 lzma_end(&self->lzs);
734#ifdef WITH_THREAD
735 if (self->lock != NULL)
736 PyThread_free_lock(self->lock);
737#endif
738 Py_TYPE(self)->tp_free((PyObject *)self);
739}
740
741static PyMethodDef Compressor_methods[] = {
742 {"compress", (PyCFunction)Compressor_compress, METH_VARARGS,
743 Compressor_compress_doc},
744 {"flush", (PyCFunction)Compressor_flush, METH_NOARGS,
745 Compressor_flush_doc},
Nadeem Vawda37970652013-10-28 21:35:23 +0100746 {"__getstate__", (PyCFunction)Compressor_getstate, METH_NOARGS},
Nadeem Vawda3ff069e2011-11-30 00:25:06 +0200747 {NULL}
748};
749
750PyDoc_STRVAR(Compressor_doc,
751"LZMACompressor(format=FORMAT_XZ, check=-1, preset=None, filters=None)\n"
752"\n"
753"Create a compressor object for compressing data incrementally.\n"
754"\n"
755"format specifies the container format to use for the output. This can\n"
756"be FORMAT_XZ (default), FORMAT_ALONE, or FORMAT_RAW.\n"
757"\n"
758"check specifies the integrity check to use. For FORMAT_XZ, the default\n"
759"is CHECK_CRC64. FORMAT_ALONE and FORMAT_RAW do not suport integrity\n"
760"checks; for these formats, check must be omitted, or be CHECK_NONE.\n"
761"\n"
762"The settings used by the compressor can be specified either as a\n"
763"preset compression level (with the 'preset' argument), or in detail\n"
764"as a custom filter chain (with the 'filters' argument). For FORMAT_XZ\n"
765"and FORMAT_ALONE, the default is to use the PRESET_DEFAULT preset\n"
766"level. For FORMAT_RAW, the caller must always specify a filter chain;\n"
767"the raw compressor does not support preset compression levels.\n"
768"\n"
769"preset (if provided) should be an integer in the range 0-9, optionally\n"
770"OR-ed with the constant PRESET_EXTREME.\n"
771"\n"
772"filters (if provided) should be a sequence of dicts. Each dict should\n"
773"have an entry for \"id\" indicating the ID of the filter, plus\n"
774"additional entries for options to the filter.\n"
775"\n"
776"For one-shot compression, use the compress() function instead.\n");
777
778static PyTypeObject Compressor_type = {
779 PyVarObject_HEAD_INIT(NULL, 0)
780 "_lzma.LZMACompressor", /* tp_name */
781 sizeof(Compressor), /* tp_basicsize */
782 0, /* tp_itemsize */
783 (destructor)Compressor_dealloc, /* tp_dealloc */
784 0, /* tp_print */
785 0, /* tp_getattr */
786 0, /* tp_setattr */
787 0, /* tp_reserved */
788 0, /* tp_repr */
789 0, /* tp_as_number */
790 0, /* tp_as_sequence */
791 0, /* tp_as_mapping */
792 0, /* tp_hash */
793 0, /* tp_call */
794 0, /* tp_str */
795 0, /* tp_getattro */
796 0, /* tp_setattro */
797 0, /* tp_as_buffer */
798 Py_TPFLAGS_DEFAULT, /* tp_flags */
799 Compressor_doc, /* tp_doc */
800 0, /* tp_traverse */
801 0, /* tp_clear */
802 0, /* tp_richcompare */
803 0, /* tp_weaklistoffset */
804 0, /* tp_iter */
805 0, /* tp_iternext */
806 Compressor_methods, /* tp_methods */
807 0, /* tp_members */
808 0, /* tp_getset */
809 0, /* tp_base */
810 0, /* tp_dict */
811 0, /* tp_descr_get */
812 0, /* tp_descr_set */
813 0, /* tp_dictoffset */
814 (initproc)Compressor_init, /* tp_init */
815 0, /* tp_alloc */
816 PyType_GenericNew, /* tp_new */
817};
818
819
820/* LZMADecompressor class. */
821
822static PyObject *
823decompress(Decompressor *d, uint8_t *data, size_t len)
824{
825 size_t data_size = 0;
826 PyObject *result;
827
828 result = PyBytes_FromStringAndSize(NULL, INITIAL_BUFFER_SIZE);
829 if (result == NULL)
830 return NULL;
831 d->lzs.next_in = data;
832 d->lzs.avail_in = len;
833 d->lzs.next_out = (uint8_t *)PyBytes_AS_STRING(result);
834 d->lzs.avail_out = PyBytes_GET_SIZE(result);
835 for (;;) {
836 lzma_ret lzret;
837
838 Py_BEGIN_ALLOW_THREADS
839 lzret = lzma_code(&d->lzs, LZMA_RUN);
840 data_size = (char *)d->lzs.next_out - PyBytes_AS_STRING(result);
841 Py_END_ALLOW_THREADS
842 if (catch_lzma_error(lzret))
843 goto error;
844 if (lzret == LZMA_GET_CHECK || lzret == LZMA_NO_CHECK)
845 d->check = lzma_get_check(&d->lzs);
846 if (lzret == LZMA_STREAM_END) {
847 d->eof = 1;
848 if (d->lzs.avail_in > 0) {
849 Py_CLEAR(d->unused_data);
850 d->unused_data = PyBytes_FromStringAndSize(
851 (char *)d->lzs.next_in, d->lzs.avail_in);
852 if (d->unused_data == NULL)
853 goto error;
854 }
855 break;
856 } else if (d->lzs.avail_in == 0) {
857 break;
858 } else if (d->lzs.avail_out == 0) {
859 if (grow_buffer(&result) == -1)
860 goto error;
861 d->lzs.next_out = (uint8_t *)PyBytes_AS_STRING(result) + data_size;
862 d->lzs.avail_out = PyBytes_GET_SIZE(result) - data_size;
863 }
864 }
865 if (data_size != PyBytes_GET_SIZE(result))
866 if (_PyBytes_Resize(&result, data_size) == -1)
867 goto error;
868 return result;
869
870error:
871 Py_XDECREF(result);
872 return NULL;
873}
874
875PyDoc_STRVAR(Decompressor_decompress_doc,
876"decompress(data) -> bytes\n"
877"\n"
878"Provide data to the decompressor object. Returns a chunk of\n"
879"decompressed data if possible, or b\"\" otherwise.\n"
880"\n"
881"Attempting to decompress data after the end of the stream is\n"
882"reached raises an EOFError. Any data found after the end of the\n"
883"stream is ignored, and saved in the unused_data attribute.\n");
884
885static PyObject *
886Decompressor_decompress(Decompressor *self, PyObject *args)
887{
888 Py_buffer buffer;
889 PyObject *result = NULL;
890
891 if (!PyArg_ParseTuple(args, "y*:decompress", &buffer))
892 return NULL;
893
894 ACQUIRE_LOCK(self);
895 if (self->eof)
896 PyErr_SetString(PyExc_EOFError, "Already at end of stream");
897 else
898 result = decompress(self, buffer.buf, buffer.len);
899 RELEASE_LOCK(self);
900 PyBuffer_Release(&buffer);
901 return result;
902}
903
Nadeem Vawda37970652013-10-28 21:35:23 +0100904static PyObject *
905Decompressor_getstate(Decompressor *self, PyObject *noargs)
906{
907 PyErr_Format(PyExc_TypeError, "cannot serialize '%s' object",
908 Py_TYPE(self)->tp_name);
909 return NULL;
910}
911
Nadeem Vawda3ff069e2011-11-30 00:25:06 +0200912static int
913Decompressor_init_raw(lzma_stream *lzs, PyObject *filterspecs)
914{
915 lzma_filter filters[LZMA_FILTERS_MAX + 1];
916 lzma_ret lzret;
917
918 if (parse_filter_chain_spec(filters, filterspecs) == -1)
919 return -1;
920 lzret = lzma_raw_decoder(lzs, filters);
921 free_filter_chain(filters);
922 if (catch_lzma_error(lzret))
923 return -1;
924 else
925 return 0;
926}
927
928static int
929Decompressor_init(Decompressor *self, PyObject *args, PyObject *kwargs)
930{
931 static char *arg_names[] = {"format", "memlimit", "filters", NULL};
932 const uint32_t decoder_flags = LZMA_TELL_ANY_CHECK | LZMA_TELL_NO_CHECK;
933 int format = FORMAT_AUTO;
934 uint64_t memlimit = UINT64_MAX;
935 PyObject *memlimit_obj = Py_None;
936 PyObject *filterspecs = Py_None;
937 lzma_ret lzret;
938
939 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
940 "|iOO:LZMADecompressor", arg_names,
941 &format, &memlimit_obj, &filterspecs))
942 return -1;
943
944 if (memlimit_obj != Py_None) {
945 if (format == FORMAT_RAW) {
946 PyErr_SetString(PyExc_ValueError,
947 "Cannot specify memory limit with FORMAT_RAW");
948 return -1;
949 }
950 memlimit = PyLong_AsUnsignedLongLong(memlimit_obj);
951 if (PyErr_Occurred())
952 return -1;
953 }
954
955 if (format == FORMAT_RAW && filterspecs == Py_None) {
956 PyErr_SetString(PyExc_ValueError,
957 "Must specify filters for FORMAT_RAW");
958 return -1;
959 } else if (format != FORMAT_RAW && filterspecs != Py_None) {
960 PyErr_SetString(PyExc_ValueError,
961 "Cannot specify filters except with FORMAT_RAW");
962 return -1;
963 }
964
Victor Stinner5064a522013-07-07 16:50:27 +0200965 self->alloc.opaque = NULL;
966 self->alloc.alloc = PyLzma_Malloc;
967 self->alloc.free = PyLzma_Free;
968 self->lzs.allocator = &self->alloc;
969
Nadeem Vawda3ff069e2011-11-30 00:25:06 +0200970#ifdef WITH_THREAD
971 self->lock = PyThread_allocate_lock();
972 if (self->lock == NULL) {
973 PyErr_SetString(PyExc_MemoryError, "Unable to allocate lock");
974 return -1;
975 }
976#endif
977
978 self->check = LZMA_CHECK_UNKNOWN;
979 self->unused_data = PyBytes_FromStringAndSize(NULL, 0);
980 if (self->unused_data == NULL)
981 goto error;
982
983 switch (format) {
984 case FORMAT_AUTO:
985 lzret = lzma_auto_decoder(&self->lzs, memlimit, decoder_flags);
986 if (catch_lzma_error(lzret))
987 break;
988 return 0;
989
990 case FORMAT_XZ:
991 lzret = lzma_stream_decoder(&self->lzs, memlimit, decoder_flags);
992 if (catch_lzma_error(lzret))
993 break;
994 return 0;
995
996 case FORMAT_ALONE:
997 self->check = LZMA_CHECK_NONE;
998 lzret = lzma_alone_decoder(&self->lzs, memlimit);
999 if (catch_lzma_error(lzret))
1000 break;
1001 return 0;
1002
1003 case FORMAT_RAW:
1004 self->check = LZMA_CHECK_NONE;
1005 if (Decompressor_init_raw(&self->lzs, filterspecs) == -1)
1006 break;
1007 return 0;
1008
1009 default:
1010 PyErr_Format(PyExc_ValueError,
1011 "Invalid container format: %d", format);
1012 break;
1013 }
1014
1015error:
1016 Py_CLEAR(self->unused_data);
1017#ifdef WITH_THREAD
1018 PyThread_free_lock(self->lock);
1019 self->lock = NULL;
1020#endif
1021 return -1;
1022}
1023
1024static void
1025Decompressor_dealloc(Decompressor *self)
1026{
1027 lzma_end(&self->lzs);
1028 Py_CLEAR(self->unused_data);
1029#ifdef WITH_THREAD
1030 if (self->lock != NULL)
1031 PyThread_free_lock(self->lock);
1032#endif
1033 Py_TYPE(self)->tp_free((PyObject *)self);
1034}
1035
1036static PyMethodDef Decompressor_methods[] = {
1037 {"decompress", (PyCFunction)Decompressor_decompress, METH_VARARGS,
1038 Decompressor_decompress_doc},
Nadeem Vawda37970652013-10-28 21:35:23 +01001039 {"__getstate__", (PyCFunction)Decompressor_getstate, METH_NOARGS},
Nadeem Vawda3ff069e2011-11-30 00:25:06 +02001040 {NULL}
1041};
1042
1043PyDoc_STRVAR(Decompressor_check_doc,
1044"ID of the integrity check used by the input stream.");
1045
1046PyDoc_STRVAR(Decompressor_eof_doc,
1047"True if the end-of-stream marker has been reached.");
1048
1049PyDoc_STRVAR(Decompressor_unused_data_doc,
1050"Data found after the end of the compressed stream.");
1051
1052static PyMemberDef Decompressor_members[] = {
1053 {"check", T_INT, offsetof(Decompressor, check), READONLY,
1054 Decompressor_check_doc},
1055 {"eof", T_BOOL, offsetof(Decompressor, eof), READONLY,
1056 Decompressor_eof_doc},
1057 {"unused_data", T_OBJECT_EX, offsetof(Decompressor, unused_data), READONLY,
1058 Decompressor_unused_data_doc},
1059 {NULL}
1060};
1061
1062PyDoc_STRVAR(Decompressor_doc,
1063"LZMADecompressor(format=FORMAT_AUTO, memlimit=None, filters=None)\n"
1064"\n"
1065"Create a decompressor object for decompressing data incrementally.\n"
1066"\n"
1067"format specifies the container format of the input stream. If this is\n"
1068"FORMAT_AUTO (the default), the decompressor will automatically detect\n"
1069"whether the input is FORMAT_XZ or FORMAT_ALONE. Streams created with\n"
1070"FORMAT_RAW cannot be autodetected.\n"
1071"\n"
1072"memlimit can be specified to limit the amount of memory used by the\n"
1073"decompressor. This will cause decompression to fail if the input\n"
1074"cannot be decompressed within the given limit.\n"
1075"\n"
1076"filters specifies a custom filter chain. This argument is required for\n"
1077"FORMAT_RAW, and not accepted with any other format. When provided,\n"
1078"this should be a sequence of dicts, each indicating the ID and options\n"
1079"for a single filter.\n"
1080"\n"
1081"For one-shot decompression, use the decompress() function instead.\n");
1082
1083static PyTypeObject Decompressor_type = {
1084 PyVarObject_HEAD_INIT(NULL, 0)
1085 "_lzma.LZMADecompressor", /* tp_name */
1086 sizeof(Decompressor), /* tp_basicsize */
1087 0, /* tp_itemsize */
1088 (destructor)Decompressor_dealloc, /* tp_dealloc */
1089 0, /* tp_print */
1090 0, /* tp_getattr */
1091 0, /* tp_setattr */
1092 0, /* tp_reserved */
1093 0, /* tp_repr */
1094 0, /* tp_as_number */
1095 0, /* tp_as_sequence */
1096 0, /* tp_as_mapping */
1097 0, /* tp_hash */
1098 0, /* tp_call */
1099 0, /* tp_str */
1100 0, /* tp_getattro */
1101 0, /* tp_setattro */
1102 0, /* tp_as_buffer */
1103 Py_TPFLAGS_DEFAULT, /* tp_flags */
1104 Decompressor_doc, /* tp_doc */
1105 0, /* tp_traverse */
1106 0, /* tp_clear */
1107 0, /* tp_richcompare */
1108 0, /* tp_weaklistoffset */
1109 0, /* tp_iter */
1110 0, /* tp_iternext */
1111 Decompressor_methods, /* tp_methods */
1112 Decompressor_members, /* tp_members */
1113 0, /* tp_getset */
1114 0, /* tp_base */
1115 0, /* tp_dict */
1116 0, /* tp_descr_get */
1117 0, /* tp_descr_set */
1118 0, /* tp_dictoffset */
1119 (initproc)Decompressor_init, /* tp_init */
1120 0, /* tp_alloc */
1121 PyType_GenericNew, /* tp_new */
1122};
1123
1124
1125/* Module-level functions. */
1126
Nadeem Vawdabc459bb2012-05-06 23:01:51 +02001127PyDoc_STRVAR(is_check_supported_doc,
1128"is_check_supported(check_id) -> bool\n"
Nadeem Vawda3ff069e2011-11-30 00:25:06 +02001129"\n"
1130"Test whether the given integrity check is supported.\n"
1131"\n"
1132"Always returns True for CHECK_NONE and CHECK_CRC32.\n");
1133
1134static PyObject *
Nadeem Vawdabc459bb2012-05-06 23:01:51 +02001135is_check_supported(PyObject *self, PyObject *args)
Nadeem Vawda3ff069e2011-11-30 00:25:06 +02001136{
1137 int check_id;
1138
Nadeem Vawdabc459bb2012-05-06 23:01:51 +02001139 if (!PyArg_ParseTuple(args, "i:is_check_supported", &check_id))
Nadeem Vawda3ff069e2011-11-30 00:25:06 +02001140 return NULL;
1141
1142 return PyBool_FromLong(lzma_check_is_supported(check_id));
1143}
1144
1145
Nadeem Vawdaa425c3d2012-06-21 23:36:48 +02001146PyDoc_STRVAR(_encode_filter_properties_doc,
1147"_encode_filter_properties(filter) -> bytes\n"
Nadeem Vawdaf55b3292012-05-06 23:01:27 +02001148"\n"
1149"Return a bytes object encoding the options (properties) of the filter\n"
1150"specified by *filter* (a dict).\n"
1151"\n"
Nadeem Vawdaa425c3d2012-06-21 23:36:48 +02001152"The result does not include the filter ID itself, only the options.\n");
Nadeem Vawdaf55b3292012-05-06 23:01:27 +02001153
1154static PyObject *
Nadeem Vawdaa425c3d2012-06-21 23:36:48 +02001155_encode_filter_properties(PyObject *self, PyObject *args)
Nadeem Vawdaf55b3292012-05-06 23:01:27 +02001156{
1157 PyObject *filterspec;
1158 lzma_filter filter;
1159 lzma_ret lzret;
1160 uint32_t encoded_size;
1161 PyObject *result = NULL;
1162
Nadeem Vawdaa425c3d2012-06-21 23:36:48 +02001163 if (!PyArg_ParseTuple(args, "O:_encode_filter_properties", &filterspec))
Nadeem Vawdaf55b3292012-05-06 23:01:27 +02001164 return NULL;
1165
1166 if (parse_filter_spec(&filter, filterspec) == NULL)
1167 return NULL;
1168
1169 lzret = lzma_properties_size(&encoded_size, &filter);
1170 if (catch_lzma_error(lzret))
1171 goto error;
1172
1173 result = PyBytes_FromStringAndSize(NULL, encoded_size);
1174 if (result == NULL)
1175 goto error;
1176
1177 lzret = lzma_properties_encode(
1178 &filter, (uint8_t *)PyBytes_AS_STRING(result));
1179 if (catch_lzma_error(lzret))
1180 goto error;
1181
1182 PyMem_Free(filter.options);
1183 return result;
1184
1185error:
1186 Py_XDECREF(result);
1187 PyMem_Free(filter.options);
1188 return NULL;
1189}
1190
1191
Nadeem Vawdaa425c3d2012-06-21 23:36:48 +02001192PyDoc_STRVAR(_decode_filter_properties_doc,
1193"_decode_filter_properties(filter_id, encoded_props) -> dict\n"
Nadeem Vawdaf55b3292012-05-06 23:01:27 +02001194"\n"
1195"Return a dict describing a filter with ID *filter_id*, and options\n"
Nadeem Vawdaa425c3d2012-06-21 23:36:48 +02001196"(properties) decoded from the bytes object *encoded_props*.\n");
Nadeem Vawdaf55b3292012-05-06 23:01:27 +02001197
1198static PyObject *
Nadeem Vawdaa425c3d2012-06-21 23:36:48 +02001199_decode_filter_properties(PyObject *self, PyObject *args)
Nadeem Vawdaf55b3292012-05-06 23:01:27 +02001200{
1201 Py_buffer encoded_props;
1202 lzma_filter filter;
1203 lzma_ret lzret;
1204 PyObject *result = NULL;
1205
Nadeem Vawdaa425c3d2012-06-21 23:36:48 +02001206 if (!PyArg_ParseTuple(args, "O&y*:_decode_filter_properties",
Nadeem Vawdaf55b3292012-05-06 23:01:27 +02001207 lzma_vli_converter, &filter.id, &encoded_props))
1208 return NULL;
1209
1210 lzret = lzma_properties_decode(
1211 &filter, NULL, encoded_props.buf, encoded_props.len);
1212 PyBuffer_Release(&encoded_props);
1213 if (catch_lzma_error(lzret))
1214 return NULL;
1215
1216 result = build_filter_spec(&filter);
1217
1218 /* We use vanilla free() here instead of PyMem_Free() - filter.options was
1219 allocated by lzma_properties_decode() using the default allocator. */
1220 free(filter.options);
1221 return result;
1222}
1223
1224
Nadeem Vawda3ff069e2011-11-30 00:25:06 +02001225/* Module initialization. */
1226
1227static PyMethodDef module_methods[] = {
Nadeem Vawdabc459bb2012-05-06 23:01:51 +02001228 {"is_check_supported", (PyCFunction)is_check_supported,
1229 METH_VARARGS, is_check_supported_doc},
Nadeem Vawdaa425c3d2012-06-21 23:36:48 +02001230 {"_encode_filter_properties", (PyCFunction)_encode_filter_properties,
1231 METH_VARARGS, _encode_filter_properties_doc},
1232 {"_decode_filter_properties", (PyCFunction)_decode_filter_properties,
1233 METH_VARARGS, _decode_filter_properties_doc},
Nadeem Vawda3ff069e2011-11-30 00:25:06 +02001234 {NULL}
1235};
1236
1237static PyModuleDef _lzmamodule = {
1238 PyModuleDef_HEAD_INIT,
1239 "_lzma",
1240 NULL,
1241 -1,
1242 module_methods,
1243 NULL,
1244 NULL,
1245 NULL,
1246 NULL,
1247};
1248
1249/* Some of our constants are more than 32 bits wide, so PyModule_AddIntConstant
1250 would not work correctly on platforms with 32-bit longs. */
1251static int
1252module_add_int_constant(PyObject *m, const char *name, PY_LONG_LONG value)
1253{
1254 PyObject *o = PyLong_FromLongLong(value);
1255 if (o == NULL)
1256 return -1;
1257 if (PyModule_AddObject(m, name, o) == 0)
1258 return 0;
1259 Py_DECREF(o);
1260 return -1;
1261}
1262
1263#define ADD_INT_PREFIX_MACRO(m, macro) \
1264 module_add_int_constant(m, #macro, LZMA_ ## macro)
1265
1266PyMODINIT_FUNC
1267PyInit__lzma(void)
1268{
1269 PyObject *m;
1270
1271 empty_tuple = PyTuple_New(0);
1272 if (empty_tuple == NULL)
1273 return NULL;
1274
1275 m = PyModule_Create(&_lzmamodule);
1276 if (m == NULL)
1277 return NULL;
1278
1279 if (PyModule_AddIntMacro(m, FORMAT_AUTO) == -1 ||
1280 PyModule_AddIntMacro(m, FORMAT_XZ) == -1 ||
1281 PyModule_AddIntMacro(m, FORMAT_ALONE) == -1 ||
1282 PyModule_AddIntMacro(m, FORMAT_RAW) == -1 ||
1283 ADD_INT_PREFIX_MACRO(m, CHECK_NONE) == -1 ||
1284 ADD_INT_PREFIX_MACRO(m, CHECK_CRC32) == -1 ||
1285 ADD_INT_PREFIX_MACRO(m, CHECK_CRC64) == -1 ||
1286 ADD_INT_PREFIX_MACRO(m, CHECK_SHA256) == -1 ||
1287 ADD_INT_PREFIX_MACRO(m, CHECK_ID_MAX) == -1 ||
1288 ADD_INT_PREFIX_MACRO(m, CHECK_UNKNOWN) == -1 ||
1289 ADD_INT_PREFIX_MACRO(m, FILTER_LZMA1) == -1 ||
1290 ADD_INT_PREFIX_MACRO(m, FILTER_LZMA2) == -1 ||
1291 ADD_INT_PREFIX_MACRO(m, FILTER_DELTA) == -1 ||
1292 ADD_INT_PREFIX_MACRO(m, FILTER_X86) == -1 ||
1293 ADD_INT_PREFIX_MACRO(m, FILTER_IA64) == -1 ||
1294 ADD_INT_PREFIX_MACRO(m, FILTER_ARM) == -1 ||
1295 ADD_INT_PREFIX_MACRO(m, FILTER_ARMTHUMB) == -1 ||
1296 ADD_INT_PREFIX_MACRO(m, FILTER_SPARC) == -1 ||
1297 ADD_INT_PREFIX_MACRO(m, FILTER_POWERPC) == -1 ||
1298 ADD_INT_PREFIX_MACRO(m, MF_HC3) == -1 ||
1299 ADD_INT_PREFIX_MACRO(m, MF_HC4) == -1 ||
1300 ADD_INT_PREFIX_MACRO(m, MF_BT2) == -1 ||
1301 ADD_INT_PREFIX_MACRO(m, MF_BT3) == -1 ||
1302 ADD_INT_PREFIX_MACRO(m, MF_BT4) == -1 ||
1303 ADD_INT_PREFIX_MACRO(m, MODE_FAST) == -1 ||
1304 ADD_INT_PREFIX_MACRO(m, MODE_NORMAL) == -1 ||
1305 ADD_INT_PREFIX_MACRO(m, PRESET_DEFAULT) == -1 ||
1306 ADD_INT_PREFIX_MACRO(m, PRESET_EXTREME) == -1)
1307 return NULL;
1308
1309 Error = PyErr_NewExceptionWithDoc(
1310 "_lzma.LZMAError", "Call to liblzma failed.", NULL, NULL);
1311 if (Error == NULL)
1312 return NULL;
1313 Py_INCREF(Error);
1314 if (PyModule_AddObject(m, "LZMAError", Error) == -1)
1315 return NULL;
1316
1317 if (PyType_Ready(&Compressor_type) == -1)
1318 return NULL;
1319 Py_INCREF(&Compressor_type);
1320 if (PyModule_AddObject(m, "LZMACompressor",
1321 (PyObject *)&Compressor_type) == -1)
1322 return NULL;
1323
1324 if (PyType_Ready(&Decompressor_type) == -1)
1325 return NULL;
1326 Py_INCREF(&Decompressor_type);
1327 if (PyModule_AddObject(m, "LZMADecompressor",
1328 (PyObject *)&Decompressor_type) == -1)
1329 return NULL;
1330
1331 return m;
1332}