File: api_binding_js_util.cc

package info (click to toggle)
chromium 139.0.7258.127-2
  • links: PTS, VCS
  • area: main
  • in suites: forky
  • size: 6,122,156 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (347 lines) | stat: -rw-r--r-- 13,796 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
// Copyright 2016 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "extensions/renderer/bindings/api_binding_js_util.h"

#include <optional>

#include "base/strings/stringprintf.h"
#include "base/values.h"
#include "content/public/renderer/v8_value_converter.h"
#include "extensions/renderer/bindings/api_event_handler.h"
#include "extensions/renderer/bindings/api_request_handler.h"
#include "extensions/renderer/bindings/api_signature.h"
#include "extensions/renderer/bindings/api_type_reference_map.h"
#include "extensions/renderer/bindings/argument_spec.h"
#include "extensions/renderer/bindings/declarative_event.h"
#include "extensions/renderer/bindings/exception_handler.h"
#include "extensions/renderer/bindings/js_runner.h"
#include "gin/converter.h"
#include "gin/dictionary.h"
#include "gin/handle.h"
#include "gin/object_template_builder.h"

namespace extensions {

gin::WrapperInfo APIBindingJSUtil::kWrapperInfo = {gin::kEmbedderNativeGin};

APIBindingJSUtil::APIBindingJSUtil(APITypeReferenceMap* type_refs,
                                   APIRequestHandler* request_handler,
                                   APIEventHandler* event_handler,
                                   ExceptionHandler* exception_handler)
    : type_refs_(type_refs),
      request_handler_(request_handler),
      event_handler_(event_handler),
      exception_handler_(exception_handler) {}

APIBindingJSUtil::~APIBindingJSUtil() = default;

gin::ObjectTemplateBuilder APIBindingJSUtil::GetObjectTemplateBuilder(
    v8::Isolate* isolate) {
  return Wrappable<APIBindingJSUtil>::GetObjectTemplateBuilder(isolate)
      .SetMethod("sendRequest", &APIBindingJSUtil::SendRequest)
      .SetMethod("registerEventArgumentMassager",
                 &APIBindingJSUtil::RegisterEventArgumentMassager)
      .SetMethod("createCustomEvent", &APIBindingJSUtil::CreateCustomEvent)
      .SetMethod("createCustomDeclarativeEvent",
                 &APIBindingJSUtil::CreateCustomDeclarativeEvent)
      .SetMethod("invalidateEvent", &APIBindingJSUtil::InvalidateEvent)
      .SetMethod("setLastError", &APIBindingJSUtil::SetLastError)
      .SetMethod("clearLastError", &APIBindingJSUtil::ClearLastError)
      .SetMethod("hasLastError", &APIBindingJSUtil::HasLastError)
      .SetMethod("getLastErrorMessage", &APIBindingJSUtil::GetLastErrorMessage)
      .SetMethod("runCallbackWithLastError",
                 &APIBindingJSUtil::RunCallbackWithLastError)
      .SetMethod("handleException", &APIBindingJSUtil::HandleException)
      .SetMethod("setExceptionHandler", &APIBindingJSUtil::SetExceptionHandler)
      .SetMethod("validateType", &APIBindingJSUtil::ValidateType)
      .SetMethod("validateCustomSignature",
                 &APIBindingJSUtil::ValidateCustomSignature)
      .SetMethod("addCustomSignature", &APIBindingJSUtil::AddCustomSignature);
}

void APIBindingJSUtil::SendRequest(
    gin::Arguments* arguments,
    const std::string& name,
    const v8::LocalVector<v8::Value>& request_args,
    v8::Local<v8::Value> options) {
  v8::Isolate* isolate = arguments->isolate();
  v8::HandleScope handle_scope(isolate);
  v8::Local<v8::Context> context = arguments->GetHolderCreationContext();

  const APISignature* signature = type_refs_->GetAPIMethodSignature(name);
  DCHECK(signature);

  v8::Local<v8::Function> custom_callback;
  if (!options.IsEmpty() && !options->IsUndefined() && !options->IsNull()) {
    if (!options->IsObject()) {
      NOTREACHED();
    }
    v8::Local<v8::Object> options_obj = options.As<v8::Object>();
    if (!options_obj->GetPrototypeV2()->IsNull()) {
      NOTREACHED();
    }
    gin::Dictionary options_dict(isolate, options_obj);
    // NOTE: We don't throw any errors here if customCallback is of an invalid
    // type. We could, if we wanted to be a bit more verbose.
    options_dict.Get("customCallback", &custom_callback);
  }

  // Some APIs (like fileSystem and contextMenus) don't provide arguments that
  // match the expected schema. For now, we need to ignore these and trust the
  // JS gives us something we expect.
  // TODO(devlin): We should ideally always be able to validate these, meaning
  // that we either need to make the APIs give us the expected signature, or
  // need to have a way of indicating an internal signature.
  // TODO(tjudkins): This call into ConvertArgumentsIgnoringSchema can hit a
  // CHECK or DCHECK if the caller leaves off an optional callback. Since all
  // the callers are only internally defined JS hooks we know none of them do at
  // the moment, but this should be fixed and will need to be resolved for
  // supporting promises through this codepath.
  APISignature::JSONParseResult parse_result =
      signature->ConvertArgumentsIgnoringSchema(context, request_args);
  CHECK(parse_result.succeeded());
  // We don't currently support promise based requests through SendRequest here.
  // See the above comment for more details.
  DCHECK_NE(binding::AsyncResponseType::kPromise, parse_result.async_type);

  request_handler_->StartRequest(
      context, name, std::move(*parse_result.arguments_list),
      parse_result.async_type, parse_result.callback, custom_callback,
      binding::ResultModifierFunction());
}

void APIBindingJSUtil::RegisterEventArgumentMassager(
    gin::Arguments* arguments,
    const std::string& event_name,
    v8::Local<v8::Function> massager) {
  v8::Isolate* isolate = arguments->isolate();
  v8::HandleScope handle_scope(isolate);
  v8::Local<v8::Context> context = arguments->GetHolderCreationContext();

  event_handler_->RegisterArgumentMassager(context, event_name, massager);
}

void APIBindingJSUtil::CreateCustomEvent(gin::Arguments* arguments,
                                         v8::Local<v8::Value> v8_event_name,
                                         bool supports_filters,
                                         bool supports_lazy_listeners) {
  v8::Isolate* isolate = arguments->isolate();
  v8::HandleScope handle_scope(isolate);
  v8::Local<v8::Context> context = arguments->GetHolderCreationContext();

  std::string event_name;
  if (!v8_event_name->IsUndefined()) {
    if (!v8_event_name->IsString()) {
      NOTREACHED();
    }
    event_name = gin::V8ToString(isolate, v8_event_name);
  }

  DCHECK(!supports_filters || !event_name.empty())
      << "Events that support filters cannot be anonymous.";
  DCHECK(!supports_lazy_listeners || !event_name.empty())
      << "Events that support lazy listeners cannot be anonymous.";

  v8::Local<v8::Value> event;
  if (event_name.empty()) {
    event = event_handler_->CreateAnonymousEventInstance(context);
  } else {
    bool notify_on_change = true;
    event = event_handler_->CreateEventInstance(
        event_name, supports_filters, supports_lazy_listeners,
        binding::kNoListenerMax, notify_on_change, context);
  }

  arguments->Return(event);
}

void APIBindingJSUtil::CreateCustomDeclarativeEvent(
    gin::Arguments* arguments,
    const std::string& event_name,
    const std::vector<std::string>& actions_list,
    const std::vector<std::string>& conditions_list,
    int webview_instance_id) {
  v8::Isolate* isolate = arguments->isolate();
  v8::HandleScope handle_scope(isolate);

  gin::Handle<DeclarativeEvent> event = gin::CreateHandle(
      isolate,
      new DeclarativeEvent(event_name, type_refs_, request_handler_,
                           actions_list, conditions_list, webview_instance_id));

  arguments->Return(event.ToV8());
}

void APIBindingJSUtil::InvalidateEvent(gin::Arguments* arguments,
                                       v8::Local<v8::Object> event) {
  v8::Isolate* isolate = arguments->isolate();
  v8::HandleScope handle_scope(isolate);
  event_handler_->InvalidateCustomEvent(arguments->GetHolderCreationContext(),
                                        event);
}

void APIBindingJSUtil::SetLastError(gin::Arguments* arguments,
                                    const std::string& error) {
  v8::Isolate* isolate = arguments->isolate();
  v8::HandleScope handle_scope(isolate);
  request_handler_->last_error()->SetError(
      arguments->GetHolderCreationContext(), error);
}

void APIBindingJSUtil::ClearLastError(gin::Arguments* arguments) {
  v8::Isolate* isolate = arguments->isolate();
  v8::HandleScope handle_scope(isolate);
  bool report_if_unchecked = false;
  request_handler_->last_error()->ClearError(
      arguments->GetHolderCreationContext(), report_if_unchecked);
}

void APIBindingJSUtil::HasLastError(gin::Arguments* arguments) {
  v8::Isolate* isolate = arguments->isolate();
  v8::HandleScope handle_scope(isolate);

  bool has_last_error = request_handler_->last_error()->HasError(
      arguments->GetHolderCreationContext());
  arguments->Return(has_last_error);
}

void APIBindingJSUtil::GetLastErrorMessage(gin::Arguments* arguments) {
  v8::Isolate* isolate = arguments->isolate();
  v8::HandleScope handle_scope(isolate);

  std::optional<std::string> last_error_message =
      request_handler_->last_error()->GetErrorMessage(
          arguments->GetHolderCreationContext());
  if (last_error_message) {
    arguments->Return(*last_error_message);
  } else {
    // TODO(tjudkins): It would be nicer to return a v8::Undefined here, but the
    // gin converter doesn't support it at the moment.
    arguments->Return(v8::Local<v8::Value>());
  }
}

void APIBindingJSUtil::RunCallbackWithLastError(
    gin::Arguments* arguments,
    const std::string& error,
    v8::Local<v8::Function> callback) {
  v8::Isolate* isolate = arguments->isolate();
  v8::HandleScope handle_scope(isolate);
  v8::Local<v8::Context> context = arguments->GetHolderCreationContext();

  request_handler_->last_error()->SetError(context, error);
  JSRunner::Get(context)->RunJSFunction(callback, context, {});

  bool report_if_unchecked = true;
  request_handler_->last_error()->ClearError(context, report_if_unchecked);
}

void APIBindingJSUtil::HandleException(gin::Arguments* arguments,
                                       const std::string& message,
                                       v8::Local<v8::Value> exception) {
  v8::Isolate* isolate = arguments->isolate();
  v8::HandleScope handle_scope(isolate);
  v8::Local<v8::Context> context = arguments->GetHolderCreationContext();

  std::string full_message;
  if (!exception->IsUndefined() && !exception->IsNull()) {
    v8::TryCatch try_catch(isolate);
    std::string exception_string;
    v8::Local<v8::String> v8_exception_string;
    if (exception->ToString(context).ToLocal(&v8_exception_string))
      exception_string = gin::V8ToString(isolate, v8_exception_string);
    else
      exception_string = "(failed to get error message)";
    full_message =
        base::StringPrintf("%s: %s", message.c_str(), exception_string.c_str());
  } else {
    full_message = message;
  }

  exception_handler_->HandleException(context, full_message, exception);
}

void APIBindingJSUtil::SetExceptionHandler(gin::Arguments* arguments,
                                           v8::Local<v8::Function> handler) {
  exception_handler_->SetHandlerForContext(
      arguments->GetHolderCreationContext(), handler);
}

void APIBindingJSUtil::ValidateType(gin::Arguments* arguments,
                                    const std::string& type_name,
                                    v8::Local<v8::Value> value) {
  v8::Isolate* isolate = arguments->isolate();
  v8::HandleScope handle_scope(isolate);
  v8::Local<v8::Context> context = arguments->GetHolderCreationContext();

  const ArgumentSpec* spec = type_refs_->GetSpec(type_name);
  if (!spec) {
    // We shouldn't be asked to validate unknown specs, but since this comes
    // from JS, assume nothing.
    NOTREACHED();
  }

  std::string error;
  if (!spec->ParseArgument(context, value, *type_refs_, nullptr, nullptr,
                           &error)) {
    arguments->ThrowTypeError(error);
  }
}

void APIBindingJSUtil::AddCustomSignature(
    gin::Arguments* arguments,
    const std::string& custom_signature_name,
    v8::Local<v8::Value> signature) {
  v8::Local<v8::Context> context = arguments->GetHolderCreationContext();

  // JS bindings run per-context, so it's expected that they will call this
  // multiple times in the lifetime of the renderer process. Only handle the
  // first call.
  if (type_refs_->GetCustomSignature(custom_signature_name))
    return;

  if (!signature->IsArray()) {
    NOTREACHED();
  }

  std::unique_ptr<base::Value> base_signature =
      content::V8ValueConverter::Create()->FromV8Value(signature, context);
  if (!base_signature->is_list()) {
    NOTREACHED();
  }

  type_refs_->AddCustomSignature(
      custom_signature_name,
      APISignature::CreateFromValues(*base_signature, nullptr /*returns_async*/,
                                     nullptr /*access_checker*/));
}

void APIBindingJSUtil::ValidateCustomSignature(
    gin::Arguments* arguments,
    const std::string& custom_signature_name,
    v8::Local<v8::Value> arguments_to_validate) {
  v8::Isolate* isolate = arguments->isolate();
  v8::HandleScope handle_scope(isolate);
  v8::Local<v8::Context> context = arguments->GetHolderCreationContext();

  const APISignature* signature =
      type_refs_->GetCustomSignature(custom_signature_name);
  if (!signature) {
    NOTREACHED();
  }

  v8::LocalVector<v8::Value> vector_arguments(isolate);
  if (!gin::ConvertFromV8(isolate, arguments_to_validate, &vector_arguments)) {
    NOTREACHED();
  }

  APISignature::V8ParseResult parse_result =
      signature->ParseArgumentsToV8(context, vector_arguments, *type_refs_);
  if (!parse_result.succeeded()) {
    arguments->ThrowTypeError(std::move(*parse_result.error));
  }
}

}  // namespace extensions