From: dirkf Date: Wed, 17 Aug 2022 13:22:02 +0000 (+0100) Subject: [jsinterp] Improve JS language support (#31175) X-Git-Url: http://git.oshgnacknak.de/?a=commitdiff_plain;h=b0a60ce2032172aeaaf27fe3866ab72768f10cb2;p=youtube-dl [jsinterp] Improve JS language support (#31175) * operator ?? * operator ?. * operator ** * accurate operator functions * `undefined` handling * object literals {a: 1, "b": expr} * more tests for weird JS comparisons: see https://github.com/ytdl-org/youtube-dl/issues/31173#issuecomment-1217854397. --- diff --git a/test/test_jsinterp.py b/test/test_jsinterp.py index c6c931743..328941e09 100644 --- a/test/test_jsinterp.py +++ b/test/test_jsinterp.py @@ -8,7 +8,10 @@ import sys import unittest sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +import math + from youtube_dl.jsinterp import JSInterpreter +undefined = JSInterpreter.undefined class TestJSInterpreter(unittest.TestCase): @@ -48,6 +51,9 @@ class TestJSInterpreter(unittest.TestCase): jsi = JSInterpreter('function f(){return 1 << 5;}') self.assertEqual(jsi.call_function('f'), 32) + jsi = JSInterpreter('function f(){return 2 ** 5}') + self.assertEqual(jsi.call_function('f'), 32) + jsi = JSInterpreter('function f(){return 19 & 21;}') self.assertEqual(jsi.call_function('f'), 17) @@ -57,6 +63,15 @@ class TestJSInterpreter(unittest.TestCase): jsi = JSInterpreter('function f(){return []? 2+3: 4;}') self.assertEqual(jsi.call_function('f'), 5) + jsi = JSInterpreter('function f(){return 1 == 2}') + self.assertEqual(jsi.call_function('f'), False) + + jsi = JSInterpreter('function f(){return 0 && 1 || 2;}') + self.assertEqual(jsi.call_function('f'), 2) + + jsi = JSInterpreter('function f(){return 0 ?? 42;}') + self.assertEqual(jsi.call_function('f'), 0) + def test_array_access(self): jsi = JSInterpreter('function f(){var x = [1,2,3]; x[0] = 4; x[0] = 5; x[2.0] = 7; return x;}') self.assertEqual(jsi.call_function('f'), [5, 2, 7]) @@ -203,6 +218,11 @@ class TestJSInterpreter(unittest.TestCase): ''') self.assertEqual(jsi.call_function('x'), 7) + jsi = JSInterpreter(''' + function x() { return (l=[0,1,2,3], function(a, b){return a+b})((l[1], l[2]), l[3]) } + ''') + self.assertEqual(jsi.call_function('x'), 5) + def test_void(self): jsi = JSInterpreter(''' function x() { return void 42; } @@ -215,6 +235,100 @@ class TestJSInterpreter(unittest.TestCase): ''') self.assertEqual(jsi.call_function('x')([]), 1) + def test_null(self): + jsi = JSInterpreter(''' + function x() { return null; } + ''') + self.assertIs(jsi.call_function('x'), None) + + jsi = JSInterpreter(''' + function x() { return [null > 0, null < 0, null == 0, null === 0]; } + ''') + self.assertEqual(jsi.call_function('x'), [False, False, False, False]) + + jsi = JSInterpreter(''' + function x() { return [null >= 0, null <= 0]; } + ''') + self.assertEqual(jsi.call_function('x'), [True, True]) + + def test_undefined(self): + jsi = JSInterpreter(''' + function x() { return undefined === undefined; } + ''') + self.assertTrue(jsi.call_function('x')) + + jsi = JSInterpreter(''' + function x() { return undefined; } + ''') + self.assertIs(jsi.call_function('x'), undefined) + + jsi = JSInterpreter(''' + function x() { let v; return v; } + ''') + self.assertIs(jsi.call_function('x'), undefined) + + jsi = JSInterpreter(''' + function x() { return [undefined === undefined, undefined == undefined, undefined < undefined, undefined > undefined]; } + ''') + self.assertEqual(jsi.call_function('x'), [True, True, False, False]) + + jsi = JSInterpreter(''' + function x() { return [undefined === 0, undefined == 0, undefined < 0, undefined > 0]; } + ''') + self.assertEqual(jsi.call_function('x'), [False, False, False, False]) + + jsi = JSInterpreter(''' + function x() { return [undefined >= 0, undefined <= 0]; } + ''') + self.assertEqual(jsi.call_function('x'), [False, False]) + + jsi = JSInterpreter(''' + function x() { return [undefined > null, undefined < null, undefined == null, undefined === null]; } + ''') + self.assertEqual(jsi.call_function('x'), [False, False, True, False]) + + jsi = JSInterpreter(''' + function x() { return [undefined === null, undefined == null, undefined < null, undefined > null]; } + ''') + self.assertEqual(jsi.call_function('x'), [False, True, False, False]) + + jsi = JSInterpreter(''' + function x() { let v; return [42+v, v+42, v**42, 42**v, 0**v]; } + ''') + for y in jsi.call_function('x'): + self.assertTrue(math.isnan(y)) + + jsi = JSInterpreter(''' + function x() { let v; return v**0; } + ''') + self.assertEqual(jsi.call_function('x'), 1) + + jsi = JSInterpreter(''' + function x() { let v; return [v>42, v<=42, v&&42, 42&&v]; } + ''') + self.assertEqual(jsi.call_function('x'), [False, False, undefined, undefined]) + + jsi = JSInterpreter('function x(){return undefined ?? 42; }') + self.assertEqual(jsi.call_function('x'), 42) + + def test_object(self): + jsi = JSInterpreter(''' + function x() { return {}; } + ''') + self.assertEqual(jsi.call_function('x'), {}) + jsi = JSInterpreter(''' + function x() { let a = {m1: 42, m2: 0 }; return [a["m1"], a.m2]; } + ''') + self.assertEqual(jsi.call_function('x'), [42, 0]) + jsi = JSInterpreter(''' + function x() { let a; return a?.qq; } + ''') + self.assertIs(jsi.call_function('x'), undefined) + jsi = JSInterpreter(''' + function x() { let a = {m1: 42, m2: 0 }; return a?.qq; } + ''') + self.assertIs(jsi.call_function('x'), undefined) + if __name__ == '__main__': unittest.main() diff --git a/test/test_youtube_signature.py b/test/test_youtube_signature.py index 6e955e0f0..4d756dad3 100644 --- a/test/test_youtube_signature.py +++ b/test/test_youtube_signature.py @@ -102,6 +102,10 @@ _NSIG_TESTS = [ 'https://www.youtube.com/s/player/4c3f79c5/player_ias.vflset/en_US/base.js', 'TDCstCG66tEAO5pR9o', 'dbxNtZ14c-yWyw', ), + ( + 'https://www.youtube.com/s/player/c81bbb4a/player_ias.vflset/en_US/base.js', + 'gre3EcLurNY2vqp94', 'Z9DfGxWP115WTg', + ), ] diff --git a/youtube_dl/jsinterp.py b/youtube_dl/jsinterp.py index c60a9b3c2..8e119d08a 100644 --- a/youtube_dl/jsinterp.py +++ b/youtube_dl/jsinterp.py @@ -7,7 +7,6 @@ import operator import re from .utils import ( - NO_DEFAULT, ExtractorError, js_to_json, remove_quotes, @@ -21,6 +20,70 @@ from .compat import ( _NAME_RE = r'[a-zA-Z_$][\w$]*' +_UNDEFINED = object() + + +def _js_bit_op(op): + + def wrapped(a, b): + def zeroise(x): + return 0 if x in (None, _UNDEFINED) else x + return op(zeroise(a), zeroise(b)) + + return wrapped + + +def _js_arith_op(op): + + def wrapped(a, b): + if _UNDEFINED in (a, b): + return float('nan') + return op(a or 0, b or 0) + + return wrapped + + +def _js_div(a, b): + if _UNDEFINED in (a, b) or not (a and b): + return float('nan') + return float('inf') if not b else operator.truediv(a or 0, b) + + +def _js_mod(a, b): + if _UNDEFINED in (a, b) or not b: + return float('nan') + return (a or 0) % b + + +def _js_exp(a, b): + if not b: + # even 0 ** 0 !! + return 1 + if _UNDEFINED in (a, b): + return float('nan') + return (a or 0) ** b + + +def _js_eq_op(op): + + def wrapped(a, b): + if set((a, b)) <= set((None, _UNDEFINED)): + return op(a, a) + return op(a, b) + + return wrapped + + +def _js_comp_op(op): + + def wrapped(a, b): + if _UNDEFINED in (a, b): + return False + return op(a or 0, b or 0) + + return wrapped + + # (op, definition) in order of binding priority, tightest first # avoid dict to maintain order # definition None => Defined in JSInterpreter._operator @@ -30,40 +93,38 @@ _DOT_OPERATORS = ( ) _OPERATORS = ( - ('|', operator.or_), - ('^', operator.xor), - ('&', operator.and_), - ('>>', operator.rshift), - ('<<', operator.lshift), - ('+', operator.add), - ('-', operator.sub), - ('*', operator.mul), - ('/', operator.truediv), - ('%', operator.mod), + ('>>', _js_bit_op(operator.rshift)), + ('<<', _js_bit_op(operator.lshift)), + ('+', _js_arith_op(operator.add)), + ('-', _js_arith_op(operator.sub)), + ('*', _js_arith_op(operator.mul)), + ('/', _js_div), + ('%', _js_mod), + ('**', _js_exp), ) _COMP_OPERATORS = ( ('===', operator.is_), - ('==', operator.eq), + ('==', _js_eq_op(operator.eq)), ('!==', operator.is_not), - ('!=', operator.ne), - ('<=', operator.le), - ('>=', operator.ge), - ('<', operator.lt), - ('>', operator.gt), + ('!=', _js_eq_op(operator.ne)), + ('<=', _js_comp_op(operator.le)), + ('>=', _js_comp_op(operator.ge)), + ('<', _js_comp_op(operator.lt)), + ('>', _js_comp_op(operator.gt)), ) _LOG_OPERATORS = ( - ('&', operator.and_), - ('|', operator.or_), - ('^', operator.xor), + ('|', _js_bit_op(operator.or_)), + ('^', _js_bit_op(operator.xor)), + ('&', _js_bit_op(operator.and_)), ) _SC_OPERATORS = ( ('?', None), + ('??', None), ('||', None), ('&&', None), - # TODO: ('??', None), ) _OPERATOR_RE = '|'.join(map(lambda x: re.escape(x[0]), _OPERATORS + _LOG_OPERATORS)) @@ -74,7 +135,7 @@ _QUOTES = '\'"' def _ternary(cndn, if_true=True, if_false=False): """Simulate JS's ternary operator (cndn?if_true:if_false)""" - if cndn in (False, None, 0, ''): + if cndn in (False, None, 0, '', _UNDEFINED): return if_false try: if math.isnan(cndn): # NB: NaN cannot be checked by membership @@ -95,6 +156,12 @@ class JS_Continue(ExtractorError): class LocalNameSpace(ChainMap): + def __getitem__(self, key): + try: + return super(LocalNameSpace, self).__getitem__(key) + except KeyError: + return _UNDEFINED + def __setitem__(self, key, value): for scope in self.maps: if key in scope: @@ -105,6 +172,13 @@ class LocalNameSpace(ChainMap): def __delitem__(self, key): raise NotImplementedError('Deleting is not supported') + def __contains__(self, key): + try: + super(LocalNameSpace, self).__getitem__(key) + return True + except KeyError: + return False + def __repr__(self): return 'LocalNameSpace%s' % (self.maps, ) @@ -112,6 +186,8 @@ class LocalNameSpace(ChainMap): class JSInterpreter(object): __named_object_counter = 0 + undefined = _UNDEFINED + def __init__(self, code, objects=None): self.code, self._functions = code, {} self._objects = {} if objects is None else objects @@ -185,12 +261,16 @@ class JSInterpreter(object): @staticmethod def _all_operators(): return itertools.chain( + # Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence _SC_OPERATORS, _LOG_OPERATORS, _COMP_OPERATORS, _OPERATORS) def _operator(self, op, left_val, right_expr, expr, local_vars, allow_recursion): if op in ('||', '&&'): if (op == '&&') ^ _ternary(left_val): return left_val # short circuiting + elif op == '??': + if left_val not in (None, self.undefined): + return left_val elif op == '?': right_expr = _ternary(left_val, *self._separate(right_expr, ':', 1)) @@ -204,12 +284,14 @@ class JSInterpreter(object): except Exception as e: raise self.Exception('Failed to evaluate {left_val!r} {op} {right_val!r}'.format(**locals()), expr, cause=e) - def _index(self, obj, idx): + def _index(self, obj, idx, allow_undefined=False): if idx == 'length': return len(obj) try: return obj[int(idx)] if isinstance(obj, list) else obj[idx] except Exception as e: + if allow_undefined: + return self.undefined raise self.Exception('Cannot get index {idx}'.format(**locals()), expr=repr(obj), cause=e) def _dump(self, obj, namespace): @@ -249,8 +331,8 @@ class JSInterpreter(object): obj = expr[4:] if obj.startswith('Date('): left, right = self._separate_at_paren(obj[4:], ')') - left = self.interpret_expression(left, local_vars, allow_recursion) - expr = unified_timestamp(left, False) + expr = unified_timestamp( + self.interpret_expression(left, local_vars, allow_recursion), False) if not expr: raise self.Exception('Failed to parse date {left!r}'.format(**locals()), expr=expr) expr = self._dump(int(expr * 1000), local_vars) + right @@ -263,6 +345,14 @@ class JSInterpreter(object): if expr.startswith('{'): inner, outer = self._separate_at_paren(expr, '}') + # try for object expression + sub_expressions = [list(self._separate(sub_expr.strip(), ':', 1)) for sub_expr in self._separate(inner)] + if all(len(sub_expr) == 2 for sub_expr in sub_expressions): + return dict( + (key_expr if re.match(_NAME_RE, key_expr) else key_expr, + self.interpret_expression(val_expr, local_vars, allow_recursion)) + for key_expr, val_expr in sub_expressions), should_return + # or statement list inner, should_abort = self.interpret_statement(inner, local_vars, allow_recursion) if not outer or should_abort: return inner, should_abort or should_return @@ -387,13 +477,13 @@ class JSInterpreter(object): (?P (?P{_NAME_RE})(?:\[(?P[^\]]+?)\])?\s* (?P{_OPERATOR_RE})? - =(?P.*)$ + =(?!=)(?P.*)$ )|(?P (?!if|return|true|false|null|undefined)(?P{_NAME_RE})$ )|(?P (?P{_NAME_RE})\[(?P.+)\]$ )|(?P - (?P{_NAME_RE})(?:\.(?P[^(]+)|\[(?P[^\]]+)\])\s* + (?P{_NAME_RE})(?:(?P\?)?\.(?P[^(]+)|\[(?P[^\]]+)\])\s* )|(?P (?P{_NAME_RE})\((?P.*)\)$ )'''.format(**globals()), expr) @@ -405,7 +495,7 @@ class JSInterpreter(object): local_vars[m.group('out')] = self._operator( m.group('op'), left_val, m.group('expr'), expr, local_vars, allow_recursion) return local_vars[m.group('out')], should_return - elif left_val is None: + elif left_val in (None, self.undefined): raise self.Exception('Cannot index undefined variable ' + m.group('out'), expr=expr) idx = self.interpret_expression(m.group('index'), local_vars, allow_recursion) @@ -424,6 +514,9 @@ class JSInterpreter(object): elif expr == 'continue': raise JS_Continue() + elif expr == 'undefined': + return self.undefined, should_return + elif md.get('return'): return local_vars[m.group('name')], should_return @@ -441,7 +534,9 @@ class JSInterpreter(object): for op, _ in self._all_operators(): # hackety: have higher priority than <>, but don't confuse them - skip_delim = (op + op) if op in ('<', '>') else None + skip_delim = (op + op) if op in '<>*?' else None + if op == '?': + skip_delim = (skip_delim, '?.') separated = list(self._separate(expr, op, skip_delims=skip_delim)) if len(separated) < 2: continue @@ -451,12 +546,10 @@ class JSInterpreter(object): right_expr = '-' + right_expr separated.pop() left_val = self.interpret_expression(op.join(separated), local_vars, allow_recursion) - return self._operator(op, 0 if left_val is None else left_val, - right_expr, expr, local_vars, allow_recursion), should_return + return self._operator(op, left_val, right_expr, expr, local_vars, allow_recursion), should_return if md.get('attribute'): - variable = m.group('var') - member = m.group('member') + variable, member, nullish = m.group('var', 'member', 'nullish') if not member: member = self.interpret_expression(m.group('member2'), local_vars, allow_recursion) arg_str = expr[m.end():] @@ -477,15 +570,24 @@ class JSInterpreter(object): 'String': compat_str, 'Math': float, } - obj = local_vars.get(variable, types.get(variable, NO_DEFAULT)) - if obj is NO_DEFAULT: - if variable not in self._objects: - self._objects[variable] = self.extract_object(variable) - obj = self._objects[variable] + obj = local_vars.get(variable) + if obj in (self.undefined, None): + obj = types.get(variable, self.undefined) + if obj is self.undefined: + try: + if variable not in self._objects: + self._objects[variable] = self.extract_object(variable) + obj = self._objects[variable] + except self.Exception: + if not nullish: + raise + + if nullish and obj is self.undefined: + return self.undefined # Member access if arg_str is None: - return self._index(obj, member) + return self._index(obj, member, nullish) # Function call argvals = [ @@ -660,7 +762,14 @@ class JSInterpreter(object): def build_arglist(cls, arg_text): if not arg_text: return [] - return list(filter(None, (x.strip() or None for x in cls._separate(arg_text)))) + + def valid_arg(y): + y = y.strip() + if not y: + raise cls.Exception('Missing arg in "%s"' % (arg_text, )) + return y + + return [valid_arg(x) for x in cls._separate(arg_text)] def build_function(self, argnames, code, *global_stack): global_stack = list(global_stack) or [{}]