_bz2module.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820
  1. /* _bz2 - Low-level Python interface to libbzip2. */
  2. #define PY_SSIZE_T_CLEAN
  3. #include "Python.h"
  4. #include "structmember.h" // PyMemberDef
  5. #include <bzlib.h>
  6. #include <stdio.h>
  7. // Blocks output buffer wrappers
  8. #include "pycore_blocks_output_buffer.h"
  9. #if OUTPUT_BUFFER_MAX_BLOCK_SIZE > UINT32_MAX
  10. #error "The maximum block size accepted by libbzip2 is UINT32_MAX."
  11. #endif
  12. typedef struct {
  13. PyTypeObject *bz2_compressor_type;
  14. PyTypeObject *bz2_decompressor_type;
  15. } _bz2_state;
  16. static inline _bz2_state *
  17. get_module_state(PyObject *module)
  18. {
  19. void *state = PyModule_GetState(module);
  20. assert(state != NULL);
  21. return (_bz2_state *)state;
  22. }
  23. static struct PyModuleDef _bz2module;
  24. static inline _bz2_state *
  25. find_module_state_by_def(PyTypeObject *type)
  26. {
  27. PyObject *module = PyType_GetModuleByDef(type, &_bz2module);
  28. assert(module != NULL);
  29. return get_module_state(module);
  30. }
  31. /* On success, return value >= 0
  32. On failure, return -1 */
  33. static inline Py_ssize_t
  34. OutputBuffer_InitAndGrow(_BlocksOutputBuffer *buffer, Py_ssize_t max_length,
  35. char **next_out, uint32_t *avail_out)
  36. {
  37. Py_ssize_t allocated;
  38. allocated = _BlocksOutputBuffer_InitAndGrow(
  39. buffer, max_length, (void**) next_out);
  40. *avail_out = (uint32_t) allocated;
  41. return allocated;
  42. }
  43. /* On success, return value >= 0
  44. On failure, return -1 */
  45. static inline Py_ssize_t
  46. OutputBuffer_Grow(_BlocksOutputBuffer *buffer,
  47. char **next_out, uint32_t *avail_out)
  48. {
  49. Py_ssize_t allocated;
  50. allocated = _BlocksOutputBuffer_Grow(
  51. buffer, (void**) next_out, (Py_ssize_t) *avail_out);
  52. *avail_out = (uint32_t) allocated;
  53. return allocated;
  54. }
  55. static inline Py_ssize_t
  56. OutputBuffer_GetDataSize(_BlocksOutputBuffer *buffer, uint32_t avail_out)
  57. {
  58. return _BlocksOutputBuffer_GetDataSize(buffer, (Py_ssize_t) avail_out);
  59. }
  60. static inline PyObject *
  61. OutputBuffer_Finish(_BlocksOutputBuffer *buffer, uint32_t avail_out)
  62. {
  63. return _BlocksOutputBuffer_Finish(buffer, (Py_ssize_t) avail_out);
  64. }
  65. static inline void
  66. OutputBuffer_OnError(_BlocksOutputBuffer *buffer)
  67. {
  68. _BlocksOutputBuffer_OnError(buffer);
  69. }
  70. #ifndef BZ_CONFIG_ERROR
  71. #define BZ2_bzCompress bzCompress
  72. #define BZ2_bzCompressInit bzCompressInit
  73. #define BZ2_bzCompressEnd bzCompressEnd
  74. #define BZ2_bzDecompress bzDecompress
  75. #define BZ2_bzDecompressInit bzDecompressInit
  76. #define BZ2_bzDecompressEnd bzDecompressEnd
  77. #endif /* ! BZ_CONFIG_ERROR */
  78. #define ACQUIRE_LOCK(obj) do { \
  79. if (!PyThread_acquire_lock((obj)->lock, 0)) { \
  80. Py_BEGIN_ALLOW_THREADS \
  81. PyThread_acquire_lock((obj)->lock, 1); \
  82. Py_END_ALLOW_THREADS \
  83. } } while (0)
  84. #define RELEASE_LOCK(obj) PyThread_release_lock((obj)->lock)
  85. typedef struct {
  86. PyObject_HEAD
  87. bz_stream bzs;
  88. int flushed;
  89. PyThread_type_lock lock;
  90. } BZ2Compressor;
  91. typedef struct {
  92. PyObject_HEAD
  93. bz_stream bzs;
  94. char eof; /* T_BOOL expects a char */
  95. PyObject *unused_data;
  96. char needs_input;
  97. char *input_buffer;
  98. size_t input_buffer_size;
  99. /* bzs->avail_in is only 32 bit, so we store the true length
  100. separately. Conversion and looping is encapsulated in
  101. decompress_buf() */
  102. size_t bzs_avail_in_real;
  103. PyThread_type_lock lock;
  104. } BZ2Decompressor;
  105. /* Helper functions. */
  106. static int
  107. catch_bz2_error(int bzerror)
  108. {
  109. switch(bzerror) {
  110. case BZ_OK:
  111. case BZ_RUN_OK:
  112. case BZ_FLUSH_OK:
  113. case BZ_FINISH_OK:
  114. case BZ_STREAM_END:
  115. return 0;
  116. #ifdef BZ_CONFIG_ERROR
  117. case BZ_CONFIG_ERROR:
  118. PyErr_SetString(PyExc_SystemError,
  119. "libbzip2 was not compiled correctly");
  120. return 1;
  121. #endif
  122. case BZ_PARAM_ERROR:
  123. PyErr_SetString(PyExc_ValueError,
  124. "Internal error - "
  125. "invalid parameters passed to libbzip2");
  126. return 1;
  127. case BZ_MEM_ERROR:
  128. PyErr_NoMemory();
  129. return 1;
  130. case BZ_DATA_ERROR:
  131. case BZ_DATA_ERROR_MAGIC:
  132. PyErr_SetString(PyExc_OSError, "Invalid data stream");
  133. return 1;
  134. case BZ_IO_ERROR:
  135. PyErr_SetString(PyExc_OSError, "Unknown I/O error");
  136. return 1;
  137. case BZ_UNEXPECTED_EOF:
  138. PyErr_SetString(PyExc_EOFError,
  139. "Compressed file ended before the logical "
  140. "end-of-stream was detected");
  141. return 1;
  142. case BZ_SEQUENCE_ERROR:
  143. PyErr_SetString(PyExc_RuntimeError,
  144. "Internal error - "
  145. "Invalid sequence of commands sent to libbzip2");
  146. return 1;
  147. default:
  148. PyErr_Format(PyExc_OSError,
  149. "Unrecognized error from libbzip2: %d", bzerror);
  150. return 1;
  151. }
  152. }
  153. /* BZ2Compressor class. */
  154. static PyObject *
  155. compress(BZ2Compressor *c, char *data, size_t len, int action)
  156. {
  157. PyObject *result;
  158. _BlocksOutputBuffer buffer = {.list = NULL};
  159. if (OutputBuffer_InitAndGrow(&buffer, -1, &c->bzs.next_out, &c->bzs.avail_out) < 0) {
  160. goto error;
  161. }
  162. c->bzs.next_in = data;
  163. c->bzs.avail_in = 0;
  164. for (;;) {
  165. int bzerror;
  166. /* On a 64-bit system, len might not fit in avail_in (an unsigned int).
  167. Do compression in chunks of no more than UINT_MAX bytes each. */
  168. if (c->bzs.avail_in == 0 && len > 0) {
  169. c->bzs.avail_in = (unsigned int)Py_MIN(len, UINT_MAX);
  170. len -= c->bzs.avail_in;
  171. }
  172. /* In regular compression mode, stop when input data is exhausted. */
  173. if (action == BZ_RUN && c->bzs.avail_in == 0)
  174. break;
  175. if (c->bzs.avail_out == 0) {
  176. if (OutputBuffer_Grow(&buffer, &c->bzs.next_out, &c->bzs.avail_out) < 0) {
  177. goto error;
  178. }
  179. }
  180. Py_BEGIN_ALLOW_THREADS
  181. bzerror = BZ2_bzCompress(&c->bzs, action);
  182. Py_END_ALLOW_THREADS
  183. if (catch_bz2_error(bzerror))
  184. goto error;
  185. /* In flushing mode, stop when all buffered data has been flushed. */
  186. if (action == BZ_FINISH && bzerror == BZ_STREAM_END)
  187. break;
  188. }
  189. result = OutputBuffer_Finish(&buffer, c->bzs.avail_out);
  190. if (result != NULL) {
  191. return result;
  192. }
  193. error:
  194. OutputBuffer_OnError(&buffer);
  195. return NULL;
  196. }
  197. /*[clinic input]
  198. module _bz2
  199. class _bz2.BZ2Compressor "BZ2Compressor *" "clinic_state()->bz2_compressor_type"
  200. class _bz2.BZ2Decompressor "BZ2Decompressor *" "clinic_state()->bz2_decompressor_type"
  201. [clinic start generated code]*/
  202. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=92348121632b94c4]*/
  203. #define clinic_state() (find_module_state_by_def(type))
  204. #include "clinic/_bz2module.c.h"
  205. #undef clinic_state
  206. /*[clinic input]
  207. _bz2.BZ2Compressor.compress
  208. data: Py_buffer
  209. /
  210. Provide data to the compressor object.
  211. Returns a chunk of compressed data if possible, or b'' otherwise.
  212. When you have finished providing data to the compressor, call the
  213. flush() method to finish the compression process.
  214. [clinic start generated code]*/
  215. static PyObject *
  216. _bz2_BZ2Compressor_compress_impl(BZ2Compressor *self, Py_buffer *data)
  217. /*[clinic end generated code: output=59365426e941fbcc input=85c963218070fc4c]*/
  218. {
  219. PyObject *result = NULL;
  220. ACQUIRE_LOCK(self);
  221. if (self->flushed)
  222. PyErr_SetString(PyExc_ValueError, "Compressor has been flushed");
  223. else
  224. result = compress(self, data->buf, data->len, BZ_RUN);
  225. RELEASE_LOCK(self);
  226. return result;
  227. }
  228. /*[clinic input]
  229. _bz2.BZ2Compressor.flush
  230. Finish the compression process.
  231. Returns the compressed data left in internal buffers.
  232. The compressor object may not be used after this method is called.
  233. [clinic start generated code]*/
  234. static PyObject *
  235. _bz2_BZ2Compressor_flush_impl(BZ2Compressor *self)
  236. /*[clinic end generated code: output=3ef03fc1b092a701 input=d64405d3c6f76691]*/
  237. {
  238. PyObject *result = NULL;
  239. ACQUIRE_LOCK(self);
  240. if (self->flushed)
  241. PyErr_SetString(PyExc_ValueError, "Repeated call to flush()");
  242. else {
  243. self->flushed = 1;
  244. result = compress(self, NULL, 0, BZ_FINISH);
  245. }
  246. RELEASE_LOCK(self);
  247. return result;
  248. }
  249. static void*
  250. BZ2_Malloc(void* ctx, int items, int size)
  251. {
  252. if (items < 0 || size < 0)
  253. return NULL;
  254. if (size != 0 && (size_t)items > (size_t)PY_SSIZE_T_MAX / (size_t)size)
  255. return NULL;
  256. /* PyMem_Malloc() cannot be used: compress() and decompress()
  257. release the GIL */
  258. return PyMem_RawMalloc((size_t)items * (size_t)size);
  259. }
  260. static void
  261. BZ2_Free(void* ctx, void *ptr)
  262. {
  263. PyMem_RawFree(ptr);
  264. }
  265. /*[clinic input]
  266. @classmethod
  267. _bz2.BZ2Compressor.__new__
  268. compresslevel: int = 9
  269. Compression level, as a number between 1 and 9.
  270. /
  271. Create a compressor object for compressing data incrementally.
  272. For one-shot compression, use the compress() function instead.
  273. [clinic start generated code]*/
  274. static PyObject *
  275. _bz2_BZ2Compressor_impl(PyTypeObject *type, int compresslevel)
  276. /*[clinic end generated code: output=83346c96beaacad7 input=d4500d2a52c8b263]*/
  277. {
  278. int bzerror;
  279. BZ2Compressor *self;
  280. if (!(1 <= compresslevel && compresslevel <= 9)) {
  281. PyErr_SetString(PyExc_ValueError,
  282. "compresslevel must be between 1 and 9");
  283. return NULL;
  284. }
  285. assert(type != NULL && type->tp_alloc != NULL);
  286. self = (BZ2Compressor *)type->tp_alloc(type, 0);
  287. if (self == NULL) {
  288. return NULL;
  289. }
  290. self->lock = PyThread_allocate_lock();
  291. if (self->lock == NULL) {
  292. Py_DECREF(self);
  293. PyErr_SetString(PyExc_MemoryError, "Unable to allocate lock");
  294. return NULL;
  295. }
  296. self->bzs.opaque = NULL;
  297. self->bzs.bzalloc = BZ2_Malloc;
  298. self->bzs.bzfree = BZ2_Free;
  299. bzerror = BZ2_bzCompressInit(&self->bzs, compresslevel, 0, 0);
  300. if (catch_bz2_error(bzerror))
  301. goto error;
  302. return (PyObject *)self;
  303. error:
  304. Py_DECREF(self);
  305. return NULL;
  306. }
  307. static void
  308. BZ2Compressor_dealloc(BZ2Compressor *self)
  309. {
  310. BZ2_bzCompressEnd(&self->bzs);
  311. if (self->lock != NULL) {
  312. PyThread_free_lock(self->lock);
  313. }
  314. PyTypeObject *tp = Py_TYPE(self);
  315. tp->tp_free((PyObject *)self);
  316. Py_DECREF(tp);
  317. }
  318. static int
  319. BZ2Compressor_traverse(BZ2Compressor *self, visitproc visit, void *arg)
  320. {
  321. Py_VISIT(Py_TYPE(self));
  322. return 0;
  323. }
  324. static PyMethodDef BZ2Compressor_methods[] = {
  325. _BZ2_BZ2COMPRESSOR_COMPRESS_METHODDEF
  326. _BZ2_BZ2COMPRESSOR_FLUSH_METHODDEF
  327. {NULL}
  328. };
  329. static PyType_Slot bz2_compressor_type_slots[] = {
  330. {Py_tp_dealloc, BZ2Compressor_dealloc},
  331. {Py_tp_methods, BZ2Compressor_methods},
  332. {Py_tp_new, _bz2_BZ2Compressor},
  333. {Py_tp_doc, (char *)_bz2_BZ2Compressor__doc__},
  334. {Py_tp_traverse, BZ2Compressor_traverse},
  335. {0, 0}
  336. };
  337. static PyType_Spec bz2_compressor_type_spec = {
  338. .name = "_bz2.BZ2Compressor",
  339. .basicsize = sizeof(BZ2Compressor),
  340. // Calling PyType_GetModuleState() on a subclass is not safe.
  341. // bz2_compressor_type_spec does not have Py_TPFLAGS_BASETYPE flag
  342. // which prevents to create a subclass.
  343. // So calling PyType_GetModuleState() in this file is always safe.
  344. .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_IMMUTABLETYPE),
  345. .slots = bz2_compressor_type_slots,
  346. };
  347. /* BZ2Decompressor class. */
  348. /* Decompress data of length d->bzs_avail_in_real in d->bzs.next_in. The output
  349. buffer is allocated dynamically and returned. At most max_length bytes are
  350. returned, so some of the input may not be consumed. d->bzs.next_in and
  351. d->bzs_avail_in_real are updated to reflect the consumed input. */
  352. static PyObject*
  353. decompress_buf(BZ2Decompressor *d, Py_ssize_t max_length)
  354. {
  355. /* data_size is strictly positive, but because we repeatedly have to
  356. compare against max_length and PyBytes_GET_SIZE we declare it as
  357. signed */
  358. PyObject *result;
  359. _BlocksOutputBuffer buffer = {.list = NULL};
  360. bz_stream *bzs = &d->bzs;
  361. if (OutputBuffer_InitAndGrow(&buffer, max_length, &bzs->next_out, &bzs->avail_out) < 0) {
  362. goto error;
  363. }
  364. for (;;) {
  365. int bzret;
  366. /* On a 64-bit system, buffer length might not fit in avail_out, so we
  367. do decompression in chunks of no more than UINT_MAX bytes
  368. each. Note that the expression for `avail` is guaranteed to be
  369. positive, so the cast is safe. */
  370. bzs->avail_in = (unsigned int)Py_MIN(d->bzs_avail_in_real, UINT_MAX);
  371. d->bzs_avail_in_real -= bzs->avail_in;
  372. Py_BEGIN_ALLOW_THREADS
  373. bzret = BZ2_bzDecompress(bzs);
  374. Py_END_ALLOW_THREADS
  375. d->bzs_avail_in_real += bzs->avail_in;
  376. if (catch_bz2_error(bzret))
  377. goto error;
  378. if (bzret == BZ_STREAM_END) {
  379. d->eof = 1;
  380. break;
  381. } else if (d->bzs_avail_in_real == 0) {
  382. break;
  383. } else if (bzs->avail_out == 0) {
  384. if (OutputBuffer_GetDataSize(&buffer, bzs->avail_out) == max_length) {
  385. break;
  386. }
  387. if (OutputBuffer_Grow(&buffer, &bzs->next_out, &bzs->avail_out) < 0) {
  388. goto error;
  389. }
  390. }
  391. }
  392. result = OutputBuffer_Finish(&buffer, bzs->avail_out);
  393. if (result != NULL) {
  394. return result;
  395. }
  396. error:
  397. OutputBuffer_OnError(&buffer);
  398. return NULL;
  399. }
  400. static PyObject *
  401. decompress(BZ2Decompressor *d, char *data, size_t len, Py_ssize_t max_length)
  402. {
  403. char input_buffer_in_use;
  404. PyObject *result;
  405. bz_stream *bzs = &d->bzs;
  406. /* Prepend unconsumed input if necessary */
  407. if (bzs->next_in != NULL) {
  408. size_t avail_now, avail_total;
  409. /* Number of bytes we can append to input buffer */
  410. avail_now = (d->input_buffer + d->input_buffer_size)
  411. - (bzs->next_in + d->bzs_avail_in_real);
  412. /* Number of bytes we can append if we move existing
  413. contents to beginning of buffer (overwriting
  414. consumed input) */
  415. avail_total = d->input_buffer_size - d->bzs_avail_in_real;
  416. if (avail_total < len) {
  417. size_t offset = bzs->next_in - d->input_buffer;
  418. char *tmp;
  419. size_t new_size = d->input_buffer_size + len - avail_now;
  420. /* Assign to temporary variable first, so we don't
  421. lose address of allocated buffer if realloc fails */
  422. tmp = PyMem_Realloc(d->input_buffer, new_size);
  423. if (tmp == NULL) {
  424. PyErr_SetNone(PyExc_MemoryError);
  425. return NULL;
  426. }
  427. d->input_buffer = tmp;
  428. d->input_buffer_size = new_size;
  429. bzs->next_in = d->input_buffer + offset;
  430. }
  431. else if (avail_now < len) {
  432. memmove(d->input_buffer, bzs->next_in,
  433. d->bzs_avail_in_real);
  434. bzs->next_in = d->input_buffer;
  435. }
  436. memcpy((void*)(bzs->next_in + d->bzs_avail_in_real), data, len);
  437. d->bzs_avail_in_real += len;
  438. input_buffer_in_use = 1;
  439. }
  440. else {
  441. bzs->next_in = data;
  442. d->bzs_avail_in_real = len;
  443. input_buffer_in_use = 0;
  444. }
  445. result = decompress_buf(d, max_length);
  446. if(result == NULL) {
  447. bzs->next_in = NULL;
  448. return NULL;
  449. }
  450. if (d->eof) {
  451. d->needs_input = 0;
  452. if (d->bzs_avail_in_real > 0) {
  453. Py_XSETREF(d->unused_data,
  454. PyBytes_FromStringAndSize(bzs->next_in, d->bzs_avail_in_real));
  455. if (d->unused_data == NULL)
  456. goto error;
  457. }
  458. }
  459. else if (d->bzs_avail_in_real == 0) {
  460. bzs->next_in = NULL;
  461. d->needs_input = 1;
  462. }
  463. else {
  464. d->needs_input = 0;
  465. /* If we did not use the input buffer, we now have
  466. to copy the tail from the caller's buffer into the
  467. input buffer */
  468. if (!input_buffer_in_use) {
  469. /* Discard buffer if it's too small
  470. (resizing it may needlessly copy the current contents) */
  471. if (d->input_buffer != NULL &&
  472. d->input_buffer_size < d->bzs_avail_in_real) {
  473. PyMem_Free(d->input_buffer);
  474. d->input_buffer = NULL;
  475. }
  476. /* Allocate if necessary */
  477. if (d->input_buffer == NULL) {
  478. d->input_buffer = PyMem_Malloc(d->bzs_avail_in_real);
  479. if (d->input_buffer == NULL) {
  480. PyErr_SetNone(PyExc_MemoryError);
  481. goto error;
  482. }
  483. d->input_buffer_size = d->bzs_avail_in_real;
  484. }
  485. /* Copy tail */
  486. memcpy(d->input_buffer, bzs->next_in, d->bzs_avail_in_real);
  487. bzs->next_in = d->input_buffer;
  488. }
  489. }
  490. return result;
  491. error:
  492. Py_XDECREF(result);
  493. return NULL;
  494. }
  495. /*[clinic input]
  496. _bz2.BZ2Decompressor.decompress
  497. data: Py_buffer
  498. max_length: Py_ssize_t=-1
  499. Decompress *data*, returning uncompressed data as bytes.
  500. If *max_length* is nonnegative, returns at most *max_length* bytes of
  501. decompressed data. If this limit is reached and further output can be
  502. produced, *self.needs_input* will be set to ``False``. In this case, the next
  503. call to *decompress()* may provide *data* as b'' to obtain more of the output.
  504. If all of the input data was decompressed and returned (either because this
  505. was less than *max_length* bytes, or because *max_length* was negative),
  506. *self.needs_input* will be set to True.
  507. Attempting to decompress data after the end of stream is reached raises an
  508. EOFError. Any data found after the end of the stream is ignored and saved in
  509. the unused_data attribute.
  510. [clinic start generated code]*/
  511. static PyObject *
  512. _bz2_BZ2Decompressor_decompress_impl(BZ2Decompressor *self, Py_buffer *data,
  513. Py_ssize_t max_length)
  514. /*[clinic end generated code: output=23e41045deb240a3 input=52e1ffc66a8ea624]*/
  515. {
  516. PyObject *result = NULL;
  517. ACQUIRE_LOCK(self);
  518. if (self->eof)
  519. PyErr_SetString(PyExc_EOFError, "End of stream already reached");
  520. else
  521. result = decompress(self, data->buf, data->len, max_length);
  522. RELEASE_LOCK(self);
  523. return result;
  524. }
  525. /*[clinic input]
  526. @classmethod
  527. _bz2.BZ2Decompressor.__new__
  528. Create a decompressor object for decompressing data incrementally.
  529. For one-shot decompression, use the decompress() function instead.
  530. [clinic start generated code]*/
  531. static PyObject *
  532. _bz2_BZ2Decompressor_impl(PyTypeObject *type)
  533. /*[clinic end generated code: output=5150d51ccaab220e input=b87413ce51853528]*/
  534. {
  535. BZ2Decompressor *self;
  536. int bzerror;
  537. assert(type != NULL && type->tp_alloc != NULL);
  538. self = (BZ2Decompressor *)type->tp_alloc(type, 0);
  539. if (self == NULL) {
  540. return NULL;
  541. }
  542. self->lock = PyThread_allocate_lock();
  543. if (self->lock == NULL) {
  544. Py_DECREF(self);
  545. PyErr_SetString(PyExc_MemoryError, "Unable to allocate lock");
  546. return NULL;
  547. }
  548. self->needs_input = 1;
  549. self->bzs_avail_in_real = 0;
  550. self->input_buffer = NULL;
  551. self->input_buffer_size = 0;
  552. self->unused_data = PyBytes_FromStringAndSize(NULL, 0);
  553. if (self->unused_data == NULL)
  554. goto error;
  555. bzerror = BZ2_bzDecompressInit(&self->bzs, 0, 0);
  556. if (catch_bz2_error(bzerror))
  557. goto error;
  558. return (PyObject *)self;
  559. error:
  560. Py_DECREF(self);
  561. return NULL;
  562. }
  563. static void
  564. BZ2Decompressor_dealloc(BZ2Decompressor *self)
  565. {
  566. if(self->input_buffer != NULL) {
  567. PyMem_Free(self->input_buffer);
  568. }
  569. BZ2_bzDecompressEnd(&self->bzs);
  570. Py_CLEAR(self->unused_data);
  571. if (self->lock != NULL) {
  572. PyThread_free_lock(self->lock);
  573. }
  574. PyTypeObject *tp = Py_TYPE(self);
  575. tp->tp_free((PyObject *)self);
  576. Py_DECREF(tp);
  577. }
  578. static int
  579. BZ2Decompressor_traverse(BZ2Decompressor *self, visitproc visit, void *arg)
  580. {
  581. Py_VISIT(Py_TYPE(self));
  582. return 0;
  583. }
  584. static PyMethodDef BZ2Decompressor_methods[] = {
  585. _BZ2_BZ2DECOMPRESSOR_DECOMPRESS_METHODDEF
  586. {NULL}
  587. };
  588. PyDoc_STRVAR(BZ2Decompressor_eof__doc__,
  589. "True if the end-of-stream marker has been reached.");
  590. PyDoc_STRVAR(BZ2Decompressor_unused_data__doc__,
  591. "Data found after the end of the compressed stream.");
  592. PyDoc_STRVAR(BZ2Decompressor_needs_input_doc,
  593. "True if more input is needed before more decompressed data can be produced.");
  594. static PyMemberDef BZ2Decompressor_members[] = {
  595. {"eof", T_BOOL, offsetof(BZ2Decompressor, eof),
  596. READONLY, BZ2Decompressor_eof__doc__},
  597. {"unused_data", T_OBJECT_EX, offsetof(BZ2Decompressor, unused_data),
  598. READONLY, BZ2Decompressor_unused_data__doc__},
  599. {"needs_input", T_BOOL, offsetof(BZ2Decompressor, needs_input), READONLY,
  600. BZ2Decompressor_needs_input_doc},
  601. {NULL}
  602. };
  603. static PyType_Slot bz2_decompressor_type_slots[] = {
  604. {Py_tp_dealloc, BZ2Decompressor_dealloc},
  605. {Py_tp_methods, BZ2Decompressor_methods},
  606. {Py_tp_doc, (char *)_bz2_BZ2Decompressor__doc__},
  607. {Py_tp_members, BZ2Decompressor_members},
  608. {Py_tp_new, _bz2_BZ2Decompressor},
  609. {Py_tp_traverse, BZ2Decompressor_traverse},
  610. {0, 0}
  611. };
  612. static PyType_Spec bz2_decompressor_type_spec = {
  613. .name = "_bz2.BZ2Decompressor",
  614. .basicsize = sizeof(BZ2Decompressor),
  615. // Calling PyType_GetModuleState() on a subclass is not safe.
  616. // bz2_decompressor_type_spec does not have Py_TPFLAGS_BASETYPE flag
  617. // which prevents to create a subclass.
  618. // So calling PyType_GetModuleState() in this file is always safe.
  619. .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_IMMUTABLETYPE),
  620. .slots = bz2_decompressor_type_slots,
  621. };
  622. /* Module initialization. */
  623. static int
  624. _bz2_exec(PyObject *module)
  625. {
  626. _bz2_state *state = get_module_state(module);
  627. state->bz2_compressor_type = (PyTypeObject *)PyType_FromModuleAndSpec(module,
  628. &bz2_compressor_type_spec, NULL);
  629. if (state->bz2_compressor_type == NULL) {
  630. return -1;
  631. }
  632. if (PyModule_AddType(module, state->bz2_compressor_type) < 0) {
  633. return -1;
  634. }
  635. state->bz2_decompressor_type = (PyTypeObject *)PyType_FromModuleAndSpec(module,
  636. &bz2_decompressor_type_spec, NULL);
  637. if (state->bz2_decompressor_type == NULL) {
  638. return -1;
  639. }
  640. if (PyModule_AddType(module, state->bz2_decompressor_type) < 0) {
  641. return -1;
  642. }
  643. return 0;
  644. }
  645. static int
  646. _bz2_traverse(PyObject *module, visitproc visit, void *arg)
  647. {
  648. _bz2_state *state = get_module_state(module);
  649. Py_VISIT(state->bz2_compressor_type);
  650. Py_VISIT(state->bz2_decompressor_type);
  651. return 0;
  652. }
  653. static int
  654. _bz2_clear(PyObject *module)
  655. {
  656. _bz2_state *state = get_module_state(module);
  657. Py_CLEAR(state->bz2_compressor_type);
  658. Py_CLEAR(state->bz2_decompressor_type);
  659. return 0;
  660. }
  661. static void
  662. _bz2_free(void *module)
  663. {
  664. (void)_bz2_clear((PyObject *)module);
  665. }
  666. static struct PyModuleDef_Slot _bz2_slots[] = {
  667. {Py_mod_exec, _bz2_exec},
  668. {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
  669. {0, NULL}
  670. };
  671. static struct PyModuleDef _bz2module = {
  672. .m_base = PyModuleDef_HEAD_INIT,
  673. .m_name = "_bz2",
  674. .m_size = sizeof(_bz2_state),
  675. .m_traverse = _bz2_traverse,
  676. .m_clear = _bz2_clear,
  677. .m_free = _bz2_free,
  678. .m_slots = _bz2_slots,
  679. };
  680. PyMODINIT_FUNC
  681. PyInit__bz2(void)
  682. {
  683. return PyModuleDef_Init(&_bz2module);
  684. }