ExecuteScript.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. /*
  2. * Copyright (c) 2022-2023, Linus Groh <linusg@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/JsonArray.h>
  7. #include <AK/JsonObject.h>
  8. #include <AK/JsonValue.h>
  9. #include <AK/NumericLimits.h>
  10. #include <AK/ScopeGuard.h>
  11. #include <AK/Time.h>
  12. #include <AK/Variant.h>
  13. #include <LibJS/Parser.h>
  14. #include <LibJS/Runtime/Array.h>
  15. #include <LibJS/Runtime/ECMAScriptFunctionObject.h>
  16. #include <LibJS/Runtime/GlobalEnvironment.h>
  17. #include <LibJS/Runtime/JSONObject.h>
  18. #include <LibJS/Runtime/Promise.h>
  19. #include <LibJS/Runtime/PromiseConstructor.h>
  20. #include <LibWeb/DOM/Document.h>
  21. #include <LibWeb/DOM/HTMLCollection.h>
  22. #include <LibWeb/DOM/NodeList.h>
  23. #include <LibWeb/FileAPI/FileList.h>
  24. #include <LibWeb/HTML/BrowsingContext.h>
  25. #include <LibWeb/HTML/HTMLOptionsCollection.h>
  26. #include <LibWeb/HTML/Scripting/Environments.h>
  27. #include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
  28. #include <LibWeb/HTML/Window.h>
  29. #include <LibWeb/Page/Page.h>
  30. #include <LibWeb/WebDriver/Contexts.h>
  31. #include <LibWeb/WebDriver/ExecuteScript.h>
  32. namespace Web::WebDriver {
  33. #define TRY_OR_JS_ERROR(expression) \
  34. ({ \
  35. auto&& _temporary_result = (expression); \
  36. if (_temporary_result.is_error()) [[unlikely]] \
  37. return ExecuteScriptResultType::JavaScriptError; \
  38. static_assert(!::AK::Detail::IsLvalueReference<decltype(_temporary_result.release_value())>, \
  39. "Do not return a reference from a fallible expression"); \
  40. _temporary_result.release_value(); \
  41. })
  42. static ErrorOr<JsonValue, ExecuteScriptResultType> internal_json_clone_algorithm(JS::Realm&, JS::Value, HashTable<JS::Object*>& seen);
  43. static ErrorOr<JsonValue, ExecuteScriptResultType> clone_an_object(JS::Realm&, JS::Object&, HashTable<JS::Object*>& seen, auto const& clone_algorithm);
  44. // https://w3c.github.io/webdriver/#dfn-collection
  45. static bool is_collection(JS::Object const& value)
  46. {
  47. // A collection is an Object that implements the Iterable interface, and whose:
  48. return (
  49. // - initial value of the toString own property is "Arguments"
  50. value.has_parameter_map()
  51. // - instance of Array
  52. || is<JS::Array>(value)
  53. // - instance of FileList
  54. || is<FileAPI::FileList>(value)
  55. // - instance of HTMLAllCollection
  56. || false // FIXME
  57. // - instance of HTMLCollection
  58. || is<DOM::HTMLCollection>(value)
  59. // - instance of HTMLFormControlsCollection
  60. || false // FIXME
  61. // - instance of HTMLOptionsCollection
  62. || is<HTML::HTMLOptionsCollection>(value)
  63. // - instance of NodeList
  64. || is<DOM::NodeList>(value));
  65. }
  66. // https://w3c.github.io/webdriver/#dfn-json-clone
  67. static ErrorOr<JsonValue, ExecuteScriptResultType> json_clone(JS::Realm& realm, JS::Value value)
  68. {
  69. // To perform a JSON clone return the result of calling the internal JSON clone algorithm with arguments value and an empty List.
  70. auto seen = HashTable<JS::Object*> {};
  71. return internal_json_clone_algorithm(realm, value, seen);
  72. }
  73. // https://w3c.github.io/webdriver/#dfn-internal-json-clone-algorithm
  74. static ErrorOr<JsonValue, ExecuteScriptResultType> internal_json_clone_algorithm(JS::Realm& realm, JS::Value value, HashTable<JS::Object*>& seen)
  75. {
  76. auto& vm = realm.vm();
  77. // When required to run the internal JSON clone algorithm with arguments value and seen, a remote end must return the value of the first matching statement, matching on value:
  78. // -> undefined
  79. // -> null
  80. if (value.is_nullish()) {
  81. // Success with data null.
  82. return JsonValue {};
  83. }
  84. // -> type Boolean
  85. // -> type Number
  86. // -> type String
  87. // Success with data value.
  88. if (value.is_boolean())
  89. return JsonValue { value.as_bool() };
  90. if (value.is_number())
  91. return JsonValue { value.as_double() };
  92. if (value.is_string())
  93. return JsonValue { value.as_string().deprecated_string() };
  94. // NOTE: BigInt and Symbol not mentioned anywhere in the WebDriver spec, as it references ES5.
  95. // It assumes that all primitives are handled above, and the value is an object for the remaining steps.
  96. if (value.is_bigint() || value.is_symbol())
  97. return ExecuteScriptResultType::JavaScriptError;
  98. // FIXME: -> a collection
  99. // FIXME: -> instance of element
  100. // FIXME: -> instance of shadow root
  101. // -> a WindowProxy object
  102. if (is<HTML::WindowProxy>(value.as_object())) {
  103. auto const& window_proxy = static_cast<HTML::WindowProxy&>(value.as_object());
  104. // If the associated browsing context of the WindowProxy object in value has been discarded, return error with
  105. // error code stale element reference.
  106. if (window_proxy.associated_browsing_context()->has_been_discarded())
  107. return ExecuteScriptResultType::BrowsingContextDiscarded;
  108. // Otherwise return success with data set to WindowProxy reference object for value.
  109. return window_proxy_reference_object(window_proxy);
  110. }
  111. // -> has an own property named "toJSON" that is a Function
  112. auto to_json = value.as_object().get_without_side_effects(vm.names.toJSON);
  113. if (to_json.is_function()) {
  114. // Return success with the value returned by Function.[[Call]](toJSON) with value as the this value.
  115. auto to_json_result = TRY_OR_JS_ERROR(to_json.as_function().internal_call(value, JS::MarkedVector<JS::Value> { vm.heap() }));
  116. if (!to_json_result.is_string())
  117. return ExecuteScriptResultType::JavaScriptError;
  118. return to_json_result.as_string().deprecated_string();
  119. }
  120. // -> Otherwise
  121. // 1. If value is in seen, return error with error code javascript error.
  122. if (seen.contains(&value.as_object()))
  123. return ExecuteScriptResultType::JavaScriptError;
  124. // 2. Append value to seen.
  125. seen.set(&value.as_object());
  126. ScopeGuard remove_seen { [&] {
  127. // 4. Remove the last element of seen.
  128. seen.remove(&value.as_object());
  129. } };
  130. // 3. Let result be the value of running the clone an object algorithm with arguments value and seen, and the internal JSON clone algorithm as the clone algorithm.
  131. auto result = TRY(clone_an_object(realm, value.as_object(), seen, internal_json_clone_algorithm));
  132. // 5. Return result.
  133. return result;
  134. }
  135. // https://w3c.github.io/webdriver/#dfn-clone-an-object
  136. static ErrorOr<JsonValue, ExecuteScriptResultType> clone_an_object(JS::Realm& realm, JS::Object& value, HashTable<JS::Object*>& seen, auto const& clone_algorithm)
  137. {
  138. auto& vm = realm.vm();
  139. // 1. Let result be the value of the first matching statement, matching on value:
  140. auto get_result = [&]() -> ErrorOr<Variant<JsonArray, JsonObject>, ExecuteScriptResultType> {
  141. // -> a collection
  142. if (is_collection(value)) {
  143. // A new Array which length property is equal to the result of getting the property length of value.
  144. auto length_property = TRY_OR_JS_ERROR(value.internal_get_own_property(vm.names.length));
  145. if (!length_property->value.has_value())
  146. return ExecuteScriptResultType::JavaScriptError;
  147. auto length = TRY_OR_JS_ERROR(length_property->value->to_length(vm));
  148. if (length > NumericLimits<u32>::max())
  149. return ExecuteScriptResultType::JavaScriptError;
  150. auto array = JsonArray {};
  151. for (size_t i = 0; i < length; ++i)
  152. array.must_append(JsonValue {});
  153. return array;
  154. }
  155. // -> Otherwise
  156. else {
  157. // A new Object.
  158. return JsonObject {};
  159. }
  160. };
  161. auto result = TRY(get_result());
  162. // 2. For each enumerable own property in value, run the following substeps:
  163. for (auto& key : MUST(value.Object::internal_own_property_keys())) {
  164. // 1. Let name be the name of the property.
  165. auto name = MUST(JS::PropertyKey::from_value(vm, key));
  166. if (!value.storage_get(name)->attributes.is_enumerable())
  167. continue;
  168. // 2. Let source property value be the result of getting a property named name from value. If doing so causes script to be run and that script throws an error, return error with error code javascript error.
  169. auto source_property_value = TRY_OR_JS_ERROR(value.internal_get_own_property(name));
  170. if (!source_property_value.has_value() || !source_property_value->value.has_value())
  171. continue;
  172. // 3. Let cloned property result be the result of calling the clone algorithm with arguments source property value and seen.
  173. auto cloned_property_result = clone_algorithm(realm, *source_property_value->value, seen);
  174. // 4. If cloned property result is a success, set a property of result with name name and value equal to cloned property result’s data.
  175. if (!cloned_property_result.is_error()) {
  176. result.visit(
  177. [&](JsonArray& array) {
  178. // NOTE: If this was a JS array, only indexed properties would be serialized anyway.
  179. if (name.is_number())
  180. array.set(name.as_number(), cloned_property_result.value());
  181. },
  182. [&](JsonObject& object) {
  183. object.set(name.to_string(), cloned_property_result.value());
  184. });
  185. }
  186. // 5. Otherwise, return cloned property result.
  187. else {
  188. return cloned_property_result;
  189. }
  190. }
  191. return result.visit([&](auto const& value) -> JsonValue { return value; });
  192. }
  193. // https://w3c.github.io/webdriver/#dfn-execute-a-function-body
  194. static JS::ThrowCompletionOr<JS::Value> execute_a_function_body(Web::Page& page, DeprecatedString const& body, JS::MarkedVector<JS::Value> parameters)
  195. {
  196. // FIXME: If at any point during the algorithm a user prompt appears, immediately return Completion { [[Type]]: normal, [[Value]]: null, [[Target]]: empty }, but continue to run the other steps of this algorithm in parallel.
  197. // 1. Let window be the associated window of the current browsing context’s active document.
  198. // FIXME: This will need adjusting when WebDriver supports frames.
  199. auto& window = page.top_level_browsing_context().active_document()->window();
  200. // 2. Let environment settings be the environment settings object for window.
  201. auto& environment_settings = Web::HTML::relevant_settings_object(window);
  202. // 3. Let global scope be environment settings realm’s global environment.
  203. auto& global_scope = environment_settings.realm().global_environment();
  204. auto& realm = window.realm();
  205. bool contains_direct_call_to_eval = false;
  206. auto source_text = DeprecatedString::formatted("function() {{ {} }}", body);
  207. auto parser = JS::Parser { JS::Lexer { source_text } };
  208. auto function_expression = parser.parse_function_node<JS::FunctionExpression>();
  209. // 4. If body is not parsable as a FunctionBody or if parsing detects an early error, return Completion { [[Type]]: normal, [[Value]]: null, [[Target]]: empty }.
  210. if (parser.has_errors())
  211. return JS::js_null();
  212. // 5. If body begins with a directive prologue that contains a use strict directive then let strict be true, otherwise let strict be false.
  213. // NOTE: Handled in step 8 below.
  214. // 6. Prepare to run a script with environment settings.
  215. environment_settings.prepare_to_run_script();
  216. // 7. Prepare to run a callback with environment settings.
  217. environment_settings.prepare_to_run_callback();
  218. // 8. Let function be the result of calling FunctionCreate, with arguments:
  219. // kind
  220. // Normal.
  221. // list
  222. // An empty List.
  223. // body
  224. // The result of parsing body above.
  225. // global scope
  226. // The result of parsing global scope above.
  227. // strict
  228. // The result of parsing strict above.
  229. auto function = JS::ECMAScriptFunctionObject::create(realm, "", move(source_text), function_expression->body(), function_expression->parameters(), function_expression->function_length(), function_expression->local_variables_names(), &global_scope, nullptr, function_expression->kind(), function_expression->is_strict_mode(), function_expression->might_need_arguments_object(), contains_direct_call_to_eval);
  230. // 9. Let completion be Function.[[Call]](window, parameters) with function as the this value.
  231. // NOTE: This is not entirely clear, but I don't think they mean actually passing `function` as
  232. // the this value argument, but using it as the object [[Call]] is executed on.
  233. auto completion = function->internal_call(&window, move(parameters));
  234. // 10. Clean up after running a callback with environment settings.
  235. environment_settings.clean_up_after_running_callback();
  236. // 11. Clean up after running a script with environment settings.
  237. environment_settings.clean_up_after_running_script();
  238. // 12. Return completion.
  239. return completion;
  240. }
  241. ExecuteScriptResultSerialized execute_script(Web::Page& page, DeprecatedString const& body, JS::MarkedVector<JS::Value> arguments, Optional<u64> const& timeout)
  242. {
  243. // FIXME: Use timeout.
  244. (void)timeout;
  245. auto* window = page.top_level_browsing_context().active_window();
  246. auto& realm = window->realm();
  247. // 4. Let promise be a new Promise.
  248. // NOTE: For now we skip this and handle a throw completion manually instead of using 'promise-calling'.
  249. // FIXME: 5. Run the following substeps in parallel:
  250. auto result = [&] {
  251. // 1. Let scriptPromise be the result of promise-calling execute a function body, with arguments body and arguments.
  252. auto completion = execute_a_function_body(page, body, move(arguments));
  253. // 2. Upon fulfillment of scriptPromise with value v, resolve promise with value v.
  254. // 3. Upon rejection of scriptPromise with value r, reject promise with value r.
  255. auto result_type = completion.is_error()
  256. ? ExecuteScriptResultType::PromiseRejected
  257. : ExecuteScriptResultType::PromiseResolved;
  258. auto result_value = completion.is_error()
  259. ? *completion.throw_completion().value()
  260. : completion.value();
  261. return ExecuteScriptResult { result_type, result_value };
  262. }();
  263. // FIXME: 6. If promise is still pending and the session script timeout is reached, return error with error code script timeout.
  264. // 7. Upon fulfillment of promise with value v, let result be a JSON clone of v, and return success with data result.
  265. // 8. Upon rejection of promise with reason r, let result be a JSON clone of r, and return error with error code javascript error and data result.
  266. auto json_value_or_error = json_clone(realm, result.value);
  267. if (json_value_or_error.is_error()) {
  268. auto error_object = JsonObject {};
  269. error_object.set("name", "Error");
  270. error_object.set("message", "Could not clone result value");
  271. return { ExecuteScriptResultType::JavaScriptError, move(error_object) };
  272. }
  273. return { result.type, json_value_or_error.release_value() };
  274. }
  275. ExecuteScriptResultSerialized execute_async_script(Web::Page& page, DeprecatedString const& body, JS::MarkedVector<JS::Value> arguments, Optional<u64> const& timeout)
  276. {
  277. auto* document = page.top_level_browsing_context().active_document();
  278. auto* window = page.top_level_browsing_context().active_window();
  279. auto& realm = window->realm();
  280. auto& vm = window->vm();
  281. auto start = MonotonicTime::now();
  282. // AD-HOC: An execution context is required for Promise creation hooks.
  283. HTML::TemporaryExecutionContext execution_context { document->relevant_settings_object() };
  284. // 4. Let promise be a new Promise.
  285. auto promise_capability = WebIDL::create_promise(realm);
  286. JS::NonnullGCPtr promise { verify_cast<JS::Promise>(*promise_capability->promise()) };
  287. // FIXME: 5 Run the following substeps in parallel:
  288. [&] {
  289. // 1. Let resolvingFunctions be CreateResolvingFunctions(promise).
  290. auto resolving_functions = promise->create_resolving_functions();
  291. // 2. Append resolvingFunctions.[[Resolve]] to arguments.
  292. arguments.append(resolving_functions.resolve);
  293. // 3. Let result be the result of calling execute a function body, with arguments body and arguments.
  294. // FIXME: 'result' -> 'scriptResult' (spec issue)
  295. auto script_result = execute_a_function_body(page, body, move(arguments));
  296. // 4.If scriptResult.[[Type]] is not normal, then reject promise with value scriptResult.[[Value]], and abort these steps.
  297. // NOTE: Prior revisions of this specification did not recognize the return value of the provided script.
  298. // In order to preserve legacy behavior, the return value only influences the command if it is a
  299. // "thenable" object or if determining this produces an exception.
  300. if (script_result.is_throw_completion())
  301. return;
  302. // 5. If Type(scriptResult.[[Value]]) is not Object, then abort these steps.
  303. if (!script_result.value().is_object())
  304. return;
  305. // 6. Let then be Get(scriptResult.[[Value]], "then").
  306. auto then = script_result.value().as_object().get(vm.names.then);
  307. // 7. If then.[[Type]] is not normal, then reject promise with value then.[[Value]], and abort these steps.
  308. if (then.is_throw_completion())
  309. return;
  310. // 8. If IsCallable(then.[[Type]]) is false, then abort these steps.
  311. if (!then.value().is_function())
  312. return;
  313. // 9. Let scriptPromise be PromiseResolve(Promise, scriptResult.[[Value]]).
  314. auto script_promise_or_error = JS::promise_resolve(vm, realm.intrinsics().promise_constructor(), script_result.value());
  315. if (script_promise_or_error.is_throw_completion())
  316. return;
  317. auto& script_promise = static_cast<JS::Promise&>(*script_promise_or_error.value());
  318. vm.custom_data()->spin_event_loop_until([&] {
  319. if (script_promise.state() != JS::Promise::State::Pending)
  320. return true;
  321. if (timeout.has_value() && (MonotonicTime::now() - start) > Duration::from_seconds(static_cast<i64>(*timeout)))
  322. return true;
  323. return false;
  324. });
  325. // 10. Upon fulfillment of scriptPromise with value v, resolve promise with value v.
  326. if (script_promise.state() == JS::Promise::State::Fulfilled)
  327. WebIDL::resolve_promise(realm, promise_capability, script_promise.result());
  328. // 11. Upon rejection of scriptPromise with value r, reject promise with value r.
  329. if (script_promise.state() == JS::Promise::State::Rejected)
  330. WebIDL::reject_promise(realm, promise_capability, script_promise.result());
  331. }();
  332. // FIXME: 6. If promise is still pending and session script timeout milliseconds is reached, return error with error code script timeout.
  333. vm.custom_data()->spin_event_loop_until([&] {
  334. return promise->state() != JS::Promise::State::Pending;
  335. });
  336. auto json_value_or_error = json_clone(realm, promise->result());
  337. if (json_value_or_error.is_error()) {
  338. auto error_object = JsonObject {};
  339. error_object.set("name", "Error");
  340. error_object.set("message", "Could not clone result value");
  341. return { ExecuteScriptResultType::JavaScriptError, move(error_object) };
  342. }
  343. // 7. Upon fulfillment of promise with value v, let result be a JSON clone of v, and return success with data result.
  344. if (promise->state() == JS::Promise::State::Fulfilled) {
  345. return { ExecuteScriptResultType::PromiseResolved, json_value_or_error.release_value() };
  346. }
  347. // 8. Upon rejection of promise with reason r, let result be a JSON clone of r, and return error with error code javascript error and data result.
  348. if (promise->state() == JS::Promise::State::Rejected) {
  349. return { ExecuteScriptResultType::PromiseRejected, json_value_or_error.release_value() };
  350. }
  351. VERIFY_NOT_REACHED();
  352. }
  353. }