Debian Codegraph @

pypy/module/marshal/interp_marshal.py

raw symbols SCIP
1 from pypy.interpreter.error import OperationError, oefmt
2 from pypy.interpreter.gateway import WrappedDefault, unwrap_spec
3 from rpython.rlib.rarithmetic import intmask
4 from rpython.rlib import rstackovf, jit
5 from pypy.objspace.std.marshal_impl import marshal, _unmarshallers_unroll, FLAG_REF
6
7 #
8 # Write Python objects to files and read them back. This is primarily
9 # intended for writing and reading compiled Python code, even though
10 # dicts, lists, sets and frozensets, not commonly seen in code
11 # objects, are supported. Version 3 of this protocol properly
12 # supports circular links and sharing. The previous version is called
13 # "2", like in Python 2.7, although it is not always compatible
14 # between CPython 2.7 and CPython 3.4. Version 4 adds small
15 # optimizations in compactness.
16 #
17 # XXX: before py3k, there was logic to do efficiently dump()/load() on
18 # a file object. The corresponding logic is gone from CPython 3.x, so
19 # I don't feel bad about killing it here too.
20 #
21
22 Py_MARSHAL_VERSION = 4
23
24
25 @unwrap_spec(version=int)
26 def dump(space, w_data, w_f, version=Py_MARSHAL_VERSION):
27 """Write the 'data' object into the open file 'f'."""
28 # same implementation as CPython 3.x.
29 w_string = dumps(space, w_data, version)
30 space.call_method(w_f, 'write', w_string)
31
32 @unwrap_spec(version=int)
33 def dumps(space, w_data, version=Py_MARSHAL_VERSION):
34 """Return the string that would have been written to a file
35 by dump(data, file)."""
36 m = StringMarshaller(space, version)
37 m.dump_w_obj(w_data)
38 return space.newbytes(m.get_value())
39
40 def load(space, w_f):
41 """Read one value from the file 'f' and return it."""
42 reader = FileReader(space, w_f)
43 try:
44 u = Unmarshaller(space, reader)
45 return u.load_w_obj()
46 finally:
47 reader.finished()
48
49 def loads(space, w_str):
50 """Convert a string back to a value. Extra characters in the string are
51 ignored."""
52 return _loads(space, w_str)
53
54 def _loads(space, w_str, hidden_applevel=False):
55 u = StringUnmarshaller(space, w_str, hidden_applevel=hidden_applevel)
56 obj = u.load_w_obj()
57 return obj
58
59
60 class AbstractReaderWriter(object):
61 def __init__(self, space):
62 self.space = space
63
64 def raise_eof(self):
65 space = self.space
66 raise oefmt(space.w_EOFError, "EOF read where object expected")
67
68 def finished(self):
69 pass
70
71 def read(self, n):
72 raise NotImplementedError("Purely abstract method")
73
74 def write(self, data):
75 raise NotImplementedError("Purely abstract method")
76
77
78 class FileReader(AbstractReaderWriter):
79 def __init__(self, space, w_f):
80 AbstractReaderWriter.__init__(self, space)
81 try:
82 self.func = space.getattr(w_f, space.newtext('read'))
83 # XXX how to check if it is callable?
84 except OperationError as e:
85 if not e.match(space, space.w_AttributeError):
86 raise
87 raise oefmt(space.w_TypeError,
88 "marshal.load() arg must be file-like object")
89
90 def read(self, n):
91 space = self.space
92 w_ret = space.call_function(self.func, space.newint(n))
93 ret = space.bytes_w(w_ret)
94 if len(ret) < n:
95 self.raise_eof()
96 if len(ret) > n:
97 raise oefmt(space.w_ValueError,
98 "read() returned too much data: "
99 "%d bytes requested, %d returned",
100 n, len(ret))
101 return ret
102
103
104 class _Base(object):
105 def raise_exc(self, msg):
106 space = self.space
107 raise OperationError(space.w_ValueError, space.newtext(msg))
108
109 class Marshaller(_Base):
110 """
111 atomic types including typecode:
112
113 atom(tc) puts single typecode
114 atom_int(tc, int) puts code and int
115 atom_int64(tc, int64) puts code and int64
116 atom_str(tc, str) puts code, len and string
117
118 building blocks for compound types:
119
120 start(typecode) sets the type character
121 put(s) puts a string with fixed length
122 put_short(int) puts a short integer
123 put_int(int) puts an integer
124 put_pascal(s) puts a short string
125 put_w_obj(w_obj) puts a wrapped object
126 put_tuple_w(TYPE, tuple_w) puts tuple_w, an unwrapped list of wrapped objects
127 """
128
129 def __init__(self, space, writer, version):
130 self.space = space
131 ## self.put = putfunc
132 self.writer = writer
133 self.version = version
134 self.all_refs = {}
135 # all_refs = {w_obj: index} for all w_obj that are of a
136 # "reasonably sharable" type. CPython checks the refcount of
137 # any object to know if it is sharable, independently of its
138 # type. We can't do that. We could do a two-pass marshaller.
139 # For now we simply add to this list all objects that marshal to
140 # more than a few fixed-sized bytes, minus ones like code
141 # objects that never appear more than once except in complete
142 # corner cases.
143
144 ## currently we cannot use a put that is a bound method
145 ## from outside. Same holds for get.
146 def put(self, s):
147 self.writer.write(s)
148
149 def put1(self, c):
150 self.writer.write(c)
151
152 def atom(self, typecode):
153 #assert type(typecode) is str and len(typecode) == 1
154 # type(char) not supported
155 self.put1(typecode)
156
157 def atom_int(self, typecode, x):
158 a = chr(x & 0xff)
159 x >>= 8
160 b = chr(x & 0xff)
161 x >>= 8
162 c = chr(x & 0xff)
163 x >>= 8
164 d = chr(x & 0xff)
165 self.put(typecode + a + b + c + d)
166
167 def atom_int64(self, typecode, x):
168 self.atom_int(typecode, x)
169 self.put_int(x>>32)
170
171 def atom_str(self, typecode, x):
172 self.atom_int(typecode, len(x))
173 self.put(x)
174
175 def start(self, typecode):
176 # type(char) not supported
177 self.put(typecode)
178
179 def put_short(self, x):
180 a = chr(x & 0xff)
181 x >>= 8
182 b = chr(x & 0xff)
183 self.put(a + b)
184
185 def put_int(self, x):
186 a = chr(x & 0xff)
187 x >>= 8
188 b = chr(x & 0xff)
189 x >>= 8
190 c = chr(x & 0xff)
191 x >>= 8
192 d = chr(x & 0xff)
193 self.put(a + b + c + d)
194
195 def put_pascal(self, x):
196 lng = len(x)
197 if lng > 255:
198 self.raise_exc('not a pascal string')
199 self.put(chr(lng))
200 self.put(x)
201
202 def put_w_obj(self, w_obj):
203 marshal(self.space, w_obj, self)
204
205 def dump_w_obj(self, w_obj):
206 space = self.space
207 try:
208 self.put_w_obj(w_obj)
209 except rstackovf.StackOverflow:
210 rstackovf.check_stack_overflow()
211 self._overflow()
212
213 def put_tuple_w(self, typecode, lst_w, single_byte_size=False):
214 self.start(typecode)
215 lng = len(lst_w)
216 if single_byte_size:
217 self.put(chr(lng))
218 else:
219 self.put_int(lng)
220 idx = 0
221 while idx < lng:
222 w_obj = lst_w[idx]
223 marshal(self.space, w_obj, self)
224 idx += 1
225
226 def _overflow(self):
227 self.raise_exc('object too deeply nested to marshal')
228
229
230 class StringMarshaller(Marshaller):
231 def __init__(self, space, version):
232 Marshaller.__init__(self, space, None, version)
233 self.buflis = [chr(0)] * 128
234 self.bufpos = 0
235
236 def put(self, s):
237 pos = self.bufpos
238 lng = len(s)
239 newpos = pos + lng
240 while len(self.buflis) < newpos:
241 self.buflis *= 2
242 idx = 0
243 while idx < lng:
244 self.buflis[pos + idx] = s[idx]
245 idx += 1
246 self.bufpos = newpos
247
248 def put1(self, c):
249 pos = self.bufpos
250 newpos = pos + 1
251 if len(self.buflis) < newpos:
252 self.buflis *= 2
253 self.buflis[pos] = c
254 self.bufpos = newpos
255
256 def atom_int(self, typecode, x):
257 a = chr(x & 0xff)
258 x >>= 8
259 b = chr(x & 0xff)
260 x >>= 8
261 c = chr(x & 0xff)
262 x >>= 8
263 d = chr(x & 0xff)
264 pos = self.bufpos
265 newpos = pos + 5
266 if len(self.buflis) < newpos:
267 self.buflis *= 2
268 self.buflis[pos] = typecode
269 self.buflis[pos+1] = a
270 self.buflis[pos+2] = b
271 self.buflis[pos+3] = c
272 self.buflis[pos+4] = d
273 self.bufpos = newpos
274
275 def put_short(self, x):
276 a = chr(x & 0xff)
277 x >>= 8
278 b = chr(x & 0xff)
279 pos = self.bufpos
280 newpos = pos + 2
281 if len(self.buflis) < newpos:
282 self.buflis *= 2
283 self.buflis[pos] = a
284 self.buflis[pos+1] = b
285 self.bufpos = newpos
286
287 def put_int(self, x):
288 a = chr(x & 0xff)
289 x >>= 8
290 b = chr(x & 0xff)
291 x >>= 8
292 c = chr(x & 0xff)
293 x >>= 8
294 d = chr(x & 0xff)
295 pos = self.bufpos
296 newpos = pos + 4
297 if len(self.buflis) < newpos:
298 self.buflis *= 2
299 self.buflis[pos] = a
300 self.buflis[pos+1] = b
301 self.buflis[pos+2] = c
302 self.buflis[pos+3] = d
303 self.bufpos = newpos
304
305 def get_value(self):
306 return ''.join(self.buflis[:self.bufpos])
307
308
309 def invalid_typecode(space, u, tc):
310 u.raise_exc("bad marshal data (unknown type code %d)" % (ord(tc),))
311
312
313 class Unmarshaller(_Base):
314 hidden_applevel = False
315
316 def __init__(self, space, reader):
317 self.space = space
318 self.reader = reader
319 self.refs_w = []
320
321 def get(self, n):
322 assert n >= 0
323 return self.reader.read(n)
324
325 def get1(self):
326 # the [0] is used to convince the annotator to return a char
327 return self.get(1)[0]
328
329 def save_ref(self, typecode, w_obj):
330 if typecode >= '\x80':
331 assert self.refs_w[-1] is None
332 self.refs_w[-1] = w_obj
333
334 def atom_str(self, typecode):
335 self.start(typecode)
336 lng = self.get_lng()
337 return self.get(lng)
338
339 def atom_lng(self, typecode):
340 self.start(typecode)
341 return self.get_lng()
342
343 def start(self, typecode):
344 tc = self.get1()
345 if tc != typecode:
346 self.raise_exc('invalid marshal data')
347
348 def get_short(self):
349 s = self.get(2)
350 a = ord(s[0])
351 b = ord(s[1])
352 x = a | (b << 8)
353 if x & 0x8000:
354 x = x - 0x10000
355 return x
356
357 def get_int(self):
358 s = self.get(4)
359 a = ord(s[0])
360 b = ord(s[1])
361 c = ord(s[2])
362 d = ord(s[3])
363 if d & 0x80:
364 d -= 0x100
365 x = a | (b<<8) | (c<<16) | (d<<24)
366 return intmask(x)
367
368 def get_lng(self):
369 s = self.get(4)
370 a = ord(s[0])
371 b = ord(s[1])
372 c = ord(s[2])
373 d = ord(s[3])
374 x = a | (b<<8) | (c<<16) | (d<<24)
375 if x >= 0:
376 return x
377 else:
378 self.raise_exc('bad marshal data')
379
380 def get_pascal(self):
381 lng = ord(self.get1())
382 return self.get(lng)
383
384 def get_str(self):
385 lng = self.get_lng()
386 return self.get(lng)
387
388 def _get_w_obj(self, allow_null=False):
389 space = self.space
390 tc = self.get1()
391 typecode = ord(tc)
392 save_ref = bool(typecode & FLAG_REF)
393 typecode = chr(typecode & ~FLAG_REF)
394 bad = False
395 index = len(self.refs_w)
396 w_ret = None
397 if save_ref:
398 self.refs_w.append(None)
399 for current_tc, func, save_ref_in_func in _unmarshallers_unroll:
400 if current_tc == typecode:
401 if save_ref_in_func:
402 save_ref = False
403 w_ret = func(space, self, tc)
404 break
405 else:
406 bad = True
407 if bad:
408 self.raise_exc("bad marshal data (unknown type code %d)" % (ord(typecode),))
409 if save_ref:
410 self.refs_w[index] = w_ret
411 if w_ret is None and not allow_null:
412 raise oefmt(space.w_TypeError, "NULL object in marshal data")
413 return w_ret
414
415 def load_w_obj(self, allow_null=False):
416 try:
417 return self._get_w_obj(allow_null)
418 except rstackovf.StackOverflow:
419 rstackovf.check_stack_overflow()
420 self._overflow()
421 except OperationError as e:
422 if not e.match(self.space, self.space.w_RecursionError):
423 raise
424 # somebody else has already converted the rpython overflow error to
425 # an OperationError (e.g. one of che space.call* calls in
426 # marshal_impl), turn it into a ValueError
427 self._overflow()
428
429 def get_tuple_w(self, single_byte_size=False):
430 if single_byte_size:
431 lng = ord(self.get1())
432 else:
433 lng = self.get_lng()
434 res_w = [None] * lng
435 idx = 0
436 space = self.space
437 w_ret = space.w_None # something not
438 while idx < lng:
439 res_w[idx] = self.load_w_obj()
440 idx += 1
441 if w_ret is None:
442 raise oefmt(space.w_TypeError, "NULL object in marshal data")
443 return res_w
444
445 def _overflow(self):
446 self.raise_exc('object too deeply nested to unmarshal')
447
448
449 class StringUnmarshaller(Unmarshaller):
450 # Unmarshaller with inlined buffer string
451 def __init__(self, space, w_str, hidden_applevel=False):
452 Unmarshaller.__init__(self, space, None)
453 self.buf = space.readbuf_w(w_str)
454 self.bufpos = 0
455 self.limit = self.buf.getlength()
456 self.hidden_applevel = hidden_applevel
457
458 def raise_eof(self):
459 space = self.space
460 raise oefmt(space.w_EOFError, "EOF read where object expected")
461
462 def get(self, n):
463 pos = self.bufpos
464 newpos = pos + n
465 if newpos > self.limit:
466 self.raise_eof()
467 self.bufpos = newpos
468 return self.buf.getslice(pos, 1, newpos - pos)
469
470 def get1(self):
471 pos = self.bufpos
472 if pos >= self.limit:
473 self.raise_eof()
474 self.bufpos = pos + 1
475 return self.buf.getitem(pos)
476
477 def get_int(self):
478 pos = self.bufpos
479 newpos = pos + 4
480 if newpos > self.limit:
481 self.raise_eof()
482 self.bufpos = newpos
483 a = ord(self.buf.getitem(pos))
484 b = ord(self.buf.getitem(pos+1))
485 c = ord(self.buf.getitem(pos+2))
486 d = ord(self.buf.getitem(pos+3))
487 if d & 0x80:
488 d -= 0x100
489 x = a | (b<<8) | (c<<16) | (d<<24)
490 return intmask(x)
491
492 def get_lng(self):
493 pos = self.bufpos
494 newpos = pos + 4
495 if newpos > self.limit:
496 self.raise_eof()
497 self.bufpos = newpos
498 a = ord(self.buf.getitem(pos))
499 b = ord(self.buf.getitem(pos+1))
500 c = ord(self.buf.getitem(pos+2))
501 d = ord(self.buf.getitem(pos+3))
502 x = a | (b<<8) | (c<<16) | (d<<24)
503 if x >= 0:
504 return x
505 else:
506 self.raise_exc('bad marshal data')