GlobalObject.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. /*
  2. * Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2020, Linus Groh <linusg@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/CharacterTypes.h>
  8. #include <AK/Hex.h>
  9. #include <AK/Platform.h>
  10. #include <AK/TemporaryChange.h>
  11. #include <AK/Utf8View.h>
  12. #include <LibJS/Console.h>
  13. #include <LibJS/Heap/DeferGC.h>
  14. #include <LibJS/Interpreter.h>
  15. #include <LibJS/Lexer.h>
  16. #include <LibJS/Parser.h>
  17. #include <LibJS/Runtime/ArrayBufferConstructor.h>
  18. #include <LibJS/Runtime/ArrayBufferPrototype.h>
  19. #include <LibJS/Runtime/ArrayConstructor.h>
  20. #include <LibJS/Runtime/ArrayIteratorPrototype.h>
  21. #include <LibJS/Runtime/ArrayPrototype.h>
  22. #include <LibJS/Runtime/BigIntConstructor.h>
  23. #include <LibJS/Runtime/BigIntPrototype.h>
  24. #include <LibJS/Runtime/BooleanConstructor.h>
  25. #include <LibJS/Runtime/BooleanPrototype.h>
  26. #include <LibJS/Runtime/ConsoleObject.h>
  27. #include <LibJS/Runtime/DateConstructor.h>
  28. #include <LibJS/Runtime/DatePrototype.h>
  29. #include <LibJS/Runtime/ErrorConstructor.h>
  30. #include <LibJS/Runtime/ErrorPrototype.h>
  31. #include <LibJS/Runtime/FunctionConstructor.h>
  32. #include <LibJS/Runtime/FunctionPrototype.h>
  33. #include <LibJS/Runtime/GlobalObject.h>
  34. #include <LibJS/Runtime/IteratorPrototype.h>
  35. #include <LibJS/Runtime/JSONObject.h>
  36. #include <LibJS/Runtime/MathObject.h>
  37. #include <LibJS/Runtime/NativeFunction.h>
  38. #include <LibJS/Runtime/NumberConstructor.h>
  39. #include <LibJS/Runtime/NumberPrototype.h>
  40. #include <LibJS/Runtime/Object.h>
  41. #include <LibJS/Runtime/ObjectConstructor.h>
  42. #include <LibJS/Runtime/ObjectPrototype.h>
  43. #include <LibJS/Runtime/PromiseConstructor.h>
  44. #include <LibJS/Runtime/PromisePrototype.h>
  45. #include <LibJS/Runtime/ProxyConstructor.h>
  46. #include <LibJS/Runtime/ReflectObject.h>
  47. #include <LibJS/Runtime/RegExpConstructor.h>
  48. #include <LibJS/Runtime/RegExpPrototype.h>
  49. #include <LibJS/Runtime/SetConstructor.h>
  50. #include <LibJS/Runtime/SetPrototype.h>
  51. #include <LibJS/Runtime/Shape.h>
  52. #include <LibJS/Runtime/StringConstructor.h>
  53. #include <LibJS/Runtime/StringIteratorPrototype.h>
  54. #include <LibJS/Runtime/StringPrototype.h>
  55. #include <LibJS/Runtime/SymbolConstructor.h>
  56. #include <LibJS/Runtime/SymbolPrototype.h>
  57. #include <LibJS/Runtime/TypedArray.h>
  58. #include <LibJS/Runtime/TypedArrayConstructor.h>
  59. #include <LibJS/Runtime/TypedArrayPrototype.h>
  60. #include <LibJS/Runtime/Value.h>
  61. namespace JS {
  62. GlobalObject::GlobalObject()
  63. : ScopeObject(GlobalObjectTag::Tag)
  64. , m_console(make<Console>(*this))
  65. {
  66. }
  67. void GlobalObject::initialize_global_object()
  68. {
  69. auto& vm = this->vm();
  70. ensure_shape_is_unique();
  71. // These are done first since other prototypes depend on their presence.
  72. m_empty_object_shape = heap().allocate_without_global_object<Shape>(*this);
  73. m_object_prototype = heap().allocate_without_global_object<ObjectPrototype>(*this);
  74. m_function_prototype = heap().allocate_without_global_object<FunctionPrototype>(*this);
  75. m_new_object_shape = vm.heap().allocate_without_global_object<Shape>(*this);
  76. m_new_object_shape->set_prototype_without_transition(m_object_prototype);
  77. m_new_script_function_prototype_object_shape = vm.heap().allocate_without_global_object<Shape>(*this);
  78. m_new_script_function_prototype_object_shape->set_prototype_without_transition(m_object_prototype);
  79. m_new_script_function_prototype_object_shape->add_property_without_transition(vm.names.constructor, Attribute::Writable | Attribute::Configurable);
  80. static_cast<FunctionPrototype*>(m_function_prototype)->initialize(*this);
  81. static_cast<ObjectPrototype*>(m_object_prototype)->initialize(*this);
  82. Object::set_prototype(m_object_prototype);
  83. #define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName, ArrayType) \
  84. if (!m_##snake_name##_prototype) \
  85. m_##snake_name##_prototype = heap().allocate<PrototypeName>(*this, *this);
  86. JS_ENUMERATE_BUILTIN_TYPES
  87. #undef __JS_ENUMERATE
  88. #define __JS_ENUMERATE(ClassName, snake_name) \
  89. if (!m_##snake_name##_prototype) \
  90. m_##snake_name##_prototype = heap().allocate<ClassName##Prototype>(*this, *this);
  91. JS_ENUMERATE_ITERATOR_PROTOTYPES
  92. #undef __JS_ENUMERATE
  93. u8 attr = Attribute::Writable | Attribute::Configurable;
  94. define_native_function(vm.names.gc, gc, 0, attr);
  95. define_native_function(vm.names.isNaN, is_nan, 1, attr);
  96. define_native_function(vm.names.isFinite, is_finite, 1, attr);
  97. define_native_function(vm.names.parseFloat, parse_float, 1, attr);
  98. define_native_function(vm.names.parseInt, parse_int, 2, attr);
  99. define_native_function(vm.names.eval, eval, 1, attr);
  100. define_native_function(vm.names.encodeURI, encode_uri, 1, attr);
  101. define_native_function(vm.names.decodeURI, decode_uri, 1, attr);
  102. define_native_function(vm.names.encodeURIComponent, encode_uri_component, 1, attr);
  103. define_native_function(vm.names.decodeURIComponent, decode_uri_component, 1, attr);
  104. define_native_function(vm.names.escape, escape, 1, attr);
  105. define_native_function(vm.names.unescape, unescape, 1, attr);
  106. define_property(vm.names.NaN, js_nan(), 0);
  107. define_property(vm.names.Infinity, js_infinity(), 0);
  108. define_property(vm.names.undefined, js_undefined(), 0);
  109. define_property(vm.names.globalThis, this, attr);
  110. define_property(vm.names.console, heap().allocate<ConsoleObject>(*this, *this), attr);
  111. define_property(vm.names.Math, heap().allocate<MathObject>(*this, *this), attr);
  112. define_property(vm.names.JSON, heap().allocate<JSONObject>(*this, *this), attr);
  113. define_property(vm.names.Reflect, heap().allocate<ReflectObject>(*this, *this), attr);
  114. add_constructor(vm.names.Array, m_array_constructor, m_array_prototype);
  115. add_constructor(vm.names.ArrayBuffer, m_array_buffer_constructor, m_array_buffer_prototype);
  116. add_constructor(vm.names.BigInt, m_bigint_constructor, m_bigint_prototype);
  117. add_constructor(vm.names.Boolean, m_boolean_constructor, m_boolean_prototype);
  118. add_constructor(vm.names.Date, m_date_constructor, m_date_prototype);
  119. add_constructor(vm.names.Error, m_error_constructor, m_error_prototype);
  120. add_constructor(vm.names.Function, m_function_constructor, m_function_prototype);
  121. add_constructor(vm.names.Number, m_number_constructor, m_number_prototype);
  122. add_constructor(vm.names.Object, m_object_constructor, m_object_prototype);
  123. add_constructor(vm.names.Promise, m_promise_constructor, m_promise_prototype);
  124. add_constructor(vm.names.Proxy, m_proxy_constructor, nullptr);
  125. add_constructor(vm.names.RegExp, m_regexp_constructor, m_regexp_prototype);
  126. add_constructor(vm.names.Set, m_set_constructor, m_set_prototype);
  127. add_constructor(vm.names.String, m_string_constructor, m_string_prototype);
  128. add_constructor(vm.names.Symbol, m_symbol_constructor, m_symbol_prototype);
  129. initialize_constructor(vm.names.TypedArray, m_typed_array_constructor, m_typed_array_prototype);
  130. #define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName, ArrayType) \
  131. add_constructor(vm.names.ClassName, m_##snake_name##_constructor, m_##snake_name##_prototype);
  132. JS_ENUMERATE_ERROR_SUBCLASSES
  133. JS_ENUMERATE_TYPED_ARRAYS
  134. #undef __JS_ENUMERATE
  135. }
  136. GlobalObject::~GlobalObject()
  137. {
  138. }
  139. void GlobalObject::visit_edges(Visitor& visitor)
  140. {
  141. Base::visit_edges(visitor);
  142. visitor.visit(m_empty_object_shape);
  143. visitor.visit(m_new_object_shape);
  144. visitor.visit(m_new_script_function_prototype_object_shape);
  145. visitor.visit(m_proxy_constructor);
  146. #define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName, ArrayType) \
  147. visitor.visit(m_##snake_name##_constructor); \
  148. visitor.visit(m_##snake_name##_prototype);
  149. JS_ENUMERATE_ERROR_SUBCLASSES
  150. JS_ENUMERATE_BUILTIN_TYPES
  151. #undef __JS_ENUMERATE
  152. #define __JS_ENUMERATE(ClassName, snake_name) \
  153. visitor.visit(m_##snake_name##_prototype);
  154. JS_ENUMERATE_ITERATOR_PROTOTYPES
  155. #undef __JS_ENUMERATE
  156. }
  157. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::gc)
  158. {
  159. dbgln("Forced garbage collection requested!");
  160. vm.heap().collect_garbage();
  161. return js_undefined();
  162. }
  163. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::is_nan)
  164. {
  165. auto number = vm.argument(0).to_number(global_object);
  166. if (vm.exception())
  167. return {};
  168. return Value(number.is_nan());
  169. }
  170. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::is_finite)
  171. {
  172. auto number = vm.argument(0).to_number(global_object);
  173. if (vm.exception())
  174. return {};
  175. return Value(number.is_finite_number());
  176. }
  177. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::parse_float)
  178. {
  179. if (vm.argument(0).is_number())
  180. return vm.argument(0);
  181. auto input_string = vm.argument(0).to_string(global_object);
  182. if (vm.exception())
  183. return {};
  184. auto trimmed_string = input_string.trim_whitespace(TrimMode::Left);
  185. for (size_t length = trimmed_string.length(); length > 0; --length) {
  186. // This can't throw, so no exception check is fine.
  187. auto number = Value(js_string(vm, trimmed_string.substring(0, length))).to_number(global_object);
  188. if (!number.is_nan())
  189. return number;
  190. }
  191. return js_nan();
  192. }
  193. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::parse_int)
  194. {
  195. // 18.2.5 parseInt ( string, radix )
  196. auto input_string = vm.argument(0).to_string(global_object);
  197. if (vm.exception())
  198. return {};
  199. // FIXME: There's a bunch of unnecessary string copying here.
  200. double sign = 1;
  201. auto s = input_string.trim_whitespace(TrimMode::Left);
  202. if (!s.is_empty() && s[0] == '-')
  203. sign = -1;
  204. if (!s.is_empty() && (s[0] == '+' || s[0] == '-'))
  205. s = s.substring(1, s.length() - 1);
  206. auto radix = vm.argument(1).to_i32(global_object);
  207. if (vm.exception())
  208. return {};
  209. bool strip_prefix = true;
  210. if (radix != 0) {
  211. if (radix < 2 || radix > 36)
  212. return js_nan();
  213. if (radix != 16)
  214. strip_prefix = false;
  215. } else {
  216. radix = 10;
  217. }
  218. if (strip_prefix) {
  219. if (s.length() >= 2 && s[0] == '0' && (s[1] == 'x' || s[1] == 'X')) {
  220. s = s.substring(2, s.length() - 2);
  221. radix = 16;
  222. }
  223. }
  224. auto parse_digit = [&](u32 code_point, i32 radix) -> Optional<i32> {
  225. if (!is_ascii_alphanumeric(code_point) || radix <= 0)
  226. return {};
  227. auto digit = parse_ascii_base36_digit(code_point);
  228. if (digit >= (u32)radix)
  229. return {};
  230. return digit;
  231. };
  232. bool had_digits = false;
  233. double number = 0;
  234. for (auto code_point : Utf8View(s)) {
  235. auto digit = parse_digit(code_point, radix);
  236. if (!digit.has_value())
  237. break;
  238. had_digits = true;
  239. number *= radix;
  240. number += digit.value();
  241. }
  242. if (!had_digits)
  243. return js_nan();
  244. return Value(sign * number);
  245. }
  246. Optional<Variable> GlobalObject::get_from_scope(const FlyString& name) const
  247. {
  248. auto value = get(name);
  249. if (value.is_empty())
  250. return {};
  251. return Variable { value, DeclarationKind::Var };
  252. }
  253. void GlobalObject::put_to_scope(const FlyString& name, Variable variable)
  254. {
  255. put(name, variable.value);
  256. }
  257. bool GlobalObject::delete_from_scope(FlyString const& name)
  258. {
  259. return delete_property(name);
  260. }
  261. bool GlobalObject::has_this_binding() const
  262. {
  263. return true;
  264. }
  265. Value GlobalObject::get_this_binding(GlobalObject&) const
  266. {
  267. return Value(this);
  268. }
  269. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::eval)
  270. {
  271. if (!vm.argument(0).is_string())
  272. return vm.argument(0);
  273. auto& code_string = vm.argument(0).as_string();
  274. JS::Parser parser { JS::Lexer { code_string.string() } };
  275. auto program = parser.parse_program();
  276. if (parser.has_errors()) {
  277. auto& error = parser.errors()[0];
  278. vm.throw_exception<SyntaxError>(global_object, error.to_string());
  279. return {};
  280. }
  281. auto& caller_frame = vm.call_stack().at(vm.call_stack().size() - 2);
  282. TemporaryChange scope_change(vm.call_frame().scope, caller_frame->scope);
  283. auto& interpreter = vm.interpreter();
  284. return interpreter.execute_statement(global_object, program).value_or(js_undefined());
  285. }
  286. // 19.2.6.1.1 Encode ( string, unescapedSet )
  287. static String encode([[maybe_unused]] JS::GlobalObject& global_object, const String& string, StringView unescaped_set)
  288. {
  289. StringBuilder encoded_builder;
  290. for (unsigned char code_unit : string) {
  291. if (unescaped_set.contains(code_unit)) {
  292. encoded_builder.append(code_unit);
  293. continue;
  294. }
  295. // FIXME: check for unpaired surrogates and throw URIError
  296. encoded_builder.appendff("%{:02X}", code_unit);
  297. }
  298. return encoded_builder.build();
  299. }
  300. // 19.2.6.1.2 Decode ( string, reservedSet )
  301. static String decode(JS::GlobalObject& global_object, const String& string, StringView reserved_set)
  302. {
  303. StringBuilder decoded_builder;
  304. auto expected_continuation_bytes = 0;
  305. for (size_t k = 0; k < string.length(); k++) {
  306. auto code_unit = string[k];
  307. if (code_unit != '%') {
  308. if (expected_continuation_bytes > 0) {
  309. global_object.vm().throw_exception<URIError>(global_object, ErrorType::URIMalformed);
  310. return {};
  311. }
  312. decoded_builder.append(code_unit);
  313. continue;
  314. }
  315. if (k + 2 >= string.length()) {
  316. global_object.vm().throw_exception<URIError>(global_object, ErrorType::URIMalformed);
  317. return {};
  318. }
  319. auto first_digit = decode_hex_digit(string[k + 1]);
  320. if (first_digit >= 16) {
  321. global_object.vm().throw_exception<URIError>(global_object, ErrorType::URIMalformed);
  322. return {};
  323. }
  324. auto second_digit = decode_hex_digit(string[k + 2]);
  325. if (second_digit >= 16) {
  326. global_object.vm().throw_exception<URIError>(global_object, ErrorType::URIMalformed);
  327. return {};
  328. }
  329. char decoded_code_unit = (first_digit << 4) | second_digit;
  330. k += 2;
  331. if (expected_continuation_bytes > 0) {
  332. decoded_builder.append(decoded_code_unit);
  333. expected_continuation_bytes--;
  334. continue;
  335. }
  336. if ((decoded_code_unit & 0x80) == 0) {
  337. if (reserved_set.contains(decoded_code_unit))
  338. decoded_builder.append(string.substring_view(k - 2, 3));
  339. else
  340. decoded_builder.append(decoded_code_unit);
  341. continue;
  342. }
  343. auto leading_ones = count_trailing_zeroes_32_safe(~decoded_code_unit) - 24;
  344. if (leading_ones == 1 || leading_ones > 4) {
  345. global_object.vm().throw_exception<URIError>(global_object, ErrorType::URIMalformed);
  346. return {};
  347. }
  348. decoded_builder.append(decoded_code_unit);
  349. expected_continuation_bytes = leading_ones - 1;
  350. }
  351. return decoded_builder.build();
  352. }
  353. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::encode_uri)
  354. {
  355. auto uri_string = vm.argument(0).to_string(global_object);
  356. if (vm.exception())
  357. return {};
  358. auto encoded = encode(global_object, uri_string, ";/?:@&=+$,abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.!~*'()#"sv);
  359. if (vm.exception())
  360. return {};
  361. return js_string(vm, move(encoded));
  362. }
  363. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::decode_uri)
  364. {
  365. auto uri_string = vm.argument(0).to_string(global_object);
  366. if (vm.exception())
  367. return {};
  368. auto decoded = decode(global_object, uri_string, ";/?:@&=+$,#"sv);
  369. if (vm.exception())
  370. return {};
  371. return js_string(vm, move(decoded));
  372. }
  373. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::encode_uri_component)
  374. {
  375. auto uri_string = vm.argument(0).to_string(global_object);
  376. if (vm.exception())
  377. return {};
  378. auto encoded = encode(global_object, uri_string, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.!~*'()"sv);
  379. if (vm.exception())
  380. return {};
  381. return js_string(vm, move(encoded));
  382. }
  383. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::decode_uri_component)
  384. {
  385. auto uri_string = vm.argument(0).to_string(global_object);
  386. if (vm.exception())
  387. return {};
  388. auto decoded = decode(global_object, uri_string, ""sv);
  389. if (vm.exception())
  390. return {};
  391. return js_string(vm, move(decoded));
  392. }
  393. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::escape)
  394. {
  395. auto string = vm.argument(0).to_string(global_object);
  396. if (vm.exception())
  397. return {};
  398. StringBuilder escaped;
  399. for (auto code_point : Utf8View(string)) {
  400. if (code_point < 256) {
  401. if ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@*_+-./"sv.contains(code_point))
  402. escaped.append(code_point);
  403. else
  404. escaped.appendff("%{:02X}", code_point);
  405. continue;
  406. }
  407. escaped.appendff("%u{:04X}", code_point); // FIXME: Handle utf-16 surrogate pairs
  408. }
  409. return js_string(vm, escaped.build());
  410. }
  411. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::unescape)
  412. {
  413. auto string = vm.argument(0).to_string(global_object);
  414. if (vm.exception())
  415. return {};
  416. ssize_t length = string.length();
  417. StringBuilder unescaped(length);
  418. for (auto k = 0; k < length; ++k) {
  419. u32 code_point = string[k];
  420. if (code_point == '%') {
  421. if (k <= length - 6 && string[k + 1] == 'u' && is_ascii_hex_digit(string[k + 2]) && is_ascii_hex_digit(string[k + 3]) && is_ascii_hex_digit(string[k + 4]) && is_ascii_hex_digit(string[k + 5])) {
  422. code_point = (parse_ascii_hex_digit(string[k + 2]) << 12) | (parse_ascii_hex_digit(string[k + 3]) << 8) | (parse_ascii_hex_digit(string[k + 4]) << 4) | parse_ascii_hex_digit(string[k + 5]);
  423. k += 5;
  424. } else if (k <= length - 3 && is_ascii_hex_digit(string[k + 1]) && is_ascii_hex_digit(string[k + 2])) {
  425. code_point = (parse_ascii_hex_digit(string[k + 1]) << 4) | parse_ascii_hex_digit(string[k + 2]);
  426. k += 2;
  427. }
  428. }
  429. unescaped.append_code_point(code_point);
  430. }
  431. return js_string(vm, unescaped.build());
  432. }
  433. }