Ejemplo n.º 1
0
static void runInteractive(GlobalObject* globalObject)
{
	//abaldeva: Put it here instead of it being static. Otherwise it allocates memory before the 
	//user has a chance to set the allocator.
	const UString interpreterName("Interpreter");

	while (true) {
#if HAVE(READLINE)
        char* line = readline(interactivePrompt);
        if (!line)
            break;
        if (line[0])
            add_history(line);
        Completion completion = Interpreter::evaluate(globalObject->globalExec(), globalObject->globalScopeChain(), interpreterName, 1, line);
        free(line);
#else
        puts(interactivePrompt);
        Vector<char, 256> line;
        int c;
        while ((c = getchar()) != EOF) {
            // FIXME: Should we also break on \r? 
            if (c == '\n')
                break;
            line.append(c);
        }
        line.append('\0');
        Completion completion = Interpreter::evaluate(globalObject->globalExec(), globalObject->globalScopeChain(), interpreterName, 1, line.data());
#endif
        if (completion.isValueCompletion())
            printf("%s\n", completion.value()->toString(globalObject->globalExec()).UTF8String().c_str());
    }
    printf("\n");
}
Ejemplo n.º 2
0
static bool runWithScripts(GlobalObject* globalObject, const Vector<UString>& fileNames, bool prettyPrint, bool dump)
{
    Vector<char> script;

    if (dump)
        CodeGenerator::setDumpsGeneratedCode(true);

    bool success = true;
    for (size_t i = 0; i < fileNames.size(); i++) {
        UString fileName = fileNames[i];

        if (!fillBufferWithContentsOfFile(fileName, script))
            return false; // fail early so we can catch missing files

        if (prettyPrint)
            prettyPrintScript(globalObject->globalExec(), fileName, script);
        else {
            Completion completion = Interpreter::evaluate(globalObject->globalExec(), globalObject->globalScopeChain(), fileName, 1, script.data());
            success = success && completion.complType() != Throw;
            if (dump) {
                if (success)
                    printf("End: %s\n", completion.value()->toString(globalObject->globalExec()).ascii());
                else
                    printf("Exception: %s\n", completion.value()->toString(globalObject->globalExec()).ascii());
            }
        }
    }
    return success;
}
Ejemplo n.º 3
0
JSValueRef JSEvaluateScript(JSContextRef ctx, JSStringRef script, JSObjectRef thisObject, JSStringRef sourceURL, int startingLineNumber, JSValueRef* exception)
{
    ExecState* exec = toJS(ctx);
    exec->globalData().heap.registerThread();
    JSLock lock(exec);

    JSObject* jsThisObject = toJS(thisObject);

    // evaluate sets "this" to the global object if it is NULL
    JSGlobalObject* globalObject = exec->dynamicGlobalObject();
    SourceCode source = makeSource(script->ustring(), sourceURL->ustring(), startingLineNumber);
    Completion completion = evaluate(globalObject->globalExec(), globalObject->globalScopeChain(), source, jsThisObject);

    if (completion.complType() == Throw) {
        if (exception)
            *exception = toRef(completion.value());
        return 0;
    }
    
    if (completion.value())
        return toRef(completion.value());
    
    // happens, for example, when the only statement is an empty (';') statement
    return toRef(jsUndefined());
}
Ejemplo n.º 4
0
bool doIt(int argc, char** argv)
{
  bool success = true;
  bool prettyPrint = false;
  GlobalImp* global = new GlobalImp();

  // create interpreter
  RefPtr<Interpreter> interp = new Interpreter(global);
  // add debug() function
  global->put(interp->globalExec(), "debug", new TestFunctionImp(TestFunctionImp::Debug, 1));
  // add "print" for compatibility with the mozilla js shell
  global->put(interp->globalExec(), "print", new TestFunctionImp(TestFunctionImp::Print, 1));
  // add "quit" for compatibility with the mozilla js shell
  global->put(interp->globalExec(), "quit", new TestFunctionImp(TestFunctionImp::Quit, 0));
  // add "gc" for compatibility with the mozilla js shell
  global->put(interp->globalExec(), "gc", new TestFunctionImp(TestFunctionImp::GC, 0));
  // add "version" for compatibility with the mozilla js shell 
  global->put(interp->globalExec(), "version", new TestFunctionImp(TestFunctionImp::Version, 1));
  global->put(interp->globalExec(), "run", new TestFunctionImp(TestFunctionImp::Run, 1));
  
  Interpreter::setShouldPrintExceptions(true);
  
  for (int i = 1; i < argc; i++) {
    const char* fileName = argv[i];
    if (strcmp(fileName, "-f") == 0) // mozilla test driver script uses "-f" prefix for files
      continue;
    if (strcmp(fileName, "-p") == 0) {
      prettyPrint = true;
      continue;
    }
    
    char* script = createStringWithContentsOfFile(fileName);
    if (!script) {
      success = false;
      break; // fail early so we can catch missing files
    }
    
    if (prettyPrint) {
      int errLine = 0;
      UString errMsg;
      UString s = Parser::prettyPrint(script, &errLine, &errMsg);
      if (s.isNull()) {
        fprintf(stderr, "%s:%d: %s.\n", fileName, errLine, errMsg.UTF8String().c_str());
        success = false;
        free(script);
        break;
      }
      
      printf("%s\n", s.UTF8String().c_str());
      
    } else {
      Completion completion = interp->evaluate(fileName, 0, script);
      success = success && completion.complType() != Throw;
    }
    
    free(script);
  }

  return success;
}
Ejemplo n.º 5
0
ScriptObject InjectedScriptHost::createInjectedScript(const String& source, ScriptState* scriptState, long id)
{
    SourceCode sourceCode = makeSource(stringToUString(source));
    JSLock lock(SilenceAssertionsOnly);
    JSDOMGlobalObject* globalObject = static_cast<JSDOMGlobalObject*>(scriptState->lexicalGlobalObject());
    JSValue globalThisValue = scriptState->globalThisValue();
    Completion comp = JSMainThreadExecState::evaluate(scriptState, globalObject->globalScopeChain(), sourceCode, globalThisValue);
    if (comp.complType() != JSC::Normal && comp.complType() != JSC::ReturnValue)
        return ScriptObject();
    JSValue functionValue = comp.value();
    CallData callData;
    CallType callType = functionValue.getCallData(callData);
    if (callType == CallTypeNone)
        return ScriptObject();

    MarkedArgumentBuffer args;
    args.append(toJS(scriptState, globalObject, this));
    args.append(globalThisValue);
    args.append(jsNumber(scriptState, id));
    args.append(jsString(scriptState, String("JSC")));
    JSValue result = JSC::call(scriptState, functionValue, callType, callData, globalThisValue, args);
    if (result.isObject())
        return ScriptObject(scriptState, result.getObject());
    return ScriptObject();
}
Ejemplo n.º 6
0
Archivo: jsc.cpp Proyecto: dmitris/tpjs
static void runInteractive(GlobalObject* globalObject)
{
    while (true) {
#if HAVE(READLINE) && !RUNNING_FROM_XCODE
        char* line = readline(interactivePrompt);
        if (!line)
            break;
        if (line[0])
            add_history(line);
        Completion completion = evaluate(globalObject->globalExec(), globalObject->globalScopeChain(), makeSource(line, interpreterName));
        free(line);
#else
        printf("%s", interactivePrompt);
        Vector<char, 256> line;
        int c;
        while ((c = getchar()) != EOF) {
            // FIXME: Should we also break on \r? 
            if (c == '\n')
                break;
            line.append(c);
        }
        if (line.isEmpty())
            break;
        line.append('\0');
        Completion completion = evaluate(globalObject->globalExec(), globalObject->globalScopeChain(), makeSource(line.data(), interpreterName));
#endif
        if (completion.complType() == Throw)
            printf("Exception: %s\n", completion.value().toString(globalObject->globalExec()).utf8().data());
        else
            printf("%s\n", completion.value().toString(globalObject->globalExec()).utf8().data());

        globalObject->globalExec()->clearException();
    }
    printf("\n");
}
Ejemplo n.º 7
0
bool _NPN_Evaluate(NPP, NPObject* o, NPString* s, NPVariant* variant)
{
    if (o->_class == NPScriptObjectClass) {
        JavaScriptObject* obj = reinterpret_cast<JavaScriptObject*>(o); 

        RootObject* rootObject = obj->rootObject;
        if (!rootObject || !rootObject->isValid())
            return false;

        ExecState* exec = rootObject->globalObject()->globalExec();
        
        JSLock lock(false);
        String scriptString = convertNPStringToUTF16(s);
        rootObject->globalObject()->startTimeoutCheck();
        Completion completion = Interpreter::evaluate(rootObject->globalObject()->globalExec(), rootObject->globalObject()->globalScopeChain(), UString(), 1, scriptString);
        rootObject->globalObject()->stopTimeoutCheck();
        ComplType type = completion.complType();
        
        JSValue* result;
        if (type == Normal) {
            result = completion.value();
            if (!result)
                result = jsUndefined();
        } else
            result = jsUndefined();

        convertValueToNPVariant(exec, result, variant);
        exec->clearException();
        return true;
    }

    VOID_TO_NPVARIANT(*variant);
    return false;
}
Ejemplo n.º 8
0
void
TestHasPrefix(const _Fragment& aFragment, bool aExpectedHas, bool aExpectedComplete)
{
  _PrefixArray array = { GeneratePrefix(_Fragment("bravo.com/"), 32),
                         GeneratePrefix(_Fragment("browsing.com/"), 8),
                         GeneratePrefix(_Fragment("gound.com/"), 5),
                         GeneratePrefix(_Fragment("small.com/"), 4)
                       };

  RunTestInNewThread([&] () -> void {
    UniquePtr<LookupCache> cache = SetupLookupCache<LookupCacheV4>(array);

    Completion lookupHash;
    lookupHash.FromPlaintext(aFragment);

    bool has, confirmed;
    uint32_t matchLength;
    // Freshness is not used in V4 so we just put dummy values here.
    TableFreshnessMap dummy;
    nsresult rv =
      cache->Has(lookupHash, &has, &matchLength, &confirmed);

    EXPECT_EQ(rv, NS_OK);
    EXPECT_EQ(has, aExpectedHas);
    EXPECT_EQ(matchLength == COMPLETE_SIZE, aExpectedComplete);
    EXPECT_EQ(confirmed, false);

    cache->ClearAll();
  });

}
Ejemplo n.º 9
0
void
TestCache(const Completion aCompletion,
          bool aExpectedHas,
          bool aExpectedConfirmed,
          bool aExpectedInCache,
          T* aCache = nullptr)
{
  bool has, inCache, confirmed;
  uint32_t matchLength;

  if (aCache) {
    aCache->Has(aCompletion, &has, &matchLength, &confirmed);
    inCache = aCache->IsInCache(aCompletion.ToUint32());
  } else {
    _PrefixArray array = { GeneratePrefix(_Fragment("cache.notexpired.com/"), 10),
                           GeneratePrefix(_Fragment("cache.expired.com/"), 8),
                           GeneratePrefix(_Fragment("gound.com/"), 5),
                           GeneratePrefix(_Fragment("small.com/"), 4)
                         };

    UniquePtr<T> cache = SetupLookupCache<T>(array);

    // Create an expired entry and a non-expired entry
    SetupCacheEntry(cache.get(), _Fragment("cache.notexpired.com/"));
    SetupCacheEntry(cache.get(), _Fragment("cache.expired.com/"), true, true);

    cache->Has(aCompletion, &has, &matchLength, &confirmed);
    inCache = cache->IsInCache(aCompletion.ToUint32());
  }

  EXPECT_EQ(has, aExpectedHas);
  EXPECT_EQ(confirmed, aExpectedConfirmed);
  EXPECT_EQ(inCache, aExpectedInCache);
}
Ejemplo n.º 10
0
/*
    JSRunEvaluate
*/
JSObjectRef JSRunEvaluate(JSRunRef ref)
{
    JSObjectRef result = 0;
    JSRun* ptr = (JSRun*)ref;
    if (ptr)
    {
        Completion completion = ptr->Evaluate();
        if (completion.isValueCompletion())
        {
            result = (JSObjectRef)KJSValueToJSObject(completion.value(), ptr->GetInterpreter()->globalExec());
        }

        if (completion.complType() == Throw)
        {
            JSFlags flags = ptr->Flags();
            if (flags & kJSFlagDebug)
            {
                CFTypeRef error = JSObjectCopyCFValue(result);
                if (error)
                {
                    CFShow(error);
                    CFRelease(error);
                }
            }
        }
    }
    return result;
}
Ejemplo n.º 11
0
void
TestHasPrefix(const _Fragment& aFragment, bool aExpectedHas, bool aExpectedComplete)
{
  _PrefixArray array = { GeneratePrefix(_Fragment("bravo.com/"), 32),
                         GeneratePrefix(_Fragment("browsing.com/"), 8),
                         GeneratePrefix(_Fragment("gound.com/"), 5),
                         GeneratePrefix(_Fragment("small.com/"), 4)
                       };

  RunTestInNewThread([&] () -> void {
    UniquePtr<LookupCache> cache = SetupLookupCacheV4(array);

    Completion lookupHash;
    nsCOMPtr<nsICryptoHash> cryptoHash = do_CreateInstance(NS_CRYPTO_HASH_CONTRACTID);
    lookupHash.FromPlaintext(aFragment, cryptoHash);

    bool has, complete;
    nsresult rv = cache->Has(lookupHash, &has, &complete);

    EXPECT_EQ(rv, NS_OK);
    EXPECT_EQ(has, aExpectedHas);
    EXPECT_EQ(complete, aExpectedComplete);

    cache->ClearAll();
  });

}
Ejemplo n.º 12
0
bool NPRuntimeObjectMap::evaluate(NPObject* npObject, const String&scriptString, NPVariant* result)
{
    Global<JSGlobalObject> globalObject(this->globalObject()->globalData(), this->globalObject());
    if (!globalObject)
        return false;

    ExecState* exec = globalObject->globalExec();
    
    JSLock lock(SilenceAssertionsOnly);
    JSValue thisValue = getOrCreateJSObject(globalObject.get(), npObject);

    globalObject->globalData().timeoutChecker.start();
    Completion completion = JSC::evaluate(exec, globalObject->globalScopeChain(), makeSource(UString(scriptString.impl())), thisValue);
    globalObject->globalData().timeoutChecker.stop();

    ComplType completionType = completion.complType();

    JSValue resultValue;
    if (completionType == Normal) {
        resultValue = completion.value();
        if (!resultValue)
            resultValue = jsUndefined();
    } else
        resultValue = jsUndefined();

    exec->clearException();
    
    convertJSValueToNPVariant(exec, resultValue, *result);
    return true;
}
ScriptValue WorkerScriptController::evaluate(const ScriptSourceCode& sourceCode, ScriptValue* exception)
{
    if (isExecutionForbidden())
        return ScriptValue();

    initScriptIfNeeded();
    JSLock lock(SilenceAssertionsOnly);

    ExecState* exec = m_workerContextWrapper->globalExec();
    m_workerContextWrapper->globalData().timeoutChecker.start();
    Completion comp = JSC::evaluate(exec, exec->dynamicGlobalObject()->globalScopeChain(), sourceCode.jsSourceCode(), m_workerContextWrapper.get());
    m_workerContextWrapper->globalData().timeoutChecker.stop();


    ComplType completionType = comp.complType();

    if (completionType == Terminated || m_workerContextWrapper->globalData().terminator.shouldTerminate()) {
        forbidExecution();
        return ScriptValue();
    }

    if (completionType == JSC::Normal || completionType == ReturnValue)
        return ScriptValue(*m_globalData, comp.value());

    if (completionType == Throw) {
        String errorMessage;
        int lineNumber = 0;
        String sourceURL = sourceCode.url().string();
        if (m_workerContext->sanitizeScriptError(errorMessage, lineNumber, sourceURL))
            *exception = ScriptValue(*m_globalData, throwError(exec, createError(exec, errorMessage.impl())));
        else
            *exception = ScriptValue(*m_globalData, comp.value());
    }
    return ScriptValue();
}
Ejemplo n.º 14
0
static void runInteractive(GlobalObject* globalObject)
{
    while (true) {
#if HAVE(READLINE)
        char* line = readline(interactivePrompt);
        if (!line)
            break;
        if (line[0])
            add_history(line);
        Completion completion = Interpreter::evaluate(globalObject->globalExec(), globalObject->globalScopeChain(), interpreterName, 1, line);
        free(line);
#else
        puts(interactivePrompt);
        Vector<char, 256> line;
        int c;
        while ((c = getchar()) != EOF) {
            // FIXME: Should we also break on \r? 
            if (c == '\n')
                break;
            line.append(c);
        }
        line.append('\0');
        Completion completion = Interpreter::evaluate(globalObject->globalExec(), globalObject->globalScopeChain(), interpreterName, 1, line.data());
#endif
        if (completion.complType() == Throw)
            printf("Exception: %s\n", completion.value()->toString(globalObject->globalExec()).ascii());
        else
            printf("%s\n", completion.value()->toString(globalObject->globalExec()).UTF8String().c_str());

        globalObject->globalExec()->clearException();
    }
    printf("\n");
}
Ejemplo n.º 15
0
bool _NPN_Evaluate(NPP, NPObject* o, NPString* s, NPVariant* variant)
{
    if (o->_class == NPScriptObjectClass) {
        JavaScriptObject* obj = reinterpret_cast<JavaScriptObject*>(o); 

        RootObject* rootObject = obj->rootObject;
        if (!rootObject || !rootObject->isValid())
            return false;

        ExecState* exec = rootObject->globalObject()->globalExec();
        JSLock lock(SilenceAssertionsOnly);
        String scriptString = convertNPStringToUTF16(s);
        ProtectedPtr<JSGlobalObject> globalObject = rootObject->globalObject();
        globalObject->globalData()->timeoutChecker.start();
        Completion completion = JSC::evaluate(globalObject->globalExec(), globalObject->globalScopeChain(), makeSource(scriptString), JSC::JSValue());
        globalObject->globalData()->timeoutChecker.stop();
        ComplType type = completion.complType();
        
        JSValue result;
        if (type == Normal) {
            result = completion.value();
            if (!result)
                result = jsUndefined();
        } else
            result = jsUndefined();

        convertValueToNPVariant(exec, result, variant);
        exec->clearException();
        return true;
    }

    VOID_TO_NPVARIANT(*variant);
    return false;
}
Ejemplo n.º 16
0
Completion DeclaredFunctionImp::execute(ExecState *exec)
{
  Completion result = body->execute(exec);

  if (result.complType() == Throw || result.complType() == ReturnValue)
      return result;
  return Completion(Normal, Undefined()); // TODO: or ReturnValue ?
}
Ejemplo n.º 17
0
Archivo: jsc.cpp Proyecto: dmitris/tpjs
static bool runWithScripts(GlobalObject* globalObject, const Vector<Script>& scripts, bool dump)
{
    UString script;
    UString fileName;
    Vector<char> scriptBuffer;

    if (dump)
        BytecodeGenerator::setDumpsGeneratedCode(true);

    JSGlobalData& globalData = globalObject->globalData();

#if ENABLE(SAMPLING_FLAGS)
    SamplingFlags::start();
#endif

    bool success = true;
    for (size_t i = 0; i < scripts.size(); i++) {
        if (scripts[i].isFile) {
            fileName = scripts[i].argument;
            if (!fillBufferWithContentsOfFile(fileName, scriptBuffer))
                return false; // fail early so we can catch missing files
            script = scriptBuffer.data();
        } else {
            script = scripts[i].argument;
            fileName = "[Command Line]";
        }

        globalData.startSampling();

        Completion completion = evaluate(globalObject->globalExec(), globalObject->globalScopeChain(), makeSource(script, fileName));
        success = success && completion.complType() != Throw;
        if (dump) {
            if (completion.complType() == Throw)
                printf("Exception: %s\n", completion.value().toString(globalObject->globalExec()).utf8().data());
            else
                printf("End: %s\n", completion.value().toString(globalObject->globalExec()).utf8().data());
        }

        globalData.stopSampling();
        globalObject->globalExec()->clearException();
    }

#if ENABLE(SAMPLING_FLAGS)
    SamplingFlags::stop();
#endif
    globalData.dumpSampleData(globalObject->globalExec());
#if ENABLE(SAMPLING_COUNTERS)
    AbstractSamplingCounter::dump();
#endif
#if ENABLE(REGEXP_TRACING)
    globalData.dumpRegExpTrace();
#endif
    return success;
}
Ejemplo n.º 18
0
// Generate a hash prefix from string
static const nsCString
GeneratePrefix(const _Fragment& aFragment, uint8_t aLength)
{
  Completion complete;
  nsCOMPtr<nsICryptoHash> cryptoHash = do_CreateInstance(NS_CRYPTO_HASH_CONTRACTID);
  complete.FromPlaintext(aFragment, cryptoHash);

  nsCString hash;
  hash.Assign((const char *)complete.buf, aLength);
  return hash;
}
Ejemplo n.º 19
0
void
TestCache(const _Fragment& aFragment,
          bool aExpectedHas,
          bool aExpectedConfirmed,
          bool aExpectedInCache,
          T* aCache = nullptr)
{
  Completion lookupHash;
  lookupHash.FromPlaintext(aFragment);

  TestCache<T>(lookupHash, aExpectedHas, aExpectedConfirmed, aExpectedInCache, aCache);
}
Ejemplo n.º 20
0
Archivo: jsc.cpp Proyecto: dmitris/tpjs
EncodedJSValue JSC_HOST_CALL functionLoad(ExecState* exec)
{
    UString fileName = exec->argument(0).toString(exec);
    Vector<char> script;
    if (!fillBufferWithContentsOfFile(fileName, script))
        return JSValue::encode(throwError(exec, createError(exec, "Could not open file.")));

    JSGlobalObject* globalObject = exec->lexicalGlobalObject();
    Completion result = evaluate(globalObject->globalExec(), globalObject->globalScopeChain(), makeSource(script.data(), fileName));
    if (result.complType() == Throw)
        throwError(exec, result.value());
    return JSValue::encode(result.value());
}
Ejemplo n.º 21
0
JSValue* KJSProxy::evaluate(const String& filename, int baseLine, const String& str, Node* n) 
{
    // evaluate code. Returns the JS return value or 0
    // if there was none, an error occured or the type couldn't be converted.

    initScriptIfNeeded();
    // inlineCode is true for <a href="javascript:doSomething()">
    // and false for <script>doSomething()</script>. Check if it has the
    // expected value in all cases.
    // See smart window.open policy for where this is used.
    bool inlineCode = filename.isNull();

    m_script->setInlineCode(inlineCode);

    JSLock lock;

    JSValue* thisNode = n ? Window::retrieve(m_frame) : toJS(m_script->globalExec(), n);
  
    m_script->startTimeoutCheck();
    Completion comp = m_script->evaluate(filename, baseLine, reinterpret_cast<const KJS::UChar*>(str.characters()), str.length(), thisNode);
    m_script->stopTimeoutCheck();
  
    if (comp.complType() == Normal || comp.complType() == ReturnValue)
        return comp.value();

    if (comp.complType() == Throw) {
        UString errorMessage = comp.value()->toString(m_script->globalExec());
        int lineNumber = comp.value()->toObject(m_script->globalExec())->get(m_script->globalExec(), "line")->toInt32(m_script->globalExec());
        UString sourceURL = comp.value()->toObject(m_script->globalExec())->get(m_script->globalExec(), "sourceURL")->toString(m_script->globalExec());
        if (Page* page = m_frame->page())
            page->chrome()->addMessageToConsole(errorMessage, lineNumber, sourceURL);
    }

    return 0;
}
Ejemplo n.º 22
0
AJValue JSC_HOST_CALL functionCheckSyntax(ExecState* exec, AJObject* o, AJValue v, const ArgList& args)
{
    UNUSED_PARAM(o);
    UNUSED_PARAM(v);
    UString fileName = args.at(0).toString(exec);
    Vector<char> script;
    if (!fillBufferWithContentsOfFile(fileName, script))
        return throwError(exec, GeneralError, "Could not open file.");

    AJGlobalObject* globalObject = exec->lexicalGlobalObject();
    Completion result = checkSyntax(globalObject->globalExec(), makeSource(script.data(), fileName));
    if (result.complType() == Throw)
        exec->setException(result.value());
    return result.value();
}
Ejemplo n.º 23
0
// This testcase check the returned result of |Has| API if fullhash matches
// a cache entry in negative cache but that entry is expired.
TEST(UrlClassifierCaching, InNegativeCacheExpired)
{
  // Create a fullhash whose prefix is in the cache.

  Completion prefix;
  prefix.FromPlaintext(_Fragment("cache.expired.com/"));

  Completion fullhash;
  fullhash.FromPlaintext(_Fragment("firefox.com/"));

  memcpy(fullhash.buf, prefix.buf, 10);

  TestCache<LookupCacheV2>(fullhash, true, false, true);
  TestCache<LookupCacheV4>(fullhash, true, false, true);
}
Ejemplo n.º 24
0
bool JSCheckScriptSyntax(JSContextRef ctx, JSStringRef script, JSStringRef sourceURL, int startingLineNumber, JSValueRef* exception)
{
    JSLock lock;

    ExecState* exec = toJS(ctx);
    UString::Rep* scriptRep = toJS(script);
    UString::Rep* sourceURLRep = sourceURL ? toJS(sourceURL) : &UString::Rep::null;
    Completion completion = Interpreter::checkSyntax(exec->dynamicGlobalObject()->globalExec(), UString(sourceURLRep), startingLineNumber, UString(scriptRep));
    if (completion.complType() == Throw) {
        if (exception)
            *exception = toRef(completion.value());
        return false;
    }
    
    return true;
}
Ejemplo n.º 25
0
nsresult
LookupCache::Has(const Completion& aCompletion,
                 bool* aHas, bool* aComplete)
{
  *aHas = *aComplete = false;

  uint32_t prefix = aCompletion.ToUint32();

  bool found;
  nsresult rv = mPrefixSet->Contains(prefix, &found);
  NS_ENSURE_SUCCESS(rv, rv);

  LOG(("Probe in %s: %X, found %d", mTableName.get(), prefix, found));

  if (found) {
    *aHas = true;
  }

  if (mCompletions.BinaryIndexOf(aCompletion) != nsTArray<Completion>::NoIndex) {
    LOG(("Complete in %s", mTableName.get()));
    *aComplete = true;
    *aHas = true;
  }

  return NS_OK;
}
Ejemplo n.º 26
0
bool JSCheckScriptSyntax(JSContextRef ctx, JSStringRef script, JSStringRef sourceURL, int startingLineNumber, JSValueRef* exception)
{
    ExecState* exec = toJS(ctx);
    exec->globalData().heap.registerThread();
    JSLock lock(exec);

    SourceCode source = makeSource(script->ustring(), sourceURL->ustring(), startingLineNumber);
    Completion completion = checkSyntax(exec->dynamicGlobalObject()->globalExec(), source);
    if (completion.complType() == Throw) {
        if (exception)
            *exception = toRef(completion.value());
        return false;
    }
    
    return true;
}
Ejemplo n.º 27
0
QVariant KJSProxyImpl::evaluate(QString filename, int baseLine,
                                const QString&str, const DOM::Node &n, Completion *completion) {
  // evaluate code. Returns the JS return value or an invalid QVariant
  // if there was none, an error occured or the type couldn't be converted.

  initScript();
  // inlineCode is true for <a href="javascript:doSomething()">
  // and false for <script>doSomething()</script>. Check if it has the
  // expected value in all cases.
  // See smart window.open policy for where this is used.
  bool inlineCode = filename.isNull();
  //kdDebug(6070) << "KJSProxyImpl::evaluate inlineCode=" << inlineCode << endl;

#ifdef KJS_DEBUGGER
  if (inlineCode)
    filename = "(unknown file)";
  if (KJSDebugWin::instance()) {
    KJSDebugWin::instance()->attach(m_script);
    KJSDebugWin::instance()->setNextSourceInfo(filename,baseLine);
  //    KJSDebugWin::instance()->setMode(KJSDebugWin::Step);
  }
#else
  Q_UNUSED(baseLine);
#endif

  m_script->setInlineCode(inlineCode);
  Window* window = Window::retrieveWindow( m_part );
  KJS::Value thisNode = n.isNull() ? Window::retrieve( m_part ) : getDOMNode(m_script->globalExec(),n);

  UString code( str );

  KJSCPUGuard guard;
  guard.start();
  Completion comp = m_script->evaluate(code, thisNode);
  guard.stop();

  bool success = ( comp.complType() == Normal ) || ( comp.complType() == ReturnValue );

  if (completion)
    *completion = comp;

#ifdef KJS_DEBUGGER
    //    KJSDebugWin::instance()->setCode(QString::null);
#endif

  window->afterScriptExecution();

  // let's try to convert the return value
  if (success && !comp.value().isNull())
    return ValueToVariant( m_script->globalExec(), comp.value());
  else
  {
    if ( comp.complType() == Throw )
    {
        UString msg = comp.value().toString(m_script->globalExec());
        kdWarning(6070) << "Script threw exception: " << msg.qstring() << endl;
    }
    return QVariant();
  }
}
Ejemplo n.º 28
0
Archivo: kjs.cpp Proyecto: KDE/kjs
static ExitCode evaluateString(Interpreter *interp, const char *fileName,
                               const UString &code,
                               bool printResult = false)
{
    ExecState *exec = interp->globalExec();

    Completion res = interp->evaluate(fileName, 0, code);

    if (res.complType() == Throw) {
        CString msg = res.value()->toString(exec).UTF8String();
        JSObject *resObj = res.value()->toObject(exec);
        CString message = resObj->toString(exec).UTF8String();
        int line = resObj->toObject(exec)->get(exec, "line")->toUInt32(exec);

        if (fileName) {
            fprintf(stderr, "%s (line %d): ", fileName, line);
        }
        fprintf(stderr, "%s\n", msg.c_str());
        return ErrorEval;
    } else if (printResult) {
        if (res.isValueCompletion() && !res.value()->isUndefined()) {
            CString s8 = res.value()->toString(exec).UTF8String();
            if (s8.size() != 0) {
                fprintf(stdout, "%s\n", s8.c_str());
            }
        }
    }

    return ErrorNone;
}
Ejemplo n.º 29
0
Archivo: jsc.cpp Proyecto: dmitris/tpjs
EncodedJSValue JSC_HOST_CALL functionCheckSyntax(ExecState* exec)
{
    UString fileName = exec->argument(0).toString(exec);
    Vector<char> script;
    if (!fillBufferWithContentsOfFile(fileName, script))
        return JSValue::encode(throwError(exec, createError(exec, "Could not open file.")));

    JSGlobalObject* globalObject = exec->lexicalGlobalObject();

    StopWatch stopWatch;
    stopWatch.start();
    Completion result = checkSyntax(globalObject->globalExec(), makeSource(script.data(), fileName));
    stopWatch.stop();

    if (result.complType() == Throw)
        throwError(exec, result.value());
    return JSValue::encode(jsNumber(stopWatch.getElapsedMS()));
}
Ejemplo n.º 30
0
Archivo: jsc.cpp Proyecto: Fale/qtmoko
static bool runWithScripts(GlobalObject* globalObject, const Vector<UString>& fileNames, bool dump)
{
    Vector<char> script;

    if (dump)
        BytecodeGenerator::setDumpsGeneratedCode(true);

#if ENABLE(OPCODE_SAMPLING)
    Interpreter* interpreter = globalObject->globalData()->interpreter;
    interpreter->setSampler(new SamplingTool(interpreter));
#endif

    bool success = true;
    for (size_t i = 0; i < fileNames.size(); i++) {
        UString fileName = fileNames[i];

        if (!fillBufferWithContentsOfFile(fileName, script))
            return false; // fail early so we can catch missing files

#if ENABLE(OPCODE_SAMPLING)
        interpreter->sampler()->start();
#endif
        Completion completion = evaluate(globalObject->globalExec(), globalObject->globalScopeChain(), makeSource(script.data(), fileName));
        success = success && completion.complType() != Throw;
        if (dump) {
            if (completion.complType() == Throw)
                printf("Exception: %s\n", completion.value()->toString(globalObject->globalExec()).ascii());
            else
                printf("End: %s\n", completion.value()->toString(globalObject->globalExec()).ascii());
        }

        globalObject->globalExec()->clearException();

#if ENABLE(OPCODE_SAMPLING)
        interpreter->sampler()->stop();
#endif
    }

#if ENABLE(OPCODE_SAMPLING)
    interpreter->sampler()->dump(globalObject->globalExec());
    delete interpreter->sampler();
#endif
    return success;
}