Esempio n. 1
0
inline void
getChildData(
            const XalanNode*    child,
            ExecutionContext&   executionContext,
            XalanDOMString&     data)
{
    assert(executionContext.hasPreserveOrStripSpaceConditions() == true);

    const XalanNode::NodeType   theType = child->getNodeType();

    if (theType == XalanNode::ELEMENT_NODE)
    {
        const XalanElement* const   theElementNode =
                static_cast<const XalanElement*>(child);

        DOMServices::doGetNodeData(*theElementNode, executionContext, data);
    }
    else if (theType == XalanNode::TEXT_NODE ||
             theType == XalanNode::CDATA_SECTION_NODE)
    {
        const XalanText*    theTextNode =
                static_cast<const XalanText*>(child);

        DOMServices::doGetNodeData(*theTextNode, executionContext, data);
    }
}
Esempio n. 2
0
bool
DynamicCheckerFunctions::Install(Stream &error_stream,
                                 ExecutionContext &exe_ctx)
{
    m_valid_pointer_check.reset(new ClangUtilityFunction(g_valid_pointer_check_text,
                                                         VALID_POINTER_CHECK_NAME));
    if (!m_valid_pointer_check->Install(error_stream, exe_ctx))
        return false;
    
    Process *process = exe_ctx.GetProcessPtr();

    if (process)
    {
        ObjCLanguageRuntime *objc_language_runtime = process->GetObjCLanguageRuntime();
        
        if (objc_language_runtime)
        {
            m_objc_object_check.reset(objc_language_runtime->CreateObjectChecker(VALID_OBJC_OBJECT_CHECK_NAME));
            
            if (!m_objc_object_check->Install(error_stream, exe_ctx))
                return false;
        }
    }
        
    return true;
}
Esempio n. 3
0
	OutputBuffer allocate_buffer(
		size_type min_data_size, size_type min_record_count)
	{
		if(!m_context){
			throw std::runtime_error(
				"This OutputWriter is not corresponding to any tasks");
		}
		auto &memory_manager = m_context->memory_manager();
		SerializedBuffer sb;
		if(m_has_keys){
			sb = SerializedBuffer::allocate_key_value_buffer(
				memory_manager,
				std::max(min_record_count, m_default_records_per_buffer),
				std::max(min_data_size,    m_default_buffer_size),
				m_current_locality.self_node_id());
		}else{
			sb = SerializedBuffer::allocate_value_only_buffer(
				memory_manager,
				std::max(min_record_count, m_default_records_per_buffer),
				std::max(min_data_size,    m_default_buffer_size),
				m_current_locality.self_node_id());
		}
		OutputBufferImpl buffer_impl;
		buffer_impl.bind_fragment(std::move(sb));
		return OutputBufferImpl::wrap_impl(std::move(buffer_impl));
	}
Esempio n. 4
0
/*!
 * \brief  Return a handle to the value of the Nth argument of the primitive.
 * \param  inIndex Index of the actual primitive in the primitive tree.
 * \param  inN Number of the argument to get the index.
 * \param  ioContext A reference to the execution context.
 * \return A handle to the value of the Nth argument of the primitive.
 */
AnyType::Handle Primitive::getArgument(unsigned int inIndex, unsigned int inN, ExecutionContext& ioContext) const {
	schnaps_StackTraceBeginM();
	unsigned int lNodeIndex = getArgumentIndex(inIndex, inN, ioContext);
	AnyType::Handle outResult = ioContext.getPrimitiveTree()[lNodeIndex].mPrimitive->execute(lNodeIndex, ioContext);
	return outResult;
	schnaps_StackTraceEndM("AnyType::Handle Primitive::getArgument(unsigned int, unsigned int, SCHNAPS::Core::ExecutionContext&) const");
}
Esempio n. 5
0
inline void
getChildData(
            const XalanNode*                child,
            ExecutionContext&               executionContext,
            FormatterListener&              formatterListener,
            DOMServices::MemberFunctionPtr  function)
{
    assert(executionContext.hasPreserveOrStripSpaceConditions() == true);

    const XalanNode::NodeType   theType = child->getNodeType();

    if (theType == XalanNode::ELEMENT_NODE)
    {
        const XalanElement* const   theElementNode =
                static_cast<const XalanElement*>(child);

        DOMServices::getNodeData(*theElementNode, executionContext, formatterListener, function);
    }
    else if (theType == XalanNode::TEXT_NODE ||
             theType == XalanNode::CDATA_SECTION_NODE)
    {
        const XalanText*    theTextNode =
                static_cast<const XalanText*>(child);

        DOMServices::getNodeData(*theTextNode, executionContext, formatterListener, function);
    }
}
bool UnwindAssembly_x86::FirstNonPrologueInsn(
    AddressRange &func, const ExecutionContext &exe_ctx,
    Address &first_non_prologue_insn) {

  if (!func.GetBaseAddress().IsValid())
    return false;

  Target *target = exe_ctx.GetTargetPtr();
  if (target == nullptr)
    return false;

  if (m_assembly_inspection_engine == nullptr)
    return false;

  const bool prefer_file_cache = true;
  std::vector<uint8_t> function_text(func.GetByteSize());
  Status error;
  if (target->ReadMemory(func.GetBaseAddress(), prefer_file_cache,
                         function_text.data(), func.GetByteSize(),
                         error) == func.GetByteSize()) {
    size_t offset;
    if (m_assembly_inspection_engine->FindFirstNonPrologueInstruction(
            function_text.data(), func.GetByteSize(), offset)) {
      first_non_prologue_insn = func.GetBaseAddress();
      first_non_prologue_insn.Slide(offset);
    }
    return true;
  }
  return false;
}
Esempio n. 7
0
// This is the static function
ExecutionResults 
ClangFunction::ExecuteFunction (
        ExecutionContext &exe_ctx, 
        lldb::addr_t function_address, 
        lldb::addr_t &void_arg,
        bool stop_others,
        bool try_all_threads,
        bool discard_on_error,
        uint32_t single_thread_timeout_usec,
        Stream &errors,
        lldb::addr_t *this_arg)
{
    lldb::ThreadPlanSP call_plan_sp (ClangFunction::GetThreadPlanToCallFunction (exe_ctx, 
                                                                                 function_address, 
                                                                                 void_arg, 
                                                                                 errors, 
                                                                                 stop_others, 
                                                                                 discard_on_error, 
                                                                                 this_arg));
    if (call_plan_sp == NULL)
        return eExecutionSetupError;
    
    call_plan_sp->SetPrivate(true);
    
    return exe_ctx.GetProcessRef().RunThreadPlan (exe_ctx, call_plan_sp, 
                                                  stop_others, 
                                                  try_all_threads, 
                                                  discard_on_error,
                                                  single_thread_timeout_usec, 
                                                  errors);
}  
void DatabaseTracker::forEachOpenDatabaseInPage(Page* page, std::unique_ptr<DatabaseCallback> callback)
{
    MutexLocker openDatabaseMapLock(m_openDatabaseMapGuard);
    if (!m_openDatabaseMap)
        return;
    for (auto& originMap : *m_openDatabaseMap) {
        for (auto& nameDatabaseSet : *originMap.value) {
            for (Database* database : *nameDatabaseSet.value) {
                ExecutionContext* context = database->getExecutionContext();
                ASSERT(context->isDocument());
                if (toDocument(context)->frame()->page() == page)
                    (*callback)(database);
            }
        }
    }
}
Esempio n. 9
0
lldb::DisassemblerSP
Disassembler::DisassembleRange
(
    const ArchSpec &arch,
    const char *plugin_name,
    const char *flavor,
    const ExecutionContext &exe_ctx,
    const AddressRange &range,
    bool prefer_file_cache
)
{
    lldb::DisassemblerSP disasm_sp;
    if (range.GetByteSize() > 0 && range.GetBaseAddress().IsValid())
    {
        disasm_sp = Disassembler::FindPluginForTarget(exe_ctx.GetTargetSP(), arch, flavor, plugin_name);

        if (disasm_sp)
        {
            size_t bytes_disassembled = disasm_sp->ParseInstructions (&exe_ctx, range, NULL, prefer_file_cache);
            if (bytes_disassembled == 0)
                disasm_sp.reset();
        }
    }
    return disasm_sp;
}
Esempio n. 10
0
/*!
 * \brief  Interpret the primitive tree.
 * \param  ioContext A reference to the execution context.
 * \return A handle to the result of the interpretation.
 * \throw  SCHNAPS::Core::AssertException if the primitive tree is empty.
 */
AnyType::Handle PrimitiveTree::interpret(ExecutionContext& ioContext) const {
	schnaps_StackTraceBeginM();
	schnaps_AssertM(empty() == false);
	ioContext.setPrimitiveTree(this);
	return (*this)[0].mPrimitive->execute(0, ioContext);
	schnaps_StackTraceEndM("SCHNAPS::Core::Atom::Handle SCHNAPS::Core::PrimitiveTree::interpret(SCHNAPS::Core::ExecutionContext&)");
}
Esempio n. 11
0
static void
ResolveAddress (const ExecutionContext &exe_ctx,
                const Address &addr, 
                Address &resolved_addr)
{
    if (!addr.IsSectionOffset())
    {
        // If we weren't passed in a section offset address range,
        // try and resolve it to something
        Target *target = exe_ctx.GetTargetPtr();
        if (target)
        {
            if (target->GetSectionLoadList().IsEmpty())
            {
                target->GetImages().ResolveFileAddress (addr.GetOffset(), resolved_addr);
            }
            else
            {
                target->GetSectionLoadList().ResolveLoadAddress (addr.GetOffset(), resolved_addr);
            }
            // We weren't able to resolve the address, just treat it as a
            // raw address
            if (resolved_addr.IsValid())
                return;
        }
    }
    resolved_addr = addr;
}
Esempio n. 12
0
lldb::ThreadPlanSP
ClangFunction::GetThreadPlanToCallFunction (ExecutionContext &exe_ctx, 
                                            lldb::addr_t args_addr,
                                            const EvaluateExpressionOptions &options,
                                            Stream &errors)
{
    Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_EXPRESSIONS | LIBLLDB_LOG_STEP));
    
    if (log)
        log->Printf("-- [ClangFunction::GetThreadPlanToCallFunction] Creating thread plan to call function \"%s\" --", m_name.c_str());
    
    // FIXME: Use the errors Stream for better error reporting.
    Thread *thread = exe_ctx.GetThreadPtr();
    if (thread == NULL)
    {
        errors.Printf("Can't call a function without a valid thread.");
        return NULL;
    }

    // Okay, now run the function:

    Address wrapper_address (m_jit_start_addr);
    
    lldb::addr_t args = { args_addr };
    
    lldb::ThreadPlanSP new_plan_sp (new ThreadPlanCallFunction (*thread,
                                                       wrapper_address,
                                                       CompilerType(),
                                                       args,
                                                       options));
    new_plan_sp->SetIsMasterPlan(true);
    new_plan_sp->SetOkayToDiscard (false);
    return new_plan_sp;
}
Esempio n. 13
0
bool
ClangFunction::FetchFunctionResults (ExecutionContext &exe_ctx, lldb::addr_t args_addr, Value &ret_value)
{
    // Read the return value - it is the last field in the struct:
    // FIXME: How does clang tell us there's no return value?  We need to handle that case.
    // FIXME: Create our ThreadPlanCallFunction with the return CompilerType, and then use GetReturnValueObject
    // to fetch the value.  That way we can fetch any values we need.
    
    Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_EXPRESSIONS | LIBLLDB_LOG_STEP));
    
    if (log)
        log->Printf("-- [ClangFunction::FetchFunctionResults] Fetching function results for \"%s\"--", m_name.c_str());
    
    Process *process = exe_ctx.GetProcessPtr();
    
    if (process == NULL)
        return false;

    lldb::ProcessSP jit_process_sp(m_jit_process_wp.lock());
    
    if (process != jit_process_sp.get())
        return false;
                
    Error error;
    ret_value.GetScalar() = process->ReadUnsignedIntegerFromMemory (args_addr + m_return_offset, m_return_size, 0, error);

    if (error.Fail())
        return false;

    ret_value.SetCompilerType(m_function_return_type);
    ret_value.SetValueType(Value::eValueTypeScalar);
    return true;
}
Esempio n. 14
0
/*
    member = string name-separator value
*/
bool JsonParser::parseMember(Object *o)
{
    BEGIN << "parseMember";
    Scope scope(context);

    QString key;
    if (!parseString(&key))
        return false;
    QChar token = nextToken();
    if (token != NameSeparator) {
        lastError = QJsonParseError::MissingNameSeparator;
        return false;
    }
    ScopedValue val(scope);
    if (!parseValue(val))
        return false;

    ScopedString s(scope, context->d()->engine->newIdentifier(key));
    uint idx = s->asArrayIndex();
    if (idx < UINT_MAX) {
        o->putIndexed(idx, val);
    } else {
        o->insertMember(s.getPointer(), val);
    }

    END;
    return true;
}
Esempio n. 15
0
void WorkerGlobalScopeFileSystem::webkitRequestFileSystem(WorkerGlobalScope* worker, int type, long long size, PassOwnPtr<FileSystemCallback> successCallback, PassOwnPtr<ErrorCallback> errorCallback)
{
    ExecutionContext* secureContext = worker->executionContext();
    if (!secureContext->securityOrigin()->canAccessFileSystem()) {
        DOMFileSystem::scheduleCallback(worker, errorCallback, FileError::create(FileError::SECURITY_ERR));
        return;
    }

    FileSystemType fileSystemType = static_cast<FileSystemType>(type);
    if (!DOMFileSystemBase::isValidType(fileSystemType)) {
        DOMFileSystem::scheduleCallback(worker, errorCallback, FileError::create(FileError::INVALID_MODIFICATION_ERR));
        return;
    }

    LocalFileSystem::from(worker)->requestFileSystem(worker, fileSystemType, size, FileSystemCallbacks::create(successCallback, errorCallback, worker, fileSystemType));
}
Esempio n. 16
0
void WorkerGlobalScopeFileSystem::webkitResolveLocalFileSystemURL(WorkerGlobalScope* worker, const String& url, PassOwnPtr<EntryCallback> successCallback, PassOwnPtr<ErrorCallback> errorCallback)
{
    KURL completedURL = worker->completeURL(url);
    ExecutionContext* secureContext = worker->executionContext();
    if (!secureContext->securityOrigin()->canAccessFileSystem() || !secureContext->securityOrigin()->canRequest(completedURL)) {
        DOMFileSystem::scheduleCallback(worker, errorCallback, FileError::create(FileError::SECURITY_ERR));
        return;
    }

    if (!completedURL.isValid()) {
        DOMFileSystem::scheduleCallback(worker, errorCallback, FileError::create(FileError::ENCODING_ERR));
        return;
    }

    LocalFileSystem::from(worker)->resolveURL(worker, completedURL, ResolveURICallbacks::create(successCallback, errorCallback, worker));
}
Esempio n. 17
0
 virtual void execute(const DOM::Node<string_type, string_adaptor>& node, 
                      ExecutionContext<string_type, string_adaptor>& context) const
 {
   ChainStackFrame<string_type, string_adaptor> frame(context);
   if(test_->evaluateAsBool(node, context.xpathContext()))
     this->execute_children(node, context);
 } // execute
static void SetupDeclVendor(ExecutionContext &exe_ctx, Target *target) {
  if (ClangModulesDeclVendor *decl_vendor =
          target->GetClangModulesDeclVendor()) {
    const ClangModulesDeclVendor::ModuleVector &hand_imported_modules =
        llvm::cast<ClangPersistentVariables>(
            target->GetPersistentExpressionStateForLanguage(
                lldb::eLanguageTypeC))
            ->GetHandLoadedClangModules();
    ClangModulesDeclVendor::ModuleVector modules_for_macros;

    for (ClangModulesDeclVendor::ModuleID module : hand_imported_modules) {
      modules_for_macros.push_back(module);
    }

    if (target->GetEnableAutoImportClangModules()) {
      if (StackFrame *frame = exe_ctx.GetFramePtr()) {
        if (Block *block = frame->GetFrameBlock()) {
          SymbolContext sc;

          block->CalculateSymbolContext(&sc);

          if (sc.comp_unit) {
            StreamString error_stream;

            decl_vendor->AddModulesForCompileUnit(
                *sc.comp_unit, modules_for_macros, error_stream);
          }
        }
      }
    }
  }
}
Esempio n. 19
0
lldb_private::Error
ClangExpressionParser::RunStaticInitializers (lldb::IRExecutionUnitSP &execution_unit_sp,
                                              ExecutionContext &exe_ctx)
{
    lldb_private::Error err;
    
    lldbassert(execution_unit_sp.get());
    lldbassert(exe_ctx.HasThreadScope());
    
    if (!execution_unit_sp.get())
    {
        err.SetErrorString ("can't run static initializers for a NULL execution unit");
        return err;
    }
    
    if (!exe_ctx.HasThreadScope())
    {
        err.SetErrorString ("can't run static initializers without a thread");
        return err;
    }
    
    std::vector<lldb::addr_t> static_initializers;
    
    execution_unit_sp->GetStaticInitializers(static_initializers);
    
    for (lldb::addr_t static_initializer : static_initializers)
    {
        EvaluateExpressionOptions options;
                
        lldb::ThreadPlanSP call_static_initializer(new ThreadPlanCallFunction(exe_ctx.GetThreadRef(),
                                                                              Address(static_initializer),
                                                                              CompilerType(),
                                                                              llvm::ArrayRef<lldb::addr_t>(),
                                                                              options));
        
        DiagnosticManager execution_errors;
        lldb::ExpressionResults results = exe_ctx.GetThreadRef().GetProcess()->RunThreadPlan(exe_ctx, call_static_initializer, options, execution_errors);
        
        if (results != lldb::eExpressionCompleted)
        {
            err.SetErrorStringWithFormat ("couldn't run static initializer: %s", execution_errors.GetString().c_str());
            return err;
        }
    }
    
    return err;
}
void V8XMLHttpRequest::constructorCustom(const v8::FunctionCallbackInfo<v8::Value>& info)
{
    ExecutionContext* context = currentExecutionContext(info.GetIsolate());

    RefPtr<SecurityOrigin> securityOrigin;
    if (context->isDocument()) {
        DOMWrapperWorld& world = DOMWrapperWorld::current(info.GetIsolate());
        if (world.isIsolatedWorld())
            securityOrigin = world.isolatedWorldSecurityOrigin();
    }

    RefPtrWillBeRawPtr<XMLHttpRequest> xmlHttpRequest = XMLHttpRequest::create(context, securityOrigin);

    v8::Handle<v8::Object> wrapper = info.Holder();
    V8DOMWrapper::associateObjectWithWrapper<V8XMLHttpRequest>(xmlHttpRequest.release(), &wrapperTypeInfo, wrapper, info.GetIsolate(), WrapperConfiguration::Dependent);
    info.GetReturnValue().Set(wrapper);
}
Esempio n. 21
0
void FileReaderLoader::startInternal(ExecutionContext& executionContext, const Stream* stream, PassRefPtr<BlobDataHandle> blobData)
{
    // The blob is read by routing through the request handling layer given a temporary public url.
    m_urlForReading = BlobURL::createPublicURL(executionContext.getSecurityOrigin());
    if (m_urlForReading.isEmpty()) {
        failed(FileError::SECURITY_ERR);
        return;
    }

    if (blobData) {
        ASSERT(!stream);
        BlobRegistry::registerPublicBlobURL(executionContext.getSecurityOrigin(), m_urlForReading, blobData);
    } else {
        ASSERT(stream);
        BlobRegistry::registerStreamURL(executionContext.getSecurityOrigin(), m_urlForReading, stream->url());
    }

    // Construct and load the request.
    ResourceRequest request(m_urlForReading);
    request.setExternalRequestStateFromRequestorAddressSpace(executionContext.securityContext().addressSpace());

    // FIXME: Should this really be 'internal'? Do we know anything about the actual request that generated this fetch?
    request.setRequestContext(WebURLRequest::RequestContextInternal);

    request.setHTTPMethod(HTTPNames::GET);
    if (m_hasRange)
        request.setHTTPHeaderField(HTTPNames::Range, AtomicString(String::format("bytes=%d-%d", m_rangeStart, m_rangeEnd)));

    ThreadableLoaderOptions options;
    options.preflightPolicy = ConsiderPreflight;
    options.crossOriginRequestPolicy = DenyCrossOriginRequests;
    // FIXME: Is there a directive to which this load should be subject?
    options.contentSecurityPolicyEnforcement = DoNotEnforceContentSecurityPolicy;
    // Use special initiator to hide the request from the inspector.
    options.initiator = FetchInitiatorTypeNames::internal;

    ResourceLoaderOptions resourceLoaderOptions;
    resourceLoaderOptions.allowCredentials = AllowStoredCredentials;

    if (m_client) {
        m_loader = ThreadableLoader::create(executionContext, this, options, resourceLoaderOptions);
        m_loader->start(request);
    } else {
        ThreadableLoader::loadResourceSynchronously(executionContext, request, *this, options, resourceLoaderOptions);
    }
}
Esempio n. 22
0
int setTimeout(ScriptState* scriptState, EventTarget& eventTarget, const String& handler, int timeout, const Vector<ScriptValue>&)
{
    ExecutionContext* executionContext = eventTarget.executionContext();
    if (!isAllowed(scriptState, executionContext, true))
        return 0;
    // Don't allow setting timeouts to run empty functions.  Was historically a
    // perfomance issue.
    if (handler.isEmpty())
        return 0;
    if (timeout >= 0 && executionContext->isDocument()) {
        // FIXME: Crude hack that attempts to pass idle time to V8. This should
        // be done using the scheduler instead.
        V8GCForContextDispose::instance().notifyIdle();
    }
    OwnPtrWillBeRawPtr<ScheduledAction> action = ScheduledAction::create(scriptState, handler);
    return DOMTimer::install(executionContext, action.release(), timeout, true);
}
void V8XMLHttpRequest::openMethodCustom(const v8::FunctionCallbackInfo<v8::Value>& info)
{
    // Four cases:
    // open(method, url)
    // open(method, url, async)
    // open(method, url, async, user)
    // open(method, url, async, user, passwd)

    ExceptionState exceptionState(ExceptionState::ExecutionContext, "open", "XMLHttpRequest", info.Holder(), info.GetIsolate());

    if (info.Length() < 2) {
        exceptionState.throwTypeError(ExceptionMessages::notEnoughArguments(2, info.Length()));
        exceptionState.throwIfNeeded();
        return;
    }

    XMLHttpRequest* xmlHttpRequest = V8XMLHttpRequest::toNative(info.Holder());

    TOSTRING_VOID(V8StringResource<>, method, info[0]);
    TOSTRING_VOID(V8StringResource<>, urlstring, info[1]);

    ExecutionContext* context = currentExecutionContext(info.GetIsolate());
    KURL url = context->completeURL(urlstring);

    if (info.Length() >= 3) {
        bool async = info[2]->BooleanValue();

        if (info.Length() >= 4 && !info[3]->IsUndefined()) {
            TOSTRING_VOID(V8StringResource<TreatNullAsNullString>, user, info[3]);

            if (info.Length() >= 5 && !info[4]->IsUndefined()) {
                TOSTRING_VOID(V8StringResource<TreatNullAsNullString>, password, info[4]);
                xmlHttpRequest->open(method, url, async, user, password, exceptionState);
            } else {
                xmlHttpRequest->open(method, url, async, user, exceptionState);
            }
        } else {
            xmlHttpRequest->open(method, url, async, exceptionState);
        }
    } else {
        xmlHttpRequest->open(method, url, exceptionState);
    }

    exceptionState.throwIfNeeded();
}
Esempio n. 24
0
 explicit io_object_impl(ExecutionContext& context,
     typename enable_if<is_convertible<
       ExecutionContext&, execution_context&>::value>::type* = 0)
   : service_(&boost::asio::use_service<IoObjectService>(context)),
     implementation_executor_(context.get_executor(),
       is_same<ExecutionContext, io_context>::value)
 {
   service_->construct(implementation_);
 }
void ThreadableLoader::loadResourceSynchronously(ExecutionContext& context, const ResourceRequest& request, ThreadableLoaderClient& client, const ThreadableLoaderOptions& options, const ResourceLoaderOptions& resourceLoaderOptions)
{
    if (context.isWorkerGlobalScope()) {
        WorkerThreadableLoader::loadResourceSynchronously(toWorkerGlobalScope(context), request, client, options, resourceLoaderOptions);
        return;
    }

    DocumentThreadableLoader::loadResourceSynchronously(toDocument(context), request, client, options, resourceLoaderOptions);
}
Esempio n. 26
0
  void report() {
    if (!m_scriptState->contextIsValid())
      return;
    // If execution termination has been triggered, quietly bail out.
    if (m_scriptState->isolate()->IsExecutionTerminating())
      return;
    ExecutionContext* executionContext = m_scriptState->getExecutionContext();
    if (!executionContext)
      return;

    ScriptState::Scope scope(m_scriptState);
    v8::Local<v8::Value> value = m_promise.newLocal(m_scriptState->isolate());
    v8::Local<v8::Value> reason =
        m_exception.newLocal(m_scriptState->isolate());
    // Either collected or https://crbug.com/450330
    if (value.IsEmpty() || !value->IsPromise())
      return;
    ASSERT(!hasHandler());

    EventTarget* target = executionContext->errorEventTarget();
    if (target &&
        !executionContext->shouldSanitizeScriptError(m_resourceName,
                                                     m_corsStatus)) {
      PromiseRejectionEventInit init;
      init.setPromise(ScriptPromise(m_scriptState, value));
      init.setReason(ScriptValue(m_scriptState, reason));
      init.setCancelable(true);
      PromiseRejectionEvent* event = PromiseRejectionEvent::create(
          m_scriptState, EventTypeNames::unhandledrejection, init);
      // Log to console if event was not canceled.
      m_shouldLogToConsole =
          target->dispatchEvent(event) == DispatchEventResult::NotCanceled;
    }

    if (m_shouldLogToConsole) {
      V8PerIsolateData* data = V8PerIsolateData::from(m_scriptState->isolate());
      if (data->threadDebugger())
        m_promiseRejectionId = data->threadDebugger()->promiseRejected(
            m_scriptState->context(), m_errorMessage, reason,
            std::move(m_location));
    }

    m_location.reset();
  }
Esempio n. 27
0
ScriptPromise USB::requestDevice(ScriptState* scriptState,
                                 const USBDeviceRequestOptions& options) {
  ExecutionContext* executionContext = scriptState->getExecutionContext();
  UseCounter::count(executionContext, UseCounter::UsbRequestDevice);

  ScriptPromiseResolver* resolver = ScriptPromiseResolver::create(scriptState);
  ScriptPromise promise = resolver->promise();

  if (!m_chooserService) {
    LocalFrame* frame = executionContext->isDocument()
                            ? toDocument(executionContext)->frame()
                            : nullptr;
    if (!frame) {
      resolver->reject(DOMException::create(NotSupportedError));
      return promise;
    }
    frame->interfaceProvider()->getInterface(mojo::GetProxy(&m_chooserService));
    m_chooserService.set_connection_error_handler(
        convertToBaseCallback(WTF::bind(&USB::onChooserServiceConnectionError,
                                        wrapWeakPersistent(this))));
  }

  String errorMessage;
  if (!executionContext->isSecureContext(errorMessage)) {
    resolver->reject(DOMException::create(SecurityError, errorMessage));
  } else if (!UserGestureIndicator::consumeUserGesture()) {
    resolver->reject(DOMException::create(
        SecurityError,
        "Must be handling a user gesture to show a permission request."));
  } else {
    Vector<usb::DeviceFilterPtr> filters;
    if (options.hasFilters()) {
      filters.reserveCapacity(options.filters().size());
      for (const auto& filter : options.filters())
        filters.append(convertDeviceFilter(filter));
    }
    m_chooserServiceRequests.add(resolver);
    m_chooserService->GetPermission(
        std::move(filters), convertToBaseCallback(WTF::bind(
                                &USB::onGetPermission, wrapPersistent(this),
                                wrapPersistent(resolver))));
  }
  return promise;
}
Esempio n. 28
0
static void promiseRejectHandler(v8::PromiseRejectMessage data, RejectedPromises& rejectedPromises, ScriptState* scriptState)
{
    if (data.GetEvent() == v8::kPromiseHandlerAddedAfterReject) {
        rejectedPromises.handlerAdded(data);
        return;
    }

    ASSERT(data.GetEvent() == v8::kPromiseRejectWithNoHandler);

    v8::Local<v8::Promise> promise = data.GetPromise();
    v8::Isolate* isolate = promise->GetIsolate();
    ExecutionContext* context = scriptState->getExecutionContext();

    v8::Local<v8::Value> exception = data.GetValue();
    if (V8DOMWrapper::isWrapper(isolate, exception)) {
        // Try to get the stack & location from a wrapped exception object (e.g. DOMException).
        ASSERT(exception->IsObject());
        auto privateError = V8PrivateProperty::getDOMExceptionError(isolate);
        v8::Local<v8::Value> error = privateError.getOrUndefined(scriptState->context(), exception.As<v8::Object>());
        if (!error->IsUndefined())
            exception = error;
    }

    String errorMessage;
    AccessControlStatus corsStatus = NotSharableCrossOrigin;
    std::unique_ptr<SourceLocation> location;

    v8::Local<v8::Message> message = v8::Exception::CreateMessage(isolate, exception);
    if (!message.IsEmpty()) {
        // message->Get() can be empty here. https://crbug.com/450330
        errorMessage = toCoreStringWithNullCheck(message->Get());
        location = SourceLocation::fromMessage(isolate, message, context);
        if (message->IsSharedCrossOrigin())
            corsStatus = SharableCrossOrigin;
    } else {
        location = SourceLocation::create(context->url().getString(), 0, 0, nullptr);
    }

    String messageForConsole = extractMessageForConsole(isolate, data.GetValue());
    if (!messageForConsole.isEmpty())
        errorMessage = "Uncaught " + messageForConsole;

    rejectedPromises.rejectedWithNoHandler(scriptState, data, errorMessage, std::move(location), corsStatus);
}
void DOMTimer::fired()
{
    ExecutionContext* context = getExecutionContext();
    ASSERT(context);
    context->timers()->setTimerNestingLevel(m_nestingLevel);
    ASSERT(!context->activeDOMObjectsAreSuspended());
    // Only the first execution of a multi-shot timer should get an affirmative user gesture indicator.
    UserGestureIndicator gestureIndicator(m_userGestureToken.release());

    TRACE_EVENT1("devtools.timeline", "TimerFire", "data", InspectorTimerFireEvent::data(context, m_timeoutID));
    InspectorInstrumentationCookie cookie = InspectorInstrumentation::willFireTimer(context, m_timeoutID);

    // Simple case for non-one-shot timers.
    if (isActive()) {
        if (repeatInterval() && repeatInterval() < minimumInterval) {
            m_nestingLevel++;
            if (m_nestingLevel >= maxTimerNestingLevel)
                augmentRepeatInterval(minimumInterval - repeatInterval());
        }

        // No access to member variables after this point, it can delete the timer.
        m_action->execute(context);

        InspectorInstrumentation::didFireTimer(cookie);

        return;
    }

    RawPtr<DOMTimer> protect(this);

    // Unregister the timer from ExecutionContext before executing the action
    // for one-shot timers.
    RawPtr<ScheduledAction> action = m_action.release();
    context->timers()->removeTimeoutByID(m_timeoutID);

    action->execute(context);

    InspectorInstrumentation::didFireTimer(cookie);
    TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "UpdateCounters", TRACE_EVENT_SCOPE_THREAD, "data", InspectorUpdateCountersEvent::data());

    // ExecutionContext might be already gone when we executed action->execute().
    if (getExecutionContext())
        getExecutionContext()->timers()->setTimerNestingLevel(0);
}
Esempio n. 30
0
QString Stringify::JO(Object *o)
{
    if (stack.contains(o)) {
        ctx->throwTypeError();
        return QString();
    }

    Scope scope(ctx);

    QString result;
    stack.push(o);
    QString stepback = indent;
    indent += gap;

    QStringList partial;
    if (propertyList.isEmpty()) {
        ObjectIterator it(scope, o, ObjectIterator::EnumerableOnly);
        ScopedValue name(scope);

        ScopedValue val(scope);
        while (1) {
            name = it.nextPropertyNameAsString(val);
            if (name->isNull())
                break;
            QString key = name->toQString();
            QString member = makeMember(key, val);
            if (!member.isEmpty())
                partial += member;
        }
    } else {
        ScopedString s(scope);
        for (int i = 0; i < propertyList.size(); ++i) {
            bool exists;
            s = propertyList.at(i);
            ScopedValue v(scope, o->get(s.getPointer(), &exists));
            if (!exists)
                continue;
            QString member = makeMember(s->toQString(), v);
            if (!member.isEmpty())
                partial += member;
        }
    }

    if (partial.isEmpty()) {
        result = QStringLiteral("{}");
    } else if (gap.isEmpty()) {
        result = QStringLiteral("{") + partial.join(QLatin1Char(',')) + QStringLiteral("}");
    } else {
        QString separator = QStringLiteral(",\n") + indent;
        result = QStringLiteral("{\n") + indent + partial.join(separator) + QStringLiteral("\n") + stepback + QStringLiteral("}");
    }

    indent = stepback;
    stack.pop();
    return result;
}