ExecuteScript.cpp 20 KB

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