GlobalObject.cpp 17 KB

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