void InspectorAnimationAgent::resolveAnimation(
    ErrorString* errorString,
    const String& animationId,
    std::unique_ptr<v8_inspector::protocol::Runtime::API::RemoteObject>*
        result) {
  blink::Animation* animation = assertAnimation(errorString, animationId);
  if (!animation)
    return;
  if (m_idToAnimationClone.get(animationId))
    animation = m_idToAnimationClone.get(animationId);
  const Element* element = toKeyframeEffect(animation->effect())->target();
  Document* document = element->ownerDocument();
  LocalFrame* frame = document ? document->frame() : nullptr;
  ScriptState* scriptState = frame ? ScriptState::forMainWorld(frame) : nullptr;
  if (!scriptState) {
    *errorString = "Element not associated with a document.";
    return;
  }

  ScriptState::Scope scope(scriptState);
  static const char kAnimationObjectGroup[] = "animation";
  m_v8Session->releaseObjectGroup(
      toV8InspectorStringView(kAnimationObjectGroup));
  *result = m_v8Session->wrapObject(
      scriptState->context(),
      toV8(animation, scriptState->context()->Global(), scriptState->isolate()),
      toV8InspectorStringView(kAnimationObjectGroup));
  if (!*result)
    *errorString = "Element not associated with a document.";
}
Example #2
0
void WebDevToolsFrontendImpl::didClearWindowObject(WebLocalFrameImpl* frame)
{
    if (m_webFrame == frame) {
        v8::Isolate* isolate = v8::Isolate::GetCurrent();
        ScriptState* scriptState = ScriptState::forMainWorld(m_webFrame->frame());
        ScriptState::Scope scope(scriptState);

        if (m_devtoolsHost)
            m_devtoolsHost->disconnectClient();
        m_devtoolsHost = DevToolsHost::create(this, m_webFrame->frame());
        v8::Local<v8::Object> global = scriptState->context()->Global();
        v8::Local<v8::Value> devtoolsHostObj = toV8(m_devtoolsHost.get(), global, scriptState->isolate());
        ASSERT(!devtoolsHostObj.IsEmpty());
        global->Set(v8AtomicString(isolate, "DevToolsHost"), devtoolsHostObj);
    }

    if (m_injectedScriptForOrigin.isEmpty())
        return;

    String origin = frame->securityOrigin().toString();
    String script = m_injectedScriptForOrigin.get(origin);
    if (script.isEmpty())
        return;
    static int s_lastScriptId = 0;
    StringBuilder scriptWithId;
    scriptWithId.append(script);
    scriptWithId.append('(');
    scriptWithId.appendNumber(++s_lastScriptId);
    scriptWithId.append(')');
    frame->frame()->script().executeScriptInMainWorld(scriptWithId.toString());
}
void InspectorAnimationAgent::resolveAnimation(ErrorString* errorString, const String& animationId, RefPtr<TypeBuilder::Runtime::RemoteObject>& result)
{
    Animation* animation = assertAnimation(errorString, animationId);
    if (!animation)
        return;
    if (m_idToAnimationClone.get(animationId))
        animation = m_idToAnimationClone.get(animationId);
    const Element* element = toKeyframeEffect(animation->effect())->target();
    Document* document = element->ownerDocument();
    LocalFrame* frame = document ? document->frame() : nullptr;
    if (!frame) {
        *errorString = "Element not associated with a document.";
        return;
    }

    ScriptState* scriptState = ScriptState::forMainWorld(frame);
    InjectedScript injectedScript = m_injectedScriptManager->injectedScriptFor(scriptState);
    if (injectedScript.isEmpty())
        return;

    ScriptState::Scope scope(scriptState);
    v8::Isolate* isolate = scriptState->isolate();
    ScriptValue scriptValue = ScriptValue(scriptState, toV8(animation, scriptState->context()->Global(), isolate));
    injectedScript.releaseObjectGroup("animation");
    result = injectedScript.wrapObject(scriptValue, "animation");
}
PassRefPtr<JSONValue> toJSONValue(const ScriptValue& value)
{
    ScriptState* scriptState = value.scriptState();
    ASSERT(scriptState->contextIsValid());
    ScriptState::Scope scope(scriptState);
    NonThrowableExceptionState exceptionState;
    return ScriptValue::to<JSONValuePtr>(scriptState->isolate(), value, exceptionState);
}
void injectInternalsObject(v8::Local<v8::Context> context)
{
    ScriptState* scriptState = ScriptState::from(context);
    ScriptState::Scope scope(scriptState);
    v8::Handle<v8::Object> global = scriptState->context()->Global();
    ExecutionContext* executionContext = scriptState->executionContext();
    if (executionContext->isDocument())
        global->Set(v8::String::NewFromUtf8(scriptState->isolate(), Internals::internalsId), toV8(Internals::create(toDocument(executionContext)), global, scriptState->isolate()));
}
void CryptoResultImpl::completeWithJson(const char* utf8Data, unsigned length)
{
    if (!m_resolver)
        return;

    ScriptState* scriptState = m_resolver->getScriptState();
    ScriptState::Scope scope(scriptState);

    v8::Local<v8::String> jsonString = v8AtomicString(scriptState->isolate(), utf8Data, length);

    v8::TryCatch exceptionCatcher(scriptState->isolate());
    v8::Local<v8::Value> jsonDictionary;
    if (v8Call(v8::JSON::Parse(scriptState->isolate(), jsonString), jsonDictionary, exceptionCatcher))
        m_resolver->resolve(jsonDictionary);
    else
        m_resolver->reject(exceptionCatcher.Exception());
    clearResolver();
}
Example #7
0
void FetchManager::Loader::failed()
{
    if (m_failed)
        return;
    if (!m_resolver->executionContext() || m_resolver->executionContext()->activeDOMObjectsAreStopped())
        return;
    m_failed = true;
    ScriptState* state = m_resolver->scriptState();
    ScriptState::Scope scope(state);
    m_resolver->reject(V8ThrowException::createTypeError("Failed to fetch", state->isolate()));
    notifyFinished();
}
void injectInternalsObject(v8::Local<v8::Context> context)
{
    ScriptState* scriptState = ScriptState::from(context);
    ScriptState::Scope scope(scriptState);
    v8::Local<v8::Object> global = scriptState->context()->Global();
    ExecutionContext* executionContext = scriptState->executionContext();
    if (executionContext->isDocument()) {
        v8::Local<v8::Value> internals = toV8(Internals::create(toDocument(executionContext)), global, scriptState->isolate());
        ASSERT(!internals.IsEmpty());
        v8CallOrCrash(global->Set(scriptState->context(), v8AtomicString(scriptState->isolate(), Internals::internalsId), internals));
    }
}
void AcceptConnectionObserver::responseWasResolved(const ScriptValue& value)
{
    ASSERT(executionContext());
    if (!m_resolver) {
        // TODO(mek): Get rid of this block when observer is only used for
        // service port connect events.
        if (!value.v8Value()->IsTrue()) {
            responseWasRejected();
            return;
        }
        ServiceWorkerGlobalScopeClient::from(executionContext())->didHandleCrossOriginConnectEvent(m_eventID, true);
        m_state = Done;
        return;
    }

    ScriptState* scriptState = m_resolver->scriptState();
    ExceptionState exceptionState(ExceptionState::UnknownContext, nullptr, nullptr, scriptState->context()->Global(), scriptState->isolate());
    ServicePortConnectResponse response = ScriptValue::to<ServicePortConnectResponse>(scriptState->isolate(), value, exceptionState);
    if (exceptionState.hadException()) {
        exceptionState.reject(m_resolver.get());
        m_resolver = nullptr;
        responseWasRejected();
        return;
    }
    if (!response.hasAccept() || !response.accept()) {
        responseWasRejected();
        return;
    }
    WebServicePort webPort;
    webPort.targetUrl = m_targetURL;
    if (response.hasName())
        webPort.name = response.name();
    if (response.hasData()) {
        webPort.data = SerializedScriptValueFactory::instance().create(scriptState->isolate(), response.data(), nullptr, exceptionState)->toWireString();
        if (exceptionState.hadException()) {
            exceptionState.reject(m_resolver.get());
            m_resolver = nullptr;
            responseWasRejected();
            return;
        }
    }
    webPort.id = m_portID;
    ServicePort* port = ServicePort::create(m_collection, webPort);
    m_collection->addPort(port);
    m_resolver->resolve(port);
    m_callbacks->onSuccess(&webPort);
    m_state = Done;
}
void FetchManager::Loader::failed(const String& message)
{
    if (m_failed || m_finished)
        return;
    m_failed = true;
    if (!message.isEmpty())
        executionContext()->addConsoleMessage(ConsoleMessage::create(JSMessageSource, ErrorMessageLevel, message));
    if (m_resolver) {
        if (!m_resolver->executionContext() || m_resolver->executionContext()->activeDOMObjectsAreStopped())
            return;
        ScriptState* state = m_resolver->scriptState();
        ScriptState::Scope scope(state);
        m_resolver->reject(V8ThrowException::createTypeError(state->isolate(), "Failed to fetch"));
    }
    notifyFinished();
}
Example #11
0
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
  // Odd sizes are handled in various ways, depending how they arrive.
  // Let's not worry about that case here.
  if (size % sizeof(UChar))
    return 0;

  // Used to control what kind of extra data is provided to the deserializer.
  unsigned hash = StringHasher::hashMemory(data, size);

  // If message ports are requested, make some.
  MessagePortArray* messagePorts = nullptr;
  if (hash & kFuzzMessagePorts) {
    messagePorts = new MessagePortArray(3);
    std::generate(messagePorts->begin(), messagePorts->end(), []() {
      WebMessagePortChannelUniquePtr channel(new WebMessagePortChannelImpl());
      MessagePort* port = MessagePort::create(pageHolder->document());
      port->entangle(std::move(channel));
      return port;
    });
  }

  // If blobs are requested, supply blob info.
  const auto* blobs = (hash & kFuzzBlobInfo) ? blobInfoArray : nullptr;

  // Set up.
  ScriptState* scriptState = ScriptState::forMainWorld(&pageHolder->frame());
  v8::Isolate* isolate = scriptState->isolate();
  ScriptState::Scope scope(scriptState);
  v8::TryCatch tryCatch(isolate);

  // Deserialize.
  RefPtr<SerializedScriptValue> serializedScriptValue =
      SerializedScriptValue::create(reinterpret_cast<const char*>(data), size);
  serializedScriptValue->deserialize(isolate, messagePorts, blobs);
  CHECK(!tryCatch.HasCaught())
      << "deserialize() should return null rather than throwing an exception.";

  // Clean up. We have to periodically run pending tasks so that scheduled
  // Oilpan GC occurs.
  static int iterations = 0;
  if (iterations++ == 2048) {
    testing::runPendingTasks();
    iterations = 0;
  }

  return 0;
}
void WebDevToolsFrontendImpl::windowObjectCleared()
{
    v8::Isolate* isolate = v8::Isolate::GetCurrent();
    Page* page = m_webViewImpl->page();
    ASSERT(page->mainFrame());
    ScriptState* scriptState = ScriptState::forMainWorld(page->deprecatedLocalMainFrame());
    ScriptState::Scope scope(scriptState);

    if (m_frontendHost)
        m_frontendHost->disconnectClient();
    m_frontendHost = InspectorFrontendHost::create(this, page);
    v8::Handle<v8::Object> global = scriptState->context()->Global();
    v8::Handle<v8::Value> frontendHostObj = toV8(m_frontendHost.get(), global, scriptState->isolate());

    global->Set(v8::String::NewFromUtf8(isolate, "InspectorFrontendHost"), frontendHostObj);
    ScriptController* scriptController = page->mainFrame() ? &page->deprecatedLocalMainFrame()->script() : 0;
    if (scriptController) {
        String installAdditionalAPI =
            "" // Wrap messages that go to embedder.
            "(function(host, methodEntries) {"
            "    host._lastCallId = 0;"
            "    host._callbacks = [];"
            "    host.embedderMessageAck = function(id, error)"
            "    {"
            "        var callback = host._callbacks[id];"
            "        delete host._callbacks[id];"
            "        if (callback)"
            "            callback(error);"
            "    };"
            "    function dispatch(methodName, argumentCount)"
            "    {"
            "        var callId = ++host._lastCallId;"
            "        var argsArray = Array.prototype.slice.call(arguments, 2);"
            "        var callback = argsArray[argsArray.length - 1];"
            "        if (typeof callback === \"function\") {"
            "            argsArray.pop();"
            "            host._callbacks[callId] = callback;"
            "        }"
            "        var message = { \"id\": callId, \"method\": methodName };"
            "        argsArray = argsArray.slice(0, argumentCount);"
            "        if (argsArray.length)"
            "            message.params = argsArray;"
            "        host.sendMessageToEmbedder(JSON.stringify(message));"
            "    };"
            "    methodEntries.forEach(function(methodEntry) { host[methodEntry[0]] = dispatch.bind(null, methodEntry[0], methodEntry[1]); });"
            "})(InspectorFrontendHost,"
            "    [['addFileSystem', 0],"
            "     ['append', 2],"
            "     ['bringToFront', 0],"
            "     ['closeWindow', 0],"
            "     ['indexPath', 2],"
            "     ['inspectElementCompleted', 0],"
            "     ['inspectedURLChanged', 1],"
            "     ['moveWindowBy', 2],"
            "     ['openInNewTab', 1],"
            "     ['openUrlOnRemoteDeviceAndInspect', 2],"
            "     ['removeFileSystem', 1],"
            "     ['requestFileSystems', 0],"
            "     ['resetZoom', 0],"
            "     ['save', 3],"
            "     ['searchInPath', 3],"
            "     ['setDeviceCountUpdatesEnabled', 1],"
            "     ['setDevicesUpdatesEnabled', 1],"
            "     ['setWhitelistedShortcuts', 1],"
            "     ['setContentsResizingStrategy', 2],"
            "     ['setInspectedPageBounds', 1],"
            "     ['setIsDocked', 1],"
            "     ['stopIndexing', 1],"
            "     ['zoomIn', 0],"
            "     ['zoomOut', 0]]);"
            ""
            "" // Support for legacy front-ends (<M34). Do not add items here.
            "InspectorFrontendHost.requestSetDockSide = function(dockSide)"
            "{"
            "    InspectorFrontendHost.setIsDocked(dockSide !== \"undocked\");"
            "};"
            "InspectorFrontendHost.supportsFileSystems = function() { return true; };"
            ""
            "" // Support for legacy front-ends (<M28). Do not add items here.
            "InspectorFrontendHost.canInspectWorkers = function() { return true; };"
            "InspectorFrontendHost.canSaveAs = function() { return true; };"
            "InspectorFrontendHost.canSave = function() { return true; };"
            "InspectorFrontendHost.loaded = function() {};"
            "InspectorFrontendHost.hiddenPanels = function() { return ""; };"
            "InspectorFrontendHost.localizedStringsURL = function() { return ""; };"
            "InspectorFrontendHost.close = function(url) { };";
        scriptController->executeScriptInMainWorld(installAdditionalAPI, ScriptController::ExecuteScriptWhenScriptsDisabled);
    }
}