Debian Codegraph @

rpython/rlib/rzlib.py

raw symbols SCIP
1 from __future__ import with_statement
2 import sys
3
4 from rpython.rlib import rgc
5 from rpython.rlib.rstring import StringBuilder
6 from rpython.rtyper.annlowlevel import llstr
7 from rpython.rtyper.lltypesystem import rffi, lltype
8 from rpython.rtyper.lltypesystem.rstr import copy_string_to_raw
9 from rpython.rtyper.tool import rffi_platform
10 from rpython.translator.platform import platform as compiler, CompilationError
11 from rpython.translator.tool.cbuild import ExternalCompilationInfo
12
13
14 if compiler.name == "msvc":
15 libname = 'zlib' # use the static lib, not zlib1 which is dll import lib
16 testonly_libraries = ['zlib1']
17 else:
18 libname = 'z'
19 testonly_libraries = []
20 eci = ExternalCompilationInfo(
21 libraries=[libname],
22 includes=['zlib.h'],
23 testonly_libraries = testonly_libraries
24 )
25 eci = rffi_platform.configure_external_library(
26 libname, eci,
27 [dict(prefix='zlib-'),
28 ])
29
30
31 constantnames = '''
32 Z_OK Z_STREAM_ERROR Z_BUF_ERROR Z_MEM_ERROR Z_STREAM_END Z_DATA_ERROR
33 Z_DEFLATED Z_DEFAULT_STRATEGY Z_DEFAULT_COMPRESSION
34 Z_NO_FLUSH Z_FINISH Z_SYNC_FLUSH Z_FULL_FLUSH
35 MAX_WBITS MAX_MEM_LEVEL
36 Z_BEST_SPEED Z_BEST_COMPRESSION Z_DEFAULT_COMPRESSION
37 Z_FILTERED Z_HUFFMAN_ONLY Z_DEFAULT_STRATEGY Z_NEED_DICT
38 Z_NULL
39 '''.split()
40
41 class SimpleCConfig:
42 """
43 Definitions for basic types defined by zlib.
44 """
45 _compilation_info_ = eci
46
47 # XXX If Z_PREFIX was defined for the libz build, then these types are
48 # named z_uInt, z_uLong, and z_Bytef instead.
49 uInt = rffi_platform.SimpleType('uInt', rffi.UINT)
50 uLong = rffi_platform.SimpleType('uLong', rffi.ULONG)
51 Bytef = rffi_platform.SimpleType('Bytef', rffi.UCHAR)
52 voidpf = rffi_platform.SimpleType('voidpf', rffi.VOIDP)
53
54 ZLIB_VERSION = rffi_platform.DefinedConstantString('ZLIB_VERSION')
55 ZLIB_VERNUM = rffi_platform.DefinedConstantInteger('ZLIB_VERNUM')
56
57 for _name in constantnames:
58 setattr(SimpleCConfig, _name, rffi_platform.ConstantInteger(_name))
59
60 config = rffi_platform.configure(SimpleCConfig)
61 voidpf = config['voidpf']
62 uInt = config['uInt']
63 uLong = config['uLong']
64 Bytef = config['Bytef']
65 Bytefp = lltype.Ptr(lltype.Array(Bytef, hints={'nolength': True}))
66
67 ZLIB_VERSION = config['ZLIB_VERSION']
68 ZLIB_VERNUM = config['ZLIB_VERNUM']
69
70 for _name in constantnames:
71 globals()[_name] = config[_name]
72
73 # The following parameter is copied from zutil.h, version 0.95,
74 # according to CPython's zlibmodule.c
75 DEFLATED = Z_DEFLATED
76 if MAX_MEM_LEVEL >= 8:
77 DEF_MEM_LEVEL = 8
78 else:
79 DEF_MEM_LEVEL = MAX_MEM_LEVEL
80
81 OUTPUT_BUFFER_SIZE = 32*1024
82 INPUT_BUFFER_MAX = 2047*1024*1024
83 # Note: we assume that zlib never outputs less than OUTPUT_BUFFER_SIZE
84 # from an input of INPUT_BUFFER_MAX bytes. This should be true by a
85 # large margin (I think zlib never compresses by more than ~1000x).
86
87
88 class ComplexCConfig:
89 """
90 Definitions of structure types defined by zlib and based on SimpleCConfig
91 definitions.
92 """
93 _compilation_info_ = eci
94
95 z_stream = rffi_platform.Struct(
96 'z_stream',
97 [('next_in', Bytefp),
98 ('avail_in', uInt),
99 ('total_in', uLong),
100
101 ('next_out', Bytefp),
102 ('avail_out', uInt),
103 ('total_out', uLong),
104
105 ('msg', rffi.CCHARP),
106
107 ('zalloc', lltype.Ptr(
108 lltype.FuncType([voidpf, uInt, uInt], voidpf))),
109 ('zfree', lltype.Ptr(
110 lltype.FuncType([voidpf, voidpf], lltype.Void))),
111
112 ('opaque', voidpf),
113
114 ('data_type', rffi.INT),
115 ('adler', uLong),
116 ('reserved', uLong)
117 ])
118
119 config = rffi_platform.configure(ComplexCConfig)
120 z_stream = config['z_stream']
121 z_stream_p = lltype.Ptr(z_stream)
122
123 def zlib_external(*a, **kw):
124 kw['compilation_info'] = eci
125 return rffi.llexternal(*a, **kw)
126
127 _crc32 = zlib_external('crc32', [uLong, Bytefp, uInt], uLong)
128 _adler32 = zlib_external('adler32', [uLong, Bytefp, uInt], uLong)
129
130
131 # XXX I want to call deflateInit2, not deflateInit2_
132 _deflateInit2_ = zlib_external(
133 'deflateInit2_',
134 [z_stream_p, # stream
135 rffi.INT, # level
136 rffi.INT, # method
137 rffi.INT, # window bits
138 rffi.INT, # mem level
139 rffi.INT, # strategy
140 rffi.CCHARP, # version
141 rffi.INT], # stream size
142 rffi.INT)
143 _deflate = zlib_external('deflate', [z_stream_p, rffi.INT], rffi.INT)
144
145 _deflateCopy = zlib_external('deflateCopy', [z_stream_p, z_stream_p], rffi.INT)
146 _deflateEnd = zlib_external('deflateEnd', [z_stream_p], rffi.INT,
147 releasegil=False)
148
149 def _deflateInit2(stream, level, method, wbits, memlevel, strategy):
150 size = rffi.sizeof(z_stream)
151 result = _deflateInit2_(
152 stream, level, method, wbits, memlevel, strategy, ZLIB_VERSION, size)
153 return result
154
155 # XXX I also want to call inflateInit2 instead of inflateInit2_
156 _inflateInit2_ = zlib_external(
157 'inflateInit2_',
158 [z_stream_p, # stream
159 rffi.INT, # window bits
160 rffi.CCHARP, # version
161 rffi.INT], # stream size
162 rffi.INT)
163 _inflate = zlib_external('inflate', [z_stream_p, rffi.INT], rffi.INT)
164
165 _inflateCopy = zlib_external('inflateCopy', [z_stream_p, z_stream_p], rffi.INT)
166 _inflateEnd = zlib_external('inflateEnd', [z_stream_p], rffi.INT,
167 releasegil=False)
168
169 def _inflateInit2(stream, wbits):
170 size = rffi.sizeof(z_stream)
171 result = _inflateInit2_(stream, wbits, ZLIB_VERSION, size)
172 return result
173
174 _deflateSetDictionary = zlib_external('deflateSetDictionary', [z_stream_p, Bytefp, uInt], rffi.INT)
175 _inflateSetDictionary = zlib_external('inflateSetDictionary', [z_stream_p, Bytefp, uInt], rffi.INT)
176 _zlibVersion = zlib_external('zlibVersion', [], rffi.CCHARP)
177
178 # ____________________________________________________________
179
180 def _crc_or_adler(string, start, function):
181 with rffi.scoped_nonmovingbuffer(string) as bytes:
182 remaining = len(string)
183 checksum = start
184 ptr = rffi.cast(Bytefp, bytes)
185 while remaining > 0:
186 count = min(remaining, 32*1024*1024)
187 checksum = function(checksum, ptr, count)
188 ptr = rffi.ptradd(ptr, count)
189 remaining -= count
190 return checksum
191
192 CRC32_DEFAULT_START = 0
193
194 def crc32(string, start=CRC32_DEFAULT_START):
195 """
196 Compute the CRC32 checksum of the string, possibly with the given
197 start value, and return it as a unsigned 32 bit integer.
198 """
199 return _crc_or_adler(string, start, _crc32)
200
201 ADLER32_DEFAULT_START = 1
202
203 def adler32(string, start=ADLER32_DEFAULT_START):
204 """
205 Compute the Adler-32 checksum of the string, possibly with the given
206 start value, and return it as a unsigned 32 bit integer.
207 """
208 return _crc_or_adler(string, start, _adler32)
209
210
211 def deflateSetDictionary(stream, string):
212 with rffi.scoped_nonmovingbuffer(string) as buf:
213 err = _deflateSetDictionary(stream, rffi.cast(Bytefp, buf), len(string))
214 if err == Z_STREAM_ERROR:
215 raise RZlibError("Parameter is invalid or the stream state is inconsistent")
216
217 def inflateSetDictionary(stream, string):
218 with rffi.scoped_nonmovingbuffer(string) as buf:
219 err = _inflateSetDictionary(stream, rffi.cast(Bytefp, buf), len(string))
220 if err == Z_STREAM_ERROR:
221 raise RZlibError("Parameter is invalid or the stream state is inconsistent")
222 elif err == Z_DATA_ERROR:
223 raise RZlibError("The given dictionary doesn't match the expected one")
224
225 def zlibVersion():
226 """Return the runtime version of zlib library"""
227 return rffi.charp2str(_zlibVersion())
228
229 # ____________________________________________________________
230
231 class RZlibError(Exception):
232 """Exception raised by failing operations in rpython.rlib.rzlib."""
233 def __init__(self, msg):
234 self.msg = msg
235
236 def __str__(self):
237 return self.msg
238
239 def fromstream(stream, err, while_doing):
240 """Return a RZlibError with a message formatted from a zlib error
241 code and stream.
242 """
243 if stream.c_msg:
244 reason = rffi.charp2str(stream.c_msg)
245 elif err == Z_MEM_ERROR:
246 reason = "out of memory"
247 elif err == Z_BUF_ERROR:
248 reason = "incomplete or truncated stream"
249 elif err == Z_STREAM_ERROR:
250 reason = "inconsistent stream state"
251 elif err == Z_DATA_ERROR:
252 reason = "invalid input data"
253 else:
254 reason = ""
255
256 if reason:
257 delim = ": "
258 else:
259 delim = ""
260 msg = "Error %d %s%s%s" % (err, while_doing, delim, reason)
261 return RZlibError(msg)
262 fromstream = staticmethod(fromstream)
263
264 null_stream = lltype.nullptr(z_stream)
265
266
267 def deflateInit(level=Z_DEFAULT_COMPRESSION, method=Z_DEFLATED,
268 wbits=MAX_WBITS, memLevel=DEF_MEM_LEVEL,
269 strategy=Z_DEFAULT_STRATEGY, zdict=None):
270 """
271 Allocate and return an opaque 'stream' object that can be used to
272 compress data.
273 """
274 stream = lltype.malloc(z_stream, flavor='raw', zero=True)
275 rgc.add_memory_pressure(rffi.sizeof(z_stream))
276 err = _deflateInit2(stream, level, method, wbits, memLevel, strategy)
277 if err == Z_OK:
278 if zdict is not None:
279 try:
280 deflateSetDictionary(stream, zdict)
281 except:
282 lltype.free(stream, flavor='raw')
283 raise
284 return stream
285 else:
286 try:
287 if err == Z_STREAM_ERROR:
288 raise ValueError("Invalid initialization option")
289 else:
290 raise RZlibError.fromstream(stream, err,
291 "while creating compression object")
292 finally:
293 lltype.free(stream, flavor='raw')
294
295
296 def deflateCopy(source):
297 """
298 Allocate and return an independent copy of the provided stream object.
299 """
300 dest = deflateInit()
301 err = _deflateCopy(dest, source)
302 if err != Z_OK:
303 deflateEnd(dest)
304 raise RZlibError.fromstream(source, err,
305 "while copying compression object")
306 return dest
307
308
309 def deflateEnd(stream):
310 """
311 Free the resources associated with the deflate stream.
312 """
313 _deflateEnd(stream)
314 lltype.free(stream, flavor='raw')
315
316
317 def inflateInit(wbits=MAX_WBITS, zdict=None):
318 """
319 Allocate and return an opaque 'stream' object that can be used to
320 decompress data.
321 """
322 stream = lltype.malloc(z_stream, flavor='raw', zero=True)
323 rgc.add_memory_pressure(rffi.sizeof(z_stream))
324 err = _inflateInit2(stream, wbits)
325 if err == Z_OK:
326 if zdict is not None and wbits < 0:
327 try:
328 if ZLIB_VERNUM is None or ZLIB_VERNUM < 0x1221:
329 raise RZlibError("zlib version %s does not allow raw "
330 "inflate with dictionary" %
331 ZLIB_VERSION if ZLIB_VERSION is not None
332 else "<unknown>")
333 inflateSetDictionary(stream, zdict)
334 except:
335 lltype.free(stream, flavor='raw')
336 raise
337 return stream
338 else:
339 try:
340 if err == Z_STREAM_ERROR:
341 raise ValueError("Invalid initialization option")
342 else:
343 raise RZlibError.fromstream(stream, err,
344 "while creating decompression object")
345 finally:
346 lltype.free(stream, flavor='raw')
347
348
349 def inflateCopy(source):
350 """
351 Allocate and return an independent copy of the provided stream object.
352 """
353 dest = inflateInit()
354 err = _inflateCopy(dest, source)
355 if err != Z_OK:
356 inflateEnd(dest)
357 raise RZlibError.fromstream(source, err,
358 "while copying decompression object")
359 return dest
360
361
362 def inflateEnd(stream):
363 """
364 Free the resources associated with the inflate stream.
365 Note that this may raise RZlibError.
366 """
367 _inflateEnd(stream)
368 lltype.free(stream, flavor='raw')
369
370
371 def compress(stream, data, flush=Z_NO_FLUSH):
372 """
373 Feed more data into a deflate stream. Returns a string containing
374 (a part of) the compressed data. If flush != Z_NO_FLUSH, this also
375 flushes the output data; see zlib.h or the documentation of the
376 zlib module for the possible values of 'flush'.
377 """
378 # Warning, reentrant calls to the zlib with a given stream can cause it
379 # to crash. The caller of rpython.rlib.rzlib should use locks if needed.
380 data, _, avail_in = _operate(stream, data, flush, sys.maxint, _deflate,
381 "while compressing")
382 assert not avail_in, "not all input consumed by deflate"
383 return data
384
385
386 def decompress(stream, data, flush=Z_SYNC_FLUSH, max_length=sys.maxint,
387 zdict=None):
388 """
389 Feed more data into an inflate stream. Returns a tuple (string,
390 finished, unused_data_length). The string contains (a part of) the
391 decompressed data. If flush != Z_NO_FLUSH, this also flushes the
392 output data; see zlib.h or the documentation of the zlib module for
393 the possible values of 'flush'.
394
395 The 'string' is never longer than 'max_length'. The
396 'unused_data_length' is the number of unprocessed input characters,
397 either because they are after the end of the compressed stream or
398 because processing it would cause the 'max_length' to be exceeded.
399 """
400 # Warning, reentrant calls to the zlib with a given stream can cause it
401 # to crash. The caller of rpython.rlib.rzlib should use locks if needed.
402
403 # _operate() does not support the Z_FINISH method of decompressing.
404 # We can use Z_SYNC_FLUSH instead and manually check that we got to
405 # the end of the data.
406 if flush == Z_FINISH:
407 flush = Z_SYNC_FLUSH
408 should_finish = True
409 else:
410 should_finish = False
411 while_doing = "while decompressing data"
412 data, err, avail_in = _operate(stream, data, flush, max_length, _inflate,
413 while_doing, zdict=zdict)
414 if should_finish:
415 # detect incomplete input
416 rffi.setintfield(stream, 'c_avail_in', 0)
417 err = _inflate(stream, Z_FINISH)
418 if err < 0:
419 raise RZlibError.fromstream(stream, err, while_doing)
420 finished = (err == Z_STREAM_END)
421 return data, finished, avail_in
422
423
424 def _operate(stream, data, flush, max_length, cfunc, while_doing, zdict=None):
425 """Common code for compress() and decompress().
426 """
427 # Prepare the input buffer for the stream
428 assert data is not None
429 with rffi.scoped_nonmovingbuffer(data) as inbuf:
430 stream.c_next_in = rffi.cast(Bytefp, inbuf)
431 end_inbuf = rffi.ptradd(stream.c_next_in, len(data))
432
433 # Prepare the output buffer
434 with lltype.scoped_alloc(rffi.CCHARP.TO, OUTPUT_BUFFER_SIZE) as outbuf:
435 # Strategy: we call deflate() to get as much output data as fits in
436 # the buffer, then accumulate all output into a StringBuffer
437 # 'result'.
438 result = StringBuilder()
439
440 while True:
441 avail_in = ptrdiff(end_inbuf, stream.c_next_in)
442 if avail_in > INPUT_BUFFER_MAX:
443 avail_in = INPUT_BUFFER_MAX
444 rffi.setintfield(stream, 'c_avail_in', avail_in)
445
446 stream.c_next_out = rffi.cast(Bytefp, outbuf)
447 bufsize = OUTPUT_BUFFER_SIZE
448 if max_length < bufsize:
449 if max_length <= 0:
450 err = Z_OK
451 break
452 bufsize = max_length
453 max_length -= bufsize
454 rffi.setintfield(stream, 'c_avail_out', bufsize)
455
456 err = cfunc(stream, flush)
457
458 if err == Z_NEED_DICT and zdict is not None:
459 inflateSetDictionary(stream, zdict)
460 # repeat the call to inflate
461 err = cfunc(stream, flush)
462 if err == Z_OK or err == Z_STREAM_END:
463 # accumulate data into 'result'
464 avail_out = rffi.cast(lltype.Signed, stream.c_avail_out)
465 result.append_charpsize(outbuf, bufsize - avail_out)
466 # if the output buffer is full, there might be more data
467 # so we need to try again. Otherwise, we're done.
468 if avail_out > 0:
469 break
470 # We're also done if we got a Z_STREAM_END (which should
471 # only occur when flush == Z_FINISH).
472 if err == Z_STREAM_END:
473 break
474 else:
475 continue
476 elif err == Z_BUF_ERROR:
477 avail_out = rffi.cast(lltype.Signed, stream.c_avail_out)
478 # When compressing, we will only get Z_BUF_ERROR if
479 # the output buffer was full but there wasn't more
480 # output when we tried again, so it is not an error
481 # condition.
482 if avail_out == bufsize:
483 break
484
485 # fallback case: report this error
486 raise RZlibError.fromstream(stream, err, while_doing)
487
488 # When decompressing, if the compressed stream of data was truncated,
489 # then the zlib simply returns Z_OK and waits for more. If it is
490 # complete it returns Z_STREAM_END.
491 avail_in = ptrdiff(end_inbuf, stream.c_next_in)
492 return (result.build(), err, avail_in)
493
494 def ptrdiff(p, q):
495 x = rffi.cast(lltype.Unsigned, p) - rffi.cast(lltype.Unsigned, q)
496 return rffi.cast(lltype.Signed, x)