ExecuteScript.cpp 21 KB

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