_lzma.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802
  1. # This file is based on lzmaffi/_lzmamodule2.py from lzmaffi version 0.3.0.
  2. # PyPy changes:
  3. # - added __getstate__() methods that raise TypeError on pickling.
  4. # - ported to CFFI 1.0
  5. import threading
  6. import functools
  7. import collections
  8. import weakref
  9. import sys
  10. import io
  11. import __pypy__
  12. from _lzma_cffi import ffi, lib as m
  13. SUPPORTED_STREAM_FLAGS_VERSION = 0
  14. __all__ = ['CHECK_CRC32',
  15. 'CHECK_CRC64',
  16. 'CHECK_ID_MAX',
  17. 'CHECK_NONE',
  18. 'CHECK_SHA256',
  19. 'CHECK_UNKNOWN',
  20. 'FILTER_ARM',
  21. 'FILTER_ARMTHUMB',
  22. 'FILTER_DELTA',
  23. 'FILTER_IA64',
  24. 'FILTER_LZMA1',
  25. 'FILTER_LZMA2',
  26. 'FILTER_POWERPC',
  27. 'FILTER_SPARC',
  28. 'FILTER_X86',
  29. 'FORMAT_ALONE',
  30. 'FORMAT_AUTO',
  31. 'FORMAT_RAW',
  32. 'FORMAT_XZ',
  33. 'FORMAT_BLOCK',
  34. 'LZMACompressor',
  35. 'LZMADecompressor',
  36. 'LZMAError',
  37. 'MF_BT2',
  38. 'MF_BT3',
  39. 'MF_BT4',
  40. 'MF_HC3',
  41. 'MF_HC4',
  42. 'MODE_FAST',
  43. 'MODE_NORMAL',
  44. 'PRESET_DEFAULT',
  45. 'PRESET_EXTREME',
  46. 'STREAM_HEADER_SIZE',
  47. 'decode_block_header_size',
  48. 'decode_stream_header',
  49. 'decode_stream_footer',
  50. 'decode_index',
  51. '_decode_filter_properties',
  52. '_encode_filter_properties',
  53. 'is_check_supported']
  54. _owns = weakref.WeakKeyDictionary()
  55. def _new_lzma_stream():
  56. ret = ffi.new('lzma_stream*')
  57. m._pylzma_stream_init(ret)
  58. return ffi.gc(ret, m.lzma_end)
  59. def _release_lzma_stream(st):
  60. ffi.gc(st, None)
  61. m.lzma_end(st)
  62. def add_constant(c):
  63. globals()[c] = getattr(m, 'LZMA_' + c)
  64. if sys.version_info >= (2,7):
  65. def to_bytes(data):
  66. return memoryview(data).tobytes()
  67. else:
  68. def to_bytes(data):
  69. if not isinstance(data, basestring):
  70. raise TypeError("lzma: must be str/unicode, got %s" % (type(data),))
  71. return bytes(data)
  72. if sys.version_info >= (3,0):
  73. long = int
  74. for c in ['CHECK_CRC32', 'CHECK_CRC64', 'CHECK_ID_MAX', 'CHECK_NONE', 'CHECK_SHA256', 'FILTER_ARM', 'FILTER_ARMTHUMB', 'FILTER_DELTA', 'FILTER_IA64', 'FILTER_LZMA1', 'FILTER_LZMA2', 'FILTER_POWERPC', 'FILTER_SPARC', 'FILTER_X86', 'MF_BT2', 'MF_BT3', 'MF_BT4', 'MF_HC3', 'MF_HC4', 'MODE_FAST', 'MODE_NORMAL', 'PRESET_DEFAULT', 'PRESET_EXTREME', 'STREAM_HEADER_SIZE']:
  75. add_constant(c)
  76. def _parse_format(format):
  77. if isinstance(format, (int, long)):
  78. return format
  79. else:
  80. raise TypeError
  81. CHECK_UNKNOWN = CHECK_ID_MAX + 1
  82. FORMAT_AUTO, FORMAT_XZ, FORMAT_ALONE, FORMAT_RAW, FORMAT_BLOCK = range(5)
  83. BCJ_FILTERS = (m.LZMA_FILTER_X86,
  84. m.LZMA_FILTER_POWERPC,
  85. m.LZMA_FILTER_IA64,
  86. m.LZMA_FILTER_ARM,
  87. m.LZMA_FILTER_ARMTHUMB,
  88. m.LZMA_FILTER_SPARC)
  89. class LZMAError(Exception):
  90. """Call to liblzma failed."""
  91. def is_check_supported(check):
  92. """is_check_supported(check_id) -> bool
  93. Test whether the given integrity check is supported.
  94. Always returns True for CHECK_NONE and CHECK_CRC32."""
  95. return bool(m.lzma_check_is_supported(check))
  96. def catch_lzma_error(fun, *args, ignore_buf_error=False):
  97. try:
  98. lzret = fun(*args)
  99. except:
  100. raise
  101. if lzret in (m.LZMA_OK, m.LZMA_GET_CHECK, m.LZMA_NO_CHECK, m.LZMA_STREAM_END):
  102. return lzret
  103. elif lzret == m.LZMA_DATA_ERROR:
  104. raise LZMAError("Corrupt input data")
  105. elif lzret == m.LZMA_UNSUPPORTED_CHECK:
  106. raise LZMAError("Unsupported integrity check")
  107. elif lzret == m.LZMA_FORMAT_ERROR:
  108. raise LZMAError("Input format not supported by decoder")
  109. elif lzret == m.LZMA_OPTIONS_ERROR:
  110. raise LZMAError("Invalid or unsupported options")
  111. elif lzret == m.LZMA_BUF_ERROR:
  112. if ignore_buf_error:
  113. return m.LZMA_OK
  114. raise LZMAError("Insufficient buffer space")
  115. elif lzret == m.LZMA_PROG_ERROR:
  116. raise LZMAError("Internal error")
  117. elif lzret == m.LZMA_MEM_ERROR:
  118. raise MemoryError
  119. else:
  120. raise LZMAError("Unrecognised error from liblzma: %d" % lzret)
  121. def parse_filter_spec_delta(id, dist=1):
  122. ret = ffi.new('lzma_options_delta*')
  123. ret.type = m.LZMA_DELTA_TYPE_BYTE
  124. ret.dist = dist
  125. return ret
  126. def parse_filter_spec_bcj(id, start_offset=0):
  127. ret = ffi.new('lzma_options_bcj*')
  128. ret.start_offset = start_offset
  129. return ret
  130. def parse_filter_spec_lzma(id, preset=m.LZMA_PRESET_DEFAULT, **kwargs):
  131. ret = ffi.new('lzma_options_lzma*')
  132. if m.lzma_lzma_preset(ret, preset):
  133. raise LZMAError("Invalid compression preset: %s" % preset)
  134. for arg, val in kwargs.items():
  135. if arg in ('dict_size', 'lc', 'lp', 'pb', 'nice_len', 'depth'):
  136. setattr(ret, arg, val)
  137. elif arg in ('mf', 'mode'):
  138. setattr(ret, arg, int(val))
  139. else:
  140. raise ValueError("Invalid filter specifier for LZMA filter")
  141. return ret
  142. def parse_filter_spec(spec):
  143. if not isinstance(spec, collections.Mapping):
  144. raise TypeError("Filter specifier must be a dict or dict-like object")
  145. ret = ffi.new('lzma_filter*')
  146. try:
  147. ret.id = spec['id']
  148. except KeyError:
  149. raise ValueError("Filter specifier must have an \"id\" entry")
  150. if ret.id in (m.LZMA_FILTER_LZMA1, m.LZMA_FILTER_LZMA2):
  151. try:
  152. options = parse_filter_spec_lzma(**spec)
  153. except TypeError:
  154. raise ValueError("Invalid filter specifier for LZMA filter")
  155. elif ret.id == m.LZMA_FILTER_DELTA:
  156. try:
  157. options = parse_filter_spec_delta(**spec)
  158. except TypeError:
  159. raise ValueError("Invalid filter specifier for delta filter")
  160. elif ret.id in BCJ_FILTERS:
  161. try:
  162. options = parse_filter_spec_bcj(**spec)
  163. except TypeError:
  164. raise ValueError("Invalid filter specifier for BCJ filter")
  165. else:
  166. raise ValueError("Invalid %d" % (ret.id,))
  167. ret.options = options
  168. _owns[ret] = options
  169. return ret
  170. def _encode_filter_properties(filterspec):
  171. """_encode_filter_properties(filter) -> bytes
  172. Return a bytes object encoding the options (properties) of the filter
  173. specified by *filter* (a dict).
  174. The result does not include the filter ID itself, only the options."""
  175. filter = parse_filter_spec(filterspec)
  176. size = ffi.new("uint32_t*")
  177. catch_lzma_error(m.lzma_properties_size, size, filter)
  178. result = ffi.new('uint8_t[]', size[0])
  179. catch_lzma_error(m.lzma_properties_encode, filter, result)
  180. return ffi.buffer(result)[:]
  181. def parse_filter_chain_spec(filterspecs):
  182. if len(filterspecs) > m.LZMA_FILTERS_MAX:
  183. raise ValueError(
  184. "Too many filters - liblzma supports a maximum of %s" %
  185. m.LZMA_FILTERS_MAX)
  186. filters = ffi.new('lzma_filter[]', m.LZMA_FILTERS_MAX+1)
  187. _owns[filters] = children = []
  188. for i in range(m.LZMA_FILTERS_MAX+1):
  189. try:
  190. filterspec = filterspecs[i]
  191. except KeyError:
  192. raise TypeError
  193. except IndexError:
  194. filters[i].id = m.LZMA_VLI_UNKNOWN
  195. else:
  196. filter = parse_filter_spec(filterspecs[i])
  197. children.append(filter)
  198. filters[i].id = filter.id
  199. filters[i].options = filter.options
  200. return filters
  201. def build_filter_spec(filter):
  202. spec = {'id': filter.id}
  203. def add_opts(options_type, *opts):
  204. options = ffi.cast('%s*' % (options_type,), filter.options)
  205. for v in opts:
  206. spec[v] = getattr(options, v)
  207. if filter.id == m.LZMA_FILTER_LZMA1:
  208. add_opts('lzma_options_lzma', 'lc', 'lp', 'pb', 'dict_size')
  209. elif filter.id == m.LZMA_FILTER_LZMA2:
  210. add_opts('lzma_options_lzma', 'dict_size')
  211. elif filter.id == m.LZMA_FILTER_DELTA:
  212. add_opts('lzma_options_delta', 'dist')
  213. elif filter.id in BCJ_FILTERS:
  214. add_opts('lzma_options_bcj', 'start_offset')
  215. else:
  216. raise ValueError("Invalid filter ID: %s" % filter.id)
  217. return spec
  218. def _decode_filter_properties(filter_id, encoded_props):
  219. """_decode_filter_properties(filter_id, encoded_props) -> dict
  220. Return a dict describing a filter with ID *filter_id*, and options
  221. (properties) decoded from the bytes object *encoded_props*."""
  222. filter = ffi.new('lzma_filter*')
  223. filter.id = filter_id
  224. catch_lzma_error(m.lzma_properties_decode,
  225. filter, ffi.NULL, encoded_props, len(encoded_props))
  226. try:
  227. return build_filter_spec(filter)
  228. finally:
  229. # TODO do we need this, the only use of m.free?
  230. m.free(filter.options)
  231. def _decode_stream_header_or_footer(decode_f, in_bytes):
  232. footer_o = ffi.new('char[]', to_bytes(in_bytes))
  233. stream_flags = ffi.new('lzma_stream_flags*')
  234. catch_lzma_error(decode_f, stream_flags, footer_o)
  235. return StreamFlags(stream_flags)
  236. decode_stream_footer = functools.partial(_decode_stream_header_or_footer,
  237. m.lzma_stream_footer_decode)
  238. decode_stream_header = functools.partial(_decode_stream_header_or_footer,
  239. m.lzma_stream_header_decode)
  240. def decode_block_header_size(in_byte):
  241. # lzma_block_header_size_decode(b) (((uint32_t)(b) + 1) * 4)
  242. return (ord(in_byte) + 1) * 4
  243. def decode_index(s, stream_padding=0):
  244. indexp = ffi.new('lzma_index**')
  245. memlimit = ffi.new('uint64_t*')
  246. memlimit[0] = m.UINT64_MAX
  247. allocator = ffi.NULL
  248. in_buf = ffi.new('char[]', to_bytes(s))
  249. in_pos = ffi.new('size_t*')
  250. in_pos[0] = 0
  251. catch_lzma_error(m.lzma_index_buffer_decode, indexp,
  252. memlimit, allocator, in_buf, in_pos, len(s))
  253. return Index(indexp[0], allocator, stream_padding)
  254. class Index(object):
  255. def __init__(self, i, allocator, stream_padding=0):
  256. self.i = i
  257. self.allocator = allocator
  258. m.lzma_index_stream_padding(i, stream_padding)
  259. @property
  260. def uncompressed_size(self):
  261. return m.lzma_index_uncompressed_size(self.i)
  262. @property
  263. def block_count(self):
  264. return m.lzma_index_block_count(self.i)
  265. @property
  266. def index_size(self):
  267. return m.lzma_index_size(self.i)
  268. @property
  269. def blocks_size(self):
  270. return m.lzma_index_total_size(self.i)
  271. def __iter__(self):
  272. return self.iterator()
  273. def iterator(self, type=m.LZMA_INDEX_ITER_BLOCK):
  274. iterator = ffi.new('lzma_index_iter*')
  275. m.lzma_index_iter_init(iterator, self.i)
  276. while not m.lzma_index_iter_next(iterator, type):
  277. yield (IndexStreamData(iterator.stream), IndexBlockData(iterator.block))
  278. def find(self, offset):
  279. iterator = ffi.new('lzma_index_iter*')
  280. m.lzma_index_iter_init(iterator, self.i)
  281. if m.lzma_index_iter_locate(iterator, offset):
  282. # offset too high
  283. return None
  284. return (IndexStreamData(iterator.stream), IndexBlockData(iterator.block))
  285. def __del__(self):
  286. m.lzma_index_end(self.i, self.allocator)
  287. def copy(self):
  288. new_i = m.lzma_index_dup(self.i, self.allocator)
  289. return Index(new_i, self.allocator)
  290. deepcopy = copy
  291. def append(self, other_index):
  292. # m.lzma_index_cat frees its second parameter so we
  293. # must copy it first
  294. other_index_i = m.lzma_index_dup(other_index.i, self.allocator)
  295. catch_lzma_error(m.lzma_index_cat, self.i,
  296. other_index_i, self.allocator)
  297. class _StructToPy(object):
  298. __slots__ = ()
  299. def __init__(self, struct_obj):
  300. # TODO make PyPy-fast
  301. for attr in self.__slots__:
  302. setattr(self, attr, getattr(struct_obj, attr))
  303. def __repr__(self):
  304. descriptions = ('%s=%r' % (attr, getattr(self, attr)) for attr in self.__slots__)
  305. return "<%s %s>" % (type(self).__name__, ' '.join(descriptions))
  306. class IndexStreamData(_StructToPy):
  307. __slots__ = ('number', 'block_count', 'compressed_offset', 'uncompressed_offset',
  308. 'compressed_size', 'uncompressed_size')
  309. class IndexBlockData(_StructToPy):
  310. __slots__ = ('number_in_file', 'compressed_file_offset', 'uncompressed_file_offset',
  311. 'compressed_stream_offset', 'uncompressed_stream_offset',
  312. 'uncompressed_size', 'unpadded_size', 'total_size')
  313. class StreamFlags(object):
  314. def __init__(self, i):
  315. self.i = i
  316. version = property(lambda self: self.i.version)
  317. check = property(lambda self: self.i.check)
  318. backward_size = property(lambda self: self.i.backward_size)
  319. @property
  320. def supported(self):
  321. return self.version > SUPPORTED_STREAM_FLAGS_VERSION
  322. def check_supported(self):
  323. if not self.supported:
  324. raise LZMAError("Stream is too new for liblzma version")
  325. def matches(self, other):
  326. return m.lzma_stream_flags_compare(self.i, other.i) == m.LZMA_OK
  327. def copy(self):
  328. other_i = ffi.new('lzma_stream_flags*', self.i)
  329. return StreamFlags(other_i)
  330. class Allocator(object):
  331. def __init__(self):
  332. self.owns = {}
  333. self.lzma_allocator = ffi.new('lzma_allocator*')
  334. alloc = self.owns['a'] = ffi.callback("void*(void*, size_t, size_t)", self.__alloc)
  335. free = self.owns['b'] = ffi.callback("void(void*, void*)", self.__free)
  336. self.lzma_allocator.alloc = alloc
  337. self.lzma_allocator.free = free
  338. self.lzma_allocator.opaque = ffi.NULL
  339. def __alloc(self, _opaque, _nmemb, size):
  340. new_mem = ffi.new('char[]', size)
  341. self.owns[self._addr(new_mem)] = new_mem
  342. return new_mem
  343. def _addr(self, ptr):
  344. return long(ffi.cast('uintptr_t', ptr))
  345. def __free(self, _opaque, ptr):
  346. if self._addr(ptr) == 0: return
  347. del self.owns[self._addr(ptr)]
  348. class LZMADecompressor(object):
  349. """
  350. LZMADecompressor(format=FORMAT_AUTO, memlimit=None, filters=None)
  351. Create a decompressor object for decompressing data incrementally.
  352. format specifies the container format of the input stream. If this is
  353. FORMAT_AUTO (the default), the decompressor will automatically detect
  354. whether the input is FORMAT_XZ or FORMAT_ALONE. Streams created with
  355. FORMAT_RAW cannot be autodetected.
  356. memlimit can be specified to limit the amount of memory used by the
  357. decompressor. This will cause decompression to fail if the input
  358. cannot be decompressed within the given limit.
  359. filters specifies a custom filter chain. This argument is required for
  360. FORMAT_RAW, and not accepted with any other format. When provided,
  361. this should be a sequence of dicts, each indicating the ID and options
  362. for a single filter.
  363. For one-shot decompression, use the decompress() function instead.
  364. """
  365. def __init__(self, format=FORMAT_AUTO, memlimit=None, filters=None,
  366. header=None, check=None, unpadded_size=None):
  367. decoder_flags = m.LZMA_TELL_ANY_CHECK | m.LZMA_TELL_NO_CHECK
  368. if memlimit is not None:
  369. if format == FORMAT_RAW:
  370. raise ValueError("Cannot specify memory limit with FORMAT_RAW")
  371. else:
  372. memlimit = m.UINT64_MAX
  373. if format == FORMAT_RAW and filters is None:
  374. raise ValueError("Must specify filters for FORMAT_RAW")
  375. elif format != FORMAT_RAW and filters is not None:
  376. raise ValueError("Cannot specify filters except with FORMAT_RAW")
  377. if format == FORMAT_BLOCK and (header is None or unpadded_size is None or check is None):
  378. raise ValueError("Must specify header, unpadded_size and check "
  379. "with FORMAT_BLOCK")
  380. elif format != FORMAT_BLOCK and (header is not None or unpadded_size is not None or check is not None):
  381. raise ValueError("Cannot specify header, unpadded_size or check "
  382. "except with FORMAT_BLOCK")
  383. format = _parse_format(format)
  384. self.lock = threading.Lock()
  385. self.check = CHECK_UNKNOWN
  386. self.unused_data = b''
  387. self.eof = False
  388. self.lzs = _new_lzma_stream()
  389. self._bufsiz = max(8192, io.DEFAULT_BUFFER_SIZE)
  390. self.needs_input = True
  391. self._input_buffer = ffi.NULL
  392. self._input_buffer_size = 0
  393. if format == FORMAT_AUTO:
  394. catch_lzma_error(m.lzma_auto_decoder, self.lzs, memlimit, decoder_flags)
  395. elif format == FORMAT_XZ:
  396. catch_lzma_error(m.lzma_stream_decoder, self.lzs, memlimit, decoder_flags)
  397. elif format == FORMAT_ALONE:
  398. self.check = CHECK_NONE
  399. catch_lzma_error(m.lzma_alone_decoder, self.lzs, memlimit)
  400. elif format == FORMAT_RAW:
  401. self.check = CHECK_NONE
  402. filters = parse_filter_chain_spec(filters)
  403. catch_lzma_error(m.lzma_raw_decoder, self.lzs,
  404. filters)
  405. elif format == FORMAT_BLOCK:
  406. self.__block = block = ffi.new('lzma_block*')
  407. block.version = 0
  408. block.check = check
  409. block.header_size = len(header)
  410. block.filters = self.__filters = ffi.new('lzma_filter[]', m.LZMA_FILTERS_MAX+1)
  411. header_b = ffi.new('char[]', to_bytes(header))
  412. catch_lzma_error(m.lzma_block_header_decode, block, self.lzs.allocator, header_b)
  413. if unpadded_size is not None:
  414. catch_lzma_error(m.lzma_block_compressed_size, block, unpadded_size)
  415. self.expected_size = block.compressed_size
  416. catch_lzma_error(m.lzma_block_decoder, self.lzs, block)
  417. else:
  418. raise ValueError("invalid container format: %s" % format)
  419. def pre_decompress_left_data(self, buf, buf_size):
  420. # in this case there is data left that needs to be processed before the first
  421. # argument can be processed
  422. lzs = self.lzs
  423. addr_input_buffer = int(ffi.cast('uintptr_t', self._input_buffer))
  424. addr_next_in = int(ffi.cast('uintptr_t', lzs.next_in))
  425. avail_now = (addr_input_buffer + self._input_buffer_size) - \
  426. (addr_next_in + lzs.avail_in)
  427. avail_total = self._input_buffer_size - lzs.avail_in
  428. if avail_total < buf_size:
  429. # resize the buffer, it is too small!
  430. offset = addr_next_in - addr_input_buffer
  431. new_size = self._input_buffer_size + buf_size - avail_now
  432. # there is no realloc?
  433. tmp = ffi.cast("uint8_t*",m.malloc(new_size))
  434. if tmp == ffi.NULL:
  435. raise MemoryError
  436. ffi.memmove(tmp, lzs.next_in, lzs.avail_in)
  437. lzs.next_in = tmp
  438. m.free(self._input_buffer)
  439. self._input_buffer = tmp
  440. self._input_buffer_size = new_size
  441. elif avail_now < buf_size:
  442. # the buffer is not too small, but we cannot append it!
  443. # move all data to the front
  444. ffi.memmove(self._input_buffer, lzs.next_in, lzs.avail_in)
  445. lzs.next_in = self._input_buffer
  446. ffi.memmove(lzs.next_in+lzs.avail_in, buf, buf_size)
  447. lzs.avail_in += buf_size
  448. return lzs.next_in, lzs.avail_in
  449. def post_decompress_avail_data(self):
  450. lzs = self.lzs
  451. # free buffer it is to small
  452. if self._input_buffer is not ffi.NULL and \
  453. self._input_buffer_size < lzs.avail_in:
  454. m.free(self._input_buffer)
  455. self._input_buffer = ffi.NONE
  456. # allocate if necessary
  457. if self._input_buffer is ffi.NULL:
  458. self._input_buffer = ffi.cast("uint8_t*",m.malloc(lzs.avail_in))
  459. if self._input_buffer == ffi.NULL:
  460. raise MemoryError
  461. self._input_buffer_size = lzs.avail_in
  462. ffi.memmove(self._input_buffer, lzs.next_in, lzs.avail_in)
  463. lzs.next_in = self._input_buffer
  464. def clear_input_buffer(self):
  465. # clean the buffer
  466. if self._input_buffer is not ffi.NULL:
  467. m.free(self._input_buffer)
  468. self._input_buffer = ffi.NULL
  469. self._input_buffer_size = 0
  470. def decompress(self, data, max_length=-1):
  471. """
  472. decompress(data, max_length=-1) -> bytes
  473. Provide data to the decompressor object. Returns a chunk of
  474. decompressed data if possible, or b"" otherwise.
  475. Attempting to decompress data after the end of the stream is
  476. reached raises an EOFError. Any data found after the end of the
  477. stream is ignored, and saved in the unused_data attribute.
  478. """
  479. if not isinstance(max_length, int):
  480. raise TypeError("max_length parameter object cannot be interpreted as an integer")
  481. with self.lock:
  482. if self.eof:
  483. raise EOFError("Already at end of stream")
  484. lzs = self.lzs
  485. data = to_bytes(data)
  486. buf = ffi.new('uint8_t[]', data)
  487. buf_size = len(data)
  488. if lzs.next_in:
  489. buf, buf_size = self.pre_decompress_left_data(buf, buf_size)
  490. used__input_buffer = True
  491. else:
  492. lzs.avail_in = buf_size
  493. lzs.next_in = ffi.cast("uint8_t*",buf)
  494. used__input_buffer = False
  495. # actual decompression
  496. result = self._decompress(buf, buf_size, max_length)
  497. if self.eof:
  498. self.needs_input = False
  499. if lzs.avail_in > 0:
  500. self.unused_data = ffi.buffer(lzs.next_in, lzs.avail_in)[:]
  501. self.clear_input_buffer()
  502. elif lzs.avail_in == 0:
  503. # completed successfully!
  504. self.needs_input = True
  505. lzs.next_in = ffi.NULL
  506. self.clear_input_buffer()
  507. else:
  508. self.needs_input = False
  509. if not used__input_buffer:
  510. self.post_decompress_avail_data()
  511. return result
  512. def _decompress(self, buf, buf_len, max_length):
  513. lzs = self.lzs
  514. lzs.next_in = buf
  515. lzs.avail_in = buf_len
  516. if buf_len == 0:
  517. return b""
  518. bufsiz = self._bufsiz
  519. if not (max_length < 0 or max_length > io.DEFAULT_BUFFER_SIZE):
  520. bufsiz = max_length
  521. lzs.next_out = orig_out = m.malloc(bufsiz)
  522. if orig_out == ffi.NULL:
  523. raise MemoryError
  524. lzs.avail_out = bufsiz
  525. data_size = 0
  526. try:
  527. while True:
  528. ret = catch_lzma_error(m.lzma_code, lzs, m.LZMA_RUN)
  529. data_size = int(ffi.cast('uintptr_t', lzs.next_out)) - int(ffi.cast('uintptr_t', orig_out))
  530. # data_size is the amount lzma_code has already outputted
  531. if ret in (m.LZMA_NO_CHECK, m.LZMA_GET_CHECK):
  532. self.check = m.lzma_get_check(lzs)
  533. if ret == m.LZMA_STREAM_END:
  534. self.eof = True
  535. break
  536. elif lzs.avail_in == 0:
  537. # it ate everything
  538. break
  539. elif lzs.avail_out == 0:
  540. if data_size == max_length:
  541. break
  542. # ran out of space in the output buffer, let's grow it
  543. bufsiz += (bufsiz >> 3) + 6
  544. next_out = m.realloc(orig_out, bufsiz)
  545. if next_out == ffi.NULL:
  546. # realloc unsuccessful
  547. m.free(orig_out)
  548. orig_out = ffi.NULL
  549. raise MemoryError
  550. orig_out = next_out
  551. lzs.next_out = orig_out + data_size
  552. lzs.avail_out = bufsiz - data_size
  553. result = ffi.buffer(orig_out, data_size)[:]
  554. finally:
  555. m.free(orig_out)
  556. return result
  557. def __getstate__(self):
  558. raise TypeError("cannot serialize '%s' object" %
  559. self.__class__.__name__)
  560. # Issue #2579: Setting up the stream for encoding takes around 17MB of
  561. # RAM on my Linux 64 system. So we call add_memory_pressure(17MB) when
  562. # we create the stream. In flush(), we actively free the stream even
  563. # though we could just leave it to the GC (but 17MB is too much for
  564. # doing that sanely); at this point we call add_memory_pressure(-17MB)
  565. # to cancel the original increase.
  566. COMPRESSION_STREAM_SIZE = 1024*1024*17
  567. class LZMACompressor(object):
  568. """
  569. LZMACompressor(format=FORMAT_XZ, check=-1, preset=None, filters=None)
  570. Create a compressor object for compressing data incrementally.
  571. format specifies the container format to use for the output. This can
  572. be FORMAT_XZ (default), FORMAT_ALONE, or FORMAT_RAW.
  573. check specifies the integrity check to use. For FORMAT_XZ, the default
  574. is CHECK_CRC64. FORMAT_ALONE and FORMAT_RAW do not suport integrity
  575. checks; for these formats, check must be omitted, or be CHECK_NONE.
  576. The settings used by the compressor can be specified either as a
  577. preset compression level (with the 'preset' argument), or in detail
  578. as a custom filter chain (with the 'filters' argument). For FORMAT_XZ
  579. and FORMAT_ALONE, the default is to use the PRESET_DEFAULT preset
  580. level. For FORMAT_RAW, the caller must always specify a filter chain;
  581. the raw compressor does not support preset compression levels.
  582. preset (if provided) should be an integer in the range 0-9, optionally
  583. OR-ed with the constant PRESET_EXTREME.
  584. filters (if provided) should be a sequence of dicts. Each dict should
  585. have an entry for "id" indicating the ID of the filter, plus
  586. additional entries for options to the filter.
  587. For one-shot compression, use the compress() function instead.
  588. """
  589. def __init__(self, format=FORMAT_XZ, check=-1, preset=None, filters=None):
  590. if format != FORMAT_XZ and check not in (-1, m.LZMA_CHECK_NONE):
  591. raise ValueError("Integrity checks are only supported by FORMAT_XZ")
  592. if preset is not None and filters is not None:
  593. raise ValueError("Cannot specify both preset and filter chain")
  594. if preset is None:
  595. preset = m.LZMA_PRESET_DEFAULT
  596. format = _parse_format(format)
  597. self.lock = threading.Lock()
  598. self.flushed = 0
  599. self.lzs = _new_lzma_stream()
  600. __pypy__.add_memory_pressure(COMPRESSION_STREAM_SIZE)
  601. if format == FORMAT_XZ:
  602. if filters is None:
  603. if check == -1:
  604. check = m.LZMA_CHECK_CRC64
  605. catch_lzma_error(m.lzma_easy_encoder, self.lzs,
  606. preset, check)
  607. else:
  608. filters = parse_filter_chain_spec(filters)
  609. catch_lzma_error(m.lzma_stream_encoder, self.lzs,
  610. filters, check)
  611. elif format == FORMAT_ALONE:
  612. if filters is None:
  613. options = ffi.new('lzma_options_lzma*')
  614. if m.lzma_lzma_preset(options, preset):
  615. raise LZMAError("Invalid compression preset: %s" % preset)
  616. catch_lzma_error(m.lzma_alone_encoder, self.lzs,
  617. options)
  618. else:
  619. raise NotImplementedError
  620. elif format == FORMAT_RAW:
  621. if filters is None:
  622. raise ValueError("Must specify filters for FORMAT_RAW")
  623. filters = parse_filter_chain_spec(filters)
  624. catch_lzma_error(m.lzma_raw_encoder, self.lzs,
  625. filters)
  626. else:
  627. raise ValueError("invalid container format: %s" % format)
  628. def compress(self, data):
  629. """
  630. compress(data) -> bytes
  631. Provide data to the compressor object. Returns a chunk of
  632. compressed data if possible, or b"" otherwise.
  633. When you have finished providing data to the compressor, call the
  634. flush() method to finish the conversion process.
  635. """
  636. with self.lock:
  637. if self.flushed:
  638. raise ValueError("Compressor has been flushed")
  639. return self._compress(data)
  640. def _compress(self, data, action=m.LZMA_RUN):
  641. # TODO use realloc like in LZMADecompressor
  642. BUFSIZ = 8192
  643. lzs = self.lzs
  644. lzs.next_in = input_ = ffi.new('uint8_t[]', to_bytes(data))
  645. lzs.avail_in = input_len = len(data)
  646. outs = [ffi.new('uint8_t[]', BUFSIZ)]
  647. lzs.next_out, = outs
  648. lzs.avail_out = BUFSIZ
  649. siz = BUFSIZ
  650. while True:
  651. next_out_pos = int(ffi.cast('intptr_t', lzs.next_out))
  652. ret = catch_lzma_error(m.lzma_code, lzs, action,
  653. ignore_buf_error=(input_len==0 and lzs.avail_out > 0))
  654. data_size = int(ffi.cast('intptr_t', lzs.next_out)) - next_out_pos
  655. if (action == m.LZMA_RUN and lzs.avail_in == 0) or \
  656. (action == m.LZMA_FINISH and ret == m.LZMA_STREAM_END):
  657. break
  658. elif lzs.avail_out == 0:
  659. # ran out of space in the output buffer
  660. #siz = (BUFSIZ << 1) + 6
  661. siz = 512
  662. outs.append(ffi.new('uint8_t[]', siz))
  663. lzs.next_out = outs[-1]
  664. lzs.avail_out = siz
  665. last_out = outs.pop()
  666. last_out_len = siz - lzs.avail_out
  667. last_out_piece = ffi.buffer(last_out[0:last_out_len], last_out_len)[:]
  668. return b''.join(ffi.buffer(nn)[:] for nn in outs) + last_out_piece
  669. def flush(self):
  670. with self.lock:
  671. if self.flushed:
  672. raise ValueError("Repeated call to flush()")
  673. self.flushed = 1
  674. result = self._compress(b'', action=m.LZMA_FINISH)
  675. __pypy__.add_memory_pressure(-COMPRESSION_STREAM_SIZE)
  676. _release_lzma_stream(self.lzs)
  677. return result
  678. def __getstate__(self):
  679. raise TypeError("cannot serialize '%s' object" %
  680. self.__class__.__name__)