]> jfr.im git - yt-dlp.git/blame - youtube_dl/swfinterp.py
[swfinterp] Implement equals opcode
[yt-dlp.git] / youtube_dl / swfinterp.py
CommitLineData
54256267
PH
1from __future__ import unicode_literals
2
3import collections
4import io
54256267
PH
5import zlib
6
70f767dc
PH
7from .utils import (
8 compat_str,
9 ExtractorError,
c13bf7c8 10 struct_unpack,
70f767dc 11)
54256267
PH
12
13
0cb20563
PH
14def _extract_tags(file_contents):
15 if file_contents[1:3] != b'WS':
16 raise ExtractorError(
17 'Not an SWF file; header is %r' % file_contents[:3])
18 if file_contents[:1] == b'C':
19 content = zlib.decompress(file_contents[8:])
20 else:
21 raise NotImplementedError(
22 'Unsupported compression format %r' %
23 file_contents[:1])
24
25 # Determine number of bits in framesize rectangle
c13bf7c8 26 framesize_nbits = struct_unpack('!B', content[:1])[0] >> 3
0cb20563
PH
27 framesize_len = (5 + 4 * framesize_nbits + 7) // 8
28
29 pos = framesize_len + 2 + 2
54256267 30 while pos < len(content):
c13bf7c8 31 header16 = struct_unpack('<H', content[pos:pos + 2])[0]
54256267
PH
32 pos += 2
33 tag_code = header16 >> 6
34 tag_len = header16 & 0x3f
35 if tag_len == 0x3f:
c13bf7c8 36 tag_len = struct_unpack('<I', content[pos:pos + 4])[0]
54256267 37 pos += 4
0cb20563
PH
38 assert pos + tag_len <= len(content), \
39 ('Tag %d ends at %d+%d - that\'s longer than the file (%d)'
40 % (tag_code, pos, tag_len, len(content)))
54256267
PH
41 yield (tag_code, content[pos:pos + tag_len])
42 pos += tag_len
43
44
45class _AVMClass_Object(object):
46 def __init__(self, avm_class):
47 self.avm_class = avm_class
48
49 def __repr__(self):
50 return '%s#%x' % (self.avm_class.name, id(self))
51
52
0d989011
PH
53class _ScopeDict(dict):
54 def __init__(self, avm_class):
55 super(_ScopeDict, self).__init__()
56 self.avm_class = avm_class
57
58 def __repr__(self):
59 return '%s__Scope(%s)' % (
60 self.avm_class.name,
61 super(_ScopeDict, self).__repr__())
62
63
54256267
PH
64class _AVMClass(object):
65 def __init__(self, name_idx, name):
66 self.name_idx = name_idx
67 self.name = name
68 self.method_names = {}
69 self.method_idxs = {}
70 self.methods = {}
71 self.method_pyfunctions = {}
70f767dc 72
0d989011 73 self.variables = _ScopeDict(self)
54256267
PH
74
75 def make_object(self):
76 return _AVMClass_Object(self)
77
01b4b745
PH
78 def __repr__(self):
79 return '_AVMClass(%s)' % (self.name)
80
81 def register_methods(self, methods):
82 self.method_names.update(methods.items())
83 self.method_idxs.update(dict(
84 (idx, name)
85 for name, idx in methods.items()))
86
54256267 87
decf2ae4
PH
88class _Multiname(object):
89 def __init__(self, kind):
90 self.kind = kind
91
92 def __repr__(self):
93 return '[MULTINAME kind: 0x%x]' % self.kind
94
95
54256267
PH
96def _read_int(reader):
97 res = 0
98 shift = 0
99 for _ in range(5):
100 buf = reader.read(1)
101 assert len(buf) == 1
c13bf7c8 102 b = struct_unpack('<B', buf)[0]
54256267
PH
103 res = res | ((b & 0x7f) << shift)
104 if b & 0x80 == 0:
105 break
106 shift += 7
107 return res
108
109
110def _u30(reader):
111 res = _read_int(reader)
112 assert res & 0xf0000000 == 0
113 return res
351f3738 114_u32 = _read_int
54256267
PH
115
116
117def _s32(reader):
118 v = _read_int(reader)
119 if v & 0x80000000 != 0:
120 v = - ((v ^ 0xffffffff) + 1)
121 return v
122
123
124def _s24(reader):
125 bs = reader.read(3)
126 assert len(bs) == 3
e75c24e8 127 last_byte = b'\xff' if (ord(bs[2:3]) >= 0x80) else b'\x00'
c13bf7c8 128 return struct_unpack('<i', bs + last_byte)[0]
54256267
PH
129
130
131def _read_string(reader):
132 slen = _u30(reader)
133 resb = reader.read(slen)
134 assert len(resb) == slen
135 return resb.decode('utf-8')
136
137
138def _read_bytes(count, reader):
0cb20563 139 assert count >= 0
54256267
PH
140 resb = reader.read(count)
141 assert len(resb) == count
142 return resb
143
144
145def _read_byte(reader):
146 resb = _read_bytes(1, reader=reader)
c13bf7c8 147 res = struct_unpack('<B', resb)[0]
54256267
PH
148 return res
149
150
3cbcff8a
PH
151StringClass = _AVMClass('(no name idx)', 'String')
152
153
54256267
PH
154class SWFInterpreter(object):
155 def __init__(self, file_contents):
b7558d98 156 self._patched_functions = {}
54256267 157 code_tag = next(tag
0cb20563 158 for tag_code, tag in _extract_tags(file_contents)
54256267
PH
159 if tag_code == 82)
160 p = code_tag.index(b'\0', 4) + 1
161 code_reader = io.BytesIO(code_tag[p:])
162
163 # Parse ABC (AVM2 ByteCode)
164
165 # Define a couple convenience methods
166 u30 = lambda *args: _u30(*args, reader=code_reader)
167 s32 = lambda *args: _s32(*args, reader=code_reader)
168 u32 = lambda *args: _u32(*args, reader=code_reader)
169 read_bytes = lambda *args: _read_bytes(*args, reader=code_reader)
170 read_byte = lambda *args: _read_byte(*args, reader=code_reader)
171
172 # minor_version + major_version
173 read_bytes(2 + 2)
174
175 # Constant pool
176 int_count = u30()
177 for _c in range(1, int_count):
178 s32()
179 uint_count = u30()
180 for _c in range(1, uint_count):
181 u32()
182 double_count = u30()
0cb20563 183 read_bytes(max(0, (double_count - 1)) * 8)
54256267 184 string_count = u30()
70f767dc 185 self.constant_strings = ['']
54256267
PH
186 for _c in range(1, string_count):
187 s = _read_string(code_reader)
70f767dc 188 self.constant_strings.append(s)
54256267
PH
189 namespace_count = u30()
190 for _c in range(1, namespace_count):
191 read_bytes(1) # kind
192 u30() # name
193 ns_set_count = u30()
194 for _c in range(1, ns_set_count):
195 count = u30()
196 for _c2 in range(count):
197 u30()
198 multiname_count = u30()
199 MULTINAME_SIZES = {
200 0x07: 2, # QName
201 0x0d: 2, # QNameA
202 0x0f: 1, # RTQName
203 0x10: 1, # RTQNameA
204 0x11: 0, # RTQNameL
205 0x12: 0, # RTQNameLA
206 0x09: 2, # Multiname
207 0x0e: 2, # MultinameA
208 0x1b: 1, # MultinameL
209 0x1c: 1, # MultinameLA
210 }
211 self.multinames = ['']
212 for _c in range(1, multiname_count):
213 kind = u30()
214 assert kind in MULTINAME_SIZES, 'Invalid multiname kind %r' % kind
215 if kind == 0x07:
216 u30() # namespace_idx
217 name_idx = u30()
70f767dc 218 self.multinames.append(self.constant_strings[name_idx])
4baafa22
PH
219 elif kind == 0x09:
220 name_idx = u30()
221 u30()
222 self.multinames.append(self.constant_strings[name_idx])
54256267 223 else:
decf2ae4 224 self.multinames.append(_Multiname(kind))
54256267
PH
225 for _c2 in range(MULTINAME_SIZES[kind]):
226 u30()
227
228 # Methods
229 method_count = u30()
230 MethodInfo = collections.namedtuple(
231 'MethodInfo',
232 ['NEED_ARGUMENTS', 'NEED_REST'])
233 method_infos = []
234 for method_id in range(method_count):
235 param_count = u30()
236 u30() # return type
237 for _ in range(param_count):
238 u30() # param type
239 u30() # name index (always 0 for youtube)
240 flags = read_byte()
241 if flags & 0x08 != 0:
242 # Options present
243 option_count = u30()
244 for c in range(option_count):
245 u30() # val
246 read_bytes(1) # kind
247 if flags & 0x80 != 0:
248 # Param names present
249 for _ in range(param_count):
250 u30() # param name
251 mi = MethodInfo(flags & 0x01 != 0, flags & 0x04 != 0)
252 method_infos.append(mi)
253
254 # Metadata
255 metadata_count = u30()
256 for _c in range(metadata_count):
257 u30() # name
258 item_count = u30()
259 for _c2 in range(item_count):
260 u30() # key
261 u30() # value
262
263 def parse_traits_info():
264 trait_name_idx = u30()
265 kind_full = read_byte()
266 kind = kind_full & 0x0f
267 attrs = kind_full >> 4
268 methods = {}
269 if kind in [0x00, 0x06]: # Slot or Const
270 u30() # Slot id
271 u30() # type_name_idx
272 vindex = u30()
273 if vindex != 0:
274 read_byte() # vkind
275 elif kind in [0x01, 0x02, 0x03]: # Method / Getter / Setter
276 u30() # disp_id
277 method_idx = u30()
278 methods[self.multinames[trait_name_idx]] = method_idx
279 elif kind == 0x04: # Class
280 u30() # slot_id
281 u30() # classi
282 elif kind == 0x05: # Function
283 u30() # slot_id
284 function_idx = u30()
285 methods[function_idx] = self.multinames[trait_name_idx]
286 else:
287 raise ExtractorError('Unsupported trait kind %d' % kind)
288
289 if attrs & 0x4 != 0: # Metadata present
290 metadata_count = u30()
291 for _c3 in range(metadata_count):
292 u30() # metadata index
293
294 return methods
295
296 # Classes
297 class_count = u30()
298 classes = []
299 for class_id in range(class_count):
300 name_idx = u30()
01b4b745
PH
301
302 cname = self.multinames[name_idx]
303 avm_class = _AVMClass(name_idx, cname)
304 classes.append(avm_class)
305
54256267
PH
306 u30() # super_name idx
307 flags = read_byte()
308 if flags & 0x08 != 0: # Protected namespace is present
309 u30() # protected_ns_idx
310 intrf_count = u30()
311 for _c2 in range(intrf_count):
312 u30()
313 u30() # iinit
314 trait_count = u30()
315 for _c2 in range(trait_count):
01b4b745
PH
316 trait_methods = parse_traits_info()
317 avm_class.register_methods(trait_methods)
318
54256267
PH
319 assert len(classes) == class_count
320 self._classes_by_name = dict((c.name, c) for c in classes)
321
322 for avm_class in classes:
323 u30() # cinit
324 trait_count = u30()
325 for _c2 in range(trait_count):
326 trait_methods = parse_traits_info()
01b4b745 327 avm_class.register_methods(trait_methods)
54256267
PH
328
329 # Scripts
330 script_count = u30()
331 for _c in range(script_count):
332 u30() # init
333 trait_count = u30()
334 for _c2 in range(trait_count):
335 parse_traits_info()
336
337 # Method bodies
338 method_body_count = u30()
339 Method = collections.namedtuple('Method', ['code', 'local_count'])
340 for _c in range(method_body_count):
341 method_idx = u30()
342 u30() # max_stack
343 local_count = u30()
344 u30() # init_scope_depth
345 u30() # max_scope_depth
346 code_length = u30()
347 code = read_bytes(code_length)
348 for avm_class in classes:
349 if method_idx in avm_class.method_idxs:
350 m = Method(code, local_count)
351 avm_class.methods[avm_class.method_idxs[method_idx]] = m
352 exception_count = u30()
353 for _c2 in range(exception_count):
354 u30() # from
355 u30() # to
356 u30() # target
357 u30() # exc_type
358 u30() # var_name
359 trait_count = u30()
360 for _c2 in range(trait_count):
361 parse_traits_info()
362
363 assert p + code_reader.tell() == len(code_tag)
364
b7558d98
PH
365 def patch_function(self, avm_class, func_name, f):
366 self._patched_functions[(avm_class, func_name)] = f
367
54256267
PH
368 def extract_class(self, class_name):
369 try:
370 return self._classes_by_name[class_name]
371 except KeyError:
372 raise ExtractorError('Class %r not found' % class_name)
373
374 def extract_function(self, avm_class, func_name):
b7558d98
PH
375 p = self._patched_functions.get((avm_class, func_name))
376 if p:
377 return p
54256267
PH
378 if func_name in avm_class.method_pyfunctions:
379 return avm_class.method_pyfunctions[func_name]
380 if func_name in self._classes_by_name:
381 return self._classes_by_name[func_name].make_object()
382 if func_name not in avm_class.methods:
01b4b745
PH
383 raise ExtractorError('Cannot find function %s.%s' % (
384 avm_class.name, func_name))
54256267
PH
385 m = avm_class.methods[func_name]
386
387 def resfunc(args):
388 # Helper functions
389 coder = io.BytesIO(m.code)
390 s24 = lambda: _s24(coder)
391 u30 = lambda: _u30(coder)
392
e75c24e8 393 registers = [avm_class.variables] + list(args) + [None] * m.local_count
54256267 394 stack = []
01b4b745
PH
395 scopes = collections.deque([
396 self._classes_by_name, avm_class.variables])
54256267
PH
397 while True:
398 opcode = _read_byte(coder)
e983cf52
PH
399 if opcode == 16: # jump
400 offset = s24()
401 coder.seek(coder.tell() + offset)
402 elif opcode == 17: # iftrue
54256267
PH
403 offset = s24()
404 value = stack.pop()
405 if value:
406 coder.seek(coder.tell() + offset)
e75c24e8
PH
407 elif opcode == 18: # iffalse
408 offset = s24()
409 value = stack.pop()
410 if not value:
411 coder.seek(coder.tell() + offset)
e983cf52
PH
412 elif opcode == 19: # ifeq
413 offset = s24()
414 value2 = stack.pop()
415 value1 = stack.pop()
416 if value2 == value1:
417 coder.seek(coder.tell() + offset)
418 elif opcode == 20: # ifne
419 offset = s24()
420 value2 = stack.pop()
421 value1 = stack.pop()
422 if value2 != value1:
423 coder.seek(coder.tell() + offset)
424 elif opcode == 32: # pushnull
425 stack.append(None)
54256267
PH
426 elif opcode == 36: # pushbyte
427 v = _read_byte(coder)
428 stack.append(v)
0cb20563
PH
429 elif opcode == 42: # dup
430 value = stack[-1]
431 stack.append(value)
54256267
PH
432 elif opcode == 44: # pushstring
433 idx = u30()
70f767dc 434 stack.append(self.constant_strings[idx])
54256267 435 elif opcode == 48: # pushscope
54256267 436 new_scope = stack.pop()
e75c24e8 437 scopes.append(new_scope)
decf2ae4
PH
438 elif opcode == 66: # construct
439 arg_count = u30()
440 args = list(reversed(
441 [stack.pop() for _ in range(arg_count)]))
442 obj = stack.pop()
443 res = obj.avm_class.make_object()
444 stack.append(res)
54256267
PH
445 elif opcode == 70: # callproperty
446 index = u30()
447 mname = self.multinames[index]
448 arg_count = u30()
449 args = list(reversed(
450 [stack.pop() for _ in range(arg_count)]))
451 obj = stack.pop()
01b4b745
PH
452
453 if isinstance(obj, _AVMClass_Object):
454 func = self.extract_function(obj.avm_class, mname)
455 res = func(args)
54256267 456 stack.append(res)
01b4b745 457 continue
0d989011
PH
458 elif isinstance(obj, _ScopeDict):
459 if mname in obj.avm_class.method_names:
460 func = self.extract_function(obj.avm_class, mname)
461 res = func(args)
462 else:
463 res = obj[mname]
464 stack.append(res)
465 continue
01b4b745
PH
466 elif isinstance(obj, compat_str):
467 if mname == 'split':
468 assert len(args) == 1
469 assert isinstance(args[0], compat_str)
470 if args[0] == '':
471 res = list(obj)
472 else:
473 res = obj.split(args[0])
474 stack.append(res)
475 continue
476 elif isinstance(obj, list):
477 if mname == 'slice':
478 assert len(args) == 1
479 assert isinstance(args[0], int)
480 res = obj[args[0]:]
481 stack.append(res)
482 continue
483 elif mname == 'join':
484 assert len(args) == 1
485 assert isinstance(args[0], compat_str)
486 res = args[0].join(obj)
487 stack.append(res)
488 continue
3cbcff8a
PH
489 elif obj == StringClass:
490 if mname == 'String':
491 assert len(args) == 1
492 assert isinstance(args[0], (int, compat_str))
493 res = compat_str(args[0])
494 stack.append(res)
495 continue
496 else:
497 raise NotImplementedError(
498 'Function String.%s is not yet implemented'
499 % mname)
01b4b745
PH
500 raise NotImplementedError(
501 'Unsupported property %r on %r'
502 % (mname, obj))
54256267
PH
503 elif opcode == 72: # returnvalue
504 res = stack.pop()
505 return res
506 elif opcode == 74: # constructproperty
507 index = u30()
508 arg_count = u30()
509 args = list(reversed(
510 [stack.pop() for _ in range(arg_count)]))
511 obj = stack.pop()
512
513 mname = self.multinames[index]
01b4b745 514 assert isinstance(obj, _AVMClass)
7fbf54dc 515
54256267
PH
516 # We do not actually call the constructor for now;
517 # we just pretend it does nothing
01b4b745 518 stack.append(obj.make_object())
54256267
PH
519 elif opcode == 79: # callpropvoid
520 index = u30()
521 mname = self.multinames[index]
522 arg_count = u30()
523 args = list(reversed(
524 [stack.pop() for _ in range(arg_count)]))
525 obj = stack.pop()
526 if mname == 'reverse':
527 assert isinstance(obj, list)
528 obj.reverse()
529 else:
530 raise NotImplementedError(
531 'Unsupported (void) property %r on %r'
532 % (mname, obj))
533 elif opcode == 86: # newarray
534 arg_count = u30()
535 arr = []
536 for i in range(arg_count):
537 arr.append(stack.pop())
538 arr = arr[::-1]
539 stack.append(arr)
70f767dc
PH
540 elif opcode == 93: # findpropstrict
541 index = u30()
542 mname = self.multinames[index]
543 for s in reversed(scopes):
544 if mname in s:
545 res = s
546 break
547 else:
548 res = scopes[0]
3cbcff8a
PH
549 if mname not in res and mname == 'String':
550 stack.append(StringClass)
551 else:
552 stack.append(res[mname])
54256267
PH
553 elif opcode == 94: # findproperty
554 index = u30()
555 mname = self.multinames[index]
e75c24e8
PH
556 for s in reversed(scopes):
557 if mname in s:
558 res = s
559 break
560 else:
01b4b745 561 res = avm_class.variables
54256267
PH
562 stack.append(res)
563 elif opcode == 96: # getlex
564 index = u30()
565 mname = self.multinames[index]
e75c24e8
PH
566 for s in reversed(scopes):
567 if mname in s:
568 scope = s
569 break
570 else:
01b4b745 571 scope = avm_class.variables
e75c24e8
PH
572 # I cannot find where static variables are initialized
573 # so let's just return None
574 res = scope.get(mname)
54256267
PH
575 stack.append(res)
576 elif opcode == 97: # setproperty
577 index = u30()
578 value = stack.pop()
579 idx = self.multinames[index]
decf2ae4
PH
580 if isinstance(idx, _Multiname):
581 idx = stack.pop()
54256267
PH
582 obj = stack.pop()
583 obj[idx] = value
584 elif opcode == 98: # getlocal
585 index = u30()
586 stack.append(registers[index])
587 elif opcode == 99: # setlocal
588 index = u30()
589 value = stack.pop()
590 registers[index] = value
591 elif opcode == 102: # getproperty
592 index = u30()
593 pname = self.multinames[index]
594 if pname == 'length':
595 obj = stack.pop()
3cbcff8a 596 assert isinstance(obj, (compat_str, list))
54256267 597 stack.append(len(obj))
4baafa22
PH
598 elif isinstance(pname, compat_str): # Member access
599 obj = stack.pop()
600 assert isinstance(obj, (dict, _ScopeDict)), \
0ab1ca55 601 'Accessing member %r on %r' % (pname, obj)
4baafa22 602 stack.append(obj[pname])
54256267
PH
603 else: # Assume attribute access
604 idx = stack.pop()
605 assert isinstance(idx, int)
606 obj = stack.pop()
607 assert isinstance(obj, list)
608 stack.append(obj[idx])
0cb20563
PH
609 elif opcode == 115: # convert_
610 value = stack.pop()
611 intvalue = int(value)
612 stack.append(intvalue)
54256267
PH
613 elif opcode == 128: # coerce
614 u30()
615 elif opcode == 133: # coerce_s
616 assert isinstance(stack[-1], (type(None), compat_str))
0cb20563
PH
617 elif opcode == 160: # add
618 value2 = stack.pop()
619 value1 = stack.pop()
620 res = value1 + value2
621 stack.append(res)
622 elif opcode == 161: # subtract
623 value2 = stack.pop()
624 value1 = stack.pop()
625 res = value1 - value2
626 stack.append(res)
54256267
PH
627 elif opcode == 164: # modulo
628 value2 = stack.pop()
629 value1 = stack.pop()
630 res = value1 % value2
631 stack.append(res)
eb537604
PH
632 elif opcode == 171: # equals
633 value2 = stack.pop()
634 value1 = stack.pop()
635 result = value1 == value2
636 stack.append(result)
54256267
PH
637 elif opcode == 175: # greaterequals
638 value2 = stack.pop()
639 value1 = stack.pop()
640 result = value1 >= value2
641 stack.append(result)
642 elif opcode == 208: # getlocal_0
643 stack.append(registers[0])
644 elif opcode == 209: # getlocal_1
645 stack.append(registers[1])
646 elif opcode == 210: # getlocal_2
647 stack.append(registers[2])
648 elif opcode == 211: # getlocal_3
649 stack.append(registers[3])
70f767dc
PH
650 elif opcode == 212: # setlocal_0
651 registers[0] = stack.pop()
652 elif opcode == 213: # setlocal_1
653 registers[1] = stack.pop()
54256267
PH
654 elif opcode == 214: # setlocal_2
655 registers[2] = stack.pop()
656 elif opcode == 215: # setlocal_3
657 registers[3] = stack.pop()
658 else:
659 raise NotImplementedError(
660 'Unsupported opcode %d' % opcode)
661
662 avm_class.method_pyfunctions[func_name] = resfunc
663 return resfunc
664