QString collectVerbatimText(QTextStream& stream)
{
    QString result;
    QString line;
    methodName(QLatin1String("collectVerbatimText"));
    while (!(line = stream.readLine()).isNull()) {
        linum++;
        line = line.trimmed();
        if (line.isEmpty() || line.startsWith(QLatin1Char(')')))
            break;
        if (line[0] != QLatin1Char('|')) {
            uError() << loc() << "expecting '|' at start of verbatim text";
            return QString();
        } else {
            result += line.mid(1) + QLatin1Char('\n');
        }
    }
    if (line.isNull()) {
        uError() << loc() << "premature EOF";
        return QString();
    }
    if (! line.isEmpty()) {
        for (int i = 0; i < line.length(); ++i) {
            const QChar& clParenth = line[i];
            if (clParenth != QLatin1Char(')')) {
                uError() << loc() << "expected ')', found: " << clParenth;
                return QString();
            }
            nClosures++;
        }
    }
    return result;
}
Example #2
0
	void UIBinding::Log(Logger::Level level, std::string& message)
	{
		if (level > Logger::LWARN)
			return;

		std::string methodName("warn");
		if (level < Logger::LWARN)
			methodName = "error";

		std::string origMethodName(methodName);
		origMethodName.append("_orig");

		std::vector<AutoUserWindow>& openWindows = UIBinding::GetInstance()->GetOpenWindows();
		for (size_t i = 0; i < openWindows.size(); i++)
		{
			KObjectRef domWindow = openWindows[i]->GetDOMWindow();
			if (domWindow.isNull())
				continue;

			KObjectRef console = domWindow->GetObject("console", 0);
			if (console.isNull())
				continue;

			KMethodRef method = console->GetMethod(origMethodName.c_str(), 0);
			if (method.isNull())
				method = console->GetMethod(methodName.c_str(), 0);

			RunOnMainThread(method, ValueList(Value::NewString(message)), false);
		}
	}
Example #3
0
static void failedMockCallAfterOneSuccess()
{
	myMock mock;
	EXPECT_CALL(mock, methodName()).Times(2).WillRepeatedly(Return(1));

	mock.methodName();
}
Example #4
0
QString CallInstruction::toString() const
{
    return QString("%1: %2.%3(...)")
            .arg(instructionId())
            .arg(instanceName())
            .arg(methodName());
}
Example #5
0
/*static*/ v8::Handle<v8::Value> JavaObject::methodCallSync(const v8::Arguments& args) {
  v8::HandleScope scope;
  JavaObject* self = node::ObjectWrap::Unwrap<JavaObject>(args.This());
  JNIEnv *env = self->m_java->getJavaEnv();
  JavaScope javaScope(env);

  v8::String::AsciiValue methodName(args.Data());
  std::string methodNameStr = *methodName;

  int argsStart = 0;
  int argsEnd = args.Length();

  jobjectArray methodArgs = v8ToJava(env, args, argsStart, argsEnd);

  jobject method = javaFindMethod(env, self->m_class, methodNameStr, methodArgs);
  if(method == NULL) {
    std::string msg = methodNotFoundToString(env, self->m_class, methodNameStr, false, args, argsStart, argsEnd);
    v8::Handle<v8::Value> ex = javaExceptionToV8(env, msg);
    return ThrowException(ex);
  }

  // run
  v8::Handle<v8::Value> callback = v8::Undefined();
  InstanceMethodCallBaton* baton = new InstanceMethodCallBaton(self->m_java, self, method, methodArgs, callback);
  v8::Handle<v8::Value> result = baton->runSync();
  delete baton;

  if(result->IsNativeError()) {
    return ThrowException(result);
  }

  return scope.Close(result);
}
Example #6
0
/*static*/ v8::Handle<v8::Value> JavaObject::methodCall(const v8::Arguments& args) {
  v8::HandleScope scope;
  JavaObject* self = node::ObjectWrap::Unwrap<JavaObject>(args.This());
  JNIEnv *env = self->m_java->getJavaEnv();
  JavaScope javaScope(env);

  v8::String::AsciiValue methodName(args.Data());
  std::string methodNameStr = *methodName;

  int argsStart = 0;
  int argsEnd = args.Length();

  // arguments
  ARGS_BACK_CALLBACK();

  if(!callbackProvided && methodNameStr == "toString") {
    return methodCallSync(args);
  }

  jobjectArray methodArgs = v8ToJava(env, args, argsStart, argsEnd);

  jobject method = javaFindMethod(env, self->m_class, methodNameStr, methodArgs);
  if(method == NULL) {
    std::string msg = methodNotFoundToString(env, self->m_class, methodNameStr, false, args, argsStart, argsEnd);
    EXCEPTION_CALL_CALLBACK(msg);
    return v8::Undefined();
  }

  // run
  InstanceMethodCallBaton* baton = new InstanceMethodCallBaton(self->m_java, self, method, methodArgs, callback);
  baton->run();

  END_CALLBACK_FUNCTION("\"Method '" << methodNameStr << "' called without a callback did you mean to use the Sync version?\"");
}
Example #7
0
/**
 * TJSオブジェクトのオーバライド処理
 * @param args 引数
 * @return 結果
 */
void
TJSInstance::tjsOverride(const FunctionCallbackInfo<Value>& args)
{
	Isolate *isolate = args.GetIsolate();
	HandleScope handle_scope(isolate);
	tTJSVariant instance;
	if (getVariant(isolate, instance, args.This())) {
		if (args.Length() > 0) {
			Local<Value> func = args.Length() > 1 ? args[1] : args.This()->Get(args[0]);
			if (func->IsFunction()) {
				tTJSVariant value = toVariant(isolate, func->ToObject(), args.This());
				String::Value methodName(args[0]);
				tjs_error error;
				if (TJS_FAILED(error = instance.AsObjectClosureNoAddRef().PropSet(TJS_MEMBERENSURE, *methodName, NULL, &value, NULL))) {
					args.GetReturnValue().Set(ERROR_KRKR(isolate, error));
					return;
				}
				args.GetReturnValue().Set(Undefined(isolate));
				return;
			}
		}
		args.GetReturnValue().Set(isolate->ThrowException(String::NewFromUtf8(isolate, "not function")));
		return;
	}
	args.GetReturnValue().Set(ERROR_BADINSTANCE(isolate));
}
/**
 * Extract the stripped down value from a (value ...) element.
 * Example: for the input
 *            (value Text "This is some text")
 *          the following is extracted:
 *            "This is some text"
 * Extracted elements and syntactic sugar of the value element are
 * removed from the input list.
 * The stream is passed into this method because it may be necessary
 * to read new lines - in the case of verbatim text.
 * The format of verbatim text in petal files is as follows:
 *
 *         (value Text
 * |This is the first line of verbatim text.
 * |This is another line of verbatim text.
 *        )
 * (The '|' character is supposed to be in the first column of the line)
 * In this case the two lines are extracted without the leading '|'.
 * The line ending '\n' of each line is preserved.
 */
QString extractValue(QStringList& l, QTextStream& stream)
{
    methodName(QLatin1String("extractValue"));
    if (l.count() == 0)
        return QString();
    if (l.first() == QLatin1String("("))
        l.pop_front();
    if (l.first() != QLatin1String("value"))
        return QString();
    l.pop_front();  // remove "value"
    l.pop_front();  // remove the value type: could be e.g. "Text" or "cardinality"
    QString result;
    if (l.count() == 0) {  // expect verbatim text to follow on subsequent lines
        QString text = collectVerbatimText(stream);
        nClosures--;  // expect own closure
        return text;
    } else {
        result = shift(l);
        if (l.first() != QLatin1String(")")) {
            uError() << loc() << "expecting closing parenthesis";
            return result;
        }
        l.pop_front();
    }
    while (l.count() && l.first() == QLatin1String(")")) {
        nClosures++;
        l.pop_front();
    }
    return result;
}
Example #9
0
ScriptValue PaymentResponse::toJSONForBinding(ScriptState* scriptState) const {
  V8ObjectBuilder result(scriptState);
  result.addString("methodName", methodName());
  result.add("details", details(scriptState, ASSERT_NO_EXCEPTION));

  if (shippingAddress())
    result.add("shippingAddress",
               shippingAddress()->toJSONForBinding(scriptState));
  else
    result.addNull("shippingAddress");

  if (shippingOption().isNull())
    result.addNull("shippingOption");
  else
    result.addString("shippingOption", shippingOption());

  if (payerEmail().isNull())
    result.addNull("payerEmail");
  else
    result.addString("payerEmail", payerEmail());

  if (payerPhone().isNull())
    result.addNull("payerPhone");
  else
    result.addString("payerPhone", payerPhone());

  return result.scriptValue();
}
Example #10
0
string JavaMethodInfo::getFQN(){
  string methodName(getClass()->getName());
  methodName+="#";
  methodName+=getName();
  methodName+=getSignature();
  
  return methodName;
}
Example #11
0
void Dictionary::ConversionContext::throwTypeError(const String& detail)
{
    if (forConstructor()) {
        exceptionState().throwTypeError(detail);
    } else {
        ASSERT(!methodName().isEmpty());
        exceptionState().throwTypeError(ExceptionMessages::failedToExecute(interfaceName(), methodName(), detail));
    }
}
Example #12
0
static bool isDecorator(PyObject* method, PyObject* self)
{
    Shiboken::AutoDecRef methodName(PyObject_GetAttrString(method, "__name__"));
    if (!PyObject_HasAttr(self, methodName))
        return true;
    Shiboken::AutoDecRef otherMethod(PyObject_GetAttr(self, methodName));
    return reinterpret_cast<PyMethodObject*>(otherMethod.object())->im_func != \
           reinterpret_cast<PyMethodObject*>(method)->im_func;
}
Example #13
0
bool Profiler::lookupFrameInformation(const JVMPI_CallFrame &frame,
        jvmtiEnv *jvmti,
        MethodListener &logWriter) {
    jint error;
    JvmtiScopedPtr<char> methodName(jvmti);

    error = jvmti->GetMethodName(frame.method_id, methodName.GetRef(), NULL, NULL);
    if (error != JVMTI_ERROR_NONE) {
        methodName.AbandonBecauseOfError();
        if (error == JVMTI_ERROR_INVALID_METHODID) {
            static int once = 0;
            if (!once) {
                once = 1;
                logError("One of your monitoring interfaces "
                         "is having trouble resolving its stack traces.  "
                         "GetMethodName on a jmethodID involved in a stacktrace "
                         "resulted in an INVALID_METHODID error which usually "
                         "indicates its declaring class has been unloaded.\n");
                logError("Unexpected JVMTI error %d in GetMethodName\n", error);
            }
        }
        return false;
    }

    // Get class name, put it in signature_ptr
    jclass declaring_class;
    JVMTI_ERROR_1(
            jvmti->GetMethodDeclaringClass(frame.method_id, &declaring_class), false);

    JvmtiScopedPtr<char> signature_ptr2(jvmti);
    JVMTI_ERROR_CLEANUP_1(
            jvmti->GetClassSignature(declaring_class, signature_ptr2.GetRef(), NULL),
            false, signature_ptr2.AbandonBecauseOfError());

    // Get source file, put it in source_name_ptr
    char *fileName;
    JvmtiScopedPtr<char> source_name_ptr(jvmti);
    static char file_unknown[] = "UnknownFile";
    if (JVMTI_ERROR_NONE !=
            jvmti->GetSourceFileName(declaring_class, source_name_ptr.GetRef())) {
        source_name_ptr.AbandonBecauseOfError();
        fileName = file_unknown;
    } else {
        fileName = source_name_ptr.Get();
    }

    logWriter.recordNewMethod((method_id) frame.method_id, fileName,
            signature_ptr2.Get(), methodName.Get());

    return true;
    /*if (line_number != NULL) {
      // TODO: is frame.lineno correct?  GetLineNumber
      // expects a BCI.
      *line_number = GetLineNumber(frame.method_id, frame.lineno);
    }*/
}
Example #14
0
    /*!
        \relates QxtMetaObject

        Invokes the \a member (a signal or a slot name) on the \a object.
        Returns \c true if the member could be invoked. Returns \c false
        if there is no such member or the parameters did not match.

        \sa QMetaObject::invokeMethod()
     */
    bool invokeMethod(QObject* object, const char* member, Qt::ConnectionType type,
                      const QVariant& arg0, const QVariant& arg1, const QVariant& arg2,
                      const QVariant& arg3, const QVariant& arg4, const QVariant& arg5,
                      const QVariant& arg6, const QVariant& arg7, const QVariant& arg8, const QVariant& arg9)
    {
        #define QXT_MO_ARG(i) QGenericArgument(arg ## i.typeName(), arg ## i.constData())
        return QMetaObject::invokeMethod(object, methodName(member), type,
                                         QXT_MO_ARG(0), QXT_MO_ARG(1), QXT_MO_ARG(2), QXT_MO_ARG(3), QXT_MO_ARG(4),
                                         QXT_MO_ARG(5), QXT_MO_ARG(6), QXT_MO_ARG(7), QXT_MO_ARG(8), QXT_MO_ARG(9));
    }
Example #15
0
int testCompetition2Stage ()
{
    TString trainingFileName ("training");
    //auto resultPre = TMVAClassification (trainingFileName, AnalysisType::DIRECT);
    std::string fileName ("NNPG20150826_0714");
    std::string methodName ("NNPG20150826_0714");
    auto interRootFileName = TMVAPredict (fileName, EnumPredictMode::INTERMEDIATE);
    auto tonbkgResult = TMVAClassification (trainingFileName, AnalysisType::BACKGROUND, interRootFileName);
    TMVAPredict (tonbkgResult.second, EnumPredictMode::FINAL);

    return 0;
}
Example #16
0
LastfmService::Result LastfmService::fetch(Args &args)
{
	Result result;
	
	std::string url = baseURL;
	url += methodName();
	for (Args::const_iterator it = args.begin(); it != args.end(); ++it)
	{
		url += "&";
		url += it->first;
		url += "=";
		url += Curl::escape(it->second);
	}
	
	std::string data;
	CURLcode code = Curl::perform(data, url);
	
	if (code != CURLE_OK)
	{
		result.second = curl_easy_strerror(code);
		return result;
	}
	
	if (actionFailed(data))
	{
		StripHtmlTags(data);
		result.second = data;
		return result;
	}
	
	if (!parse(data))
	{
		// if relevant part of data was not found and one of arguments
		// was language, try to fetch it again without that parameter.
		// otherwise just report failure.
		Args::iterator lang = args.find("lang");
		if (lang != args.end())
		{
			args.erase(lang);
			return fetch(args);
		}
		else
		{
			// parse should change data to error msg, if it fails
			result.second = data;
			return result;
		}
	}
	
	result.first = true;
	result.second = data;
	return result;
}
Example #17
0
void invokeNativeFunction(METHOD thisMethod)
{
    
    NativeFunctionPtr native = thisMethod->u.native.code;

    if (native == NULL) { 
        /*  Native function not found; throw error */
        START_TEMPORARY_ROOTS
            sprintf(str_buffer,"Native method '%s::%s' not found",
                    className(thisMethod->ofClass), methodName(thisMethod));
        END_TEMPORARY_ROOTS
        fatalError(str_buffer);
    }
    


    frameTracing(thisMethod, "=>", +1);

    if (INCLUDEDEBUGCODE && !ASYNCHRONOUS_NATIVE_FUNCTIONS) { 
        cell* expectedSP = sp + getReturnSize(thisMethod)- thisMethod->argCount;
        FRAME expectedFP = fp;
        BYTE *expectedIP = ip;

        native();
        
        if (expectedFP == fp && expectedIP == ip && expectedSP != sp) { 
            /* We presume that if the fp or ip changed, the native code was 
             * doing something special, and we shouldn't interfere.
             * Otherwise, we check to make sure the sp is the value that
             * we expected.
             */
            START_TEMPORARY_ROOTS
                sprintf(str_buffer, 
                        "Bad native stack manipulation: %s.%s. Stack off by %d",
                        className(thisMethod->ofClass), methodName(thisMethod), 
                        sp - expectedSP);
                fatalError(str_buffer);
            END_TEMPORARY_ROOTS
        }
Example #18
0
QString Field::diff( Field * after )
{
	QStringList ret;
	if( type() != after->type() )
		ret += "Type Changed from " + typeString() + " to " + after->typeString();
	for( int i=0; i<Field::LastFlag; i++ ) {
		Flags f((Field::Flags)i);
		if( flag(f) != after->flag(f) )
			ret += QString(flag(f) ? "-" : "+") + " " + stringFromFlag(i);
	}
	if( pluralMethodName() != after->pluralMethodName() )
		ret += "Plural Method Name changed from " + pluralMethodName() + " to " + after->pluralMethodName();
	if( methodName() != after->methodName() )
		ret += "Method Name changed from " + methodName() + " to " + after->methodName();
	if( displayName() != after->displayName() )
		ret += "Display Name changed from " + displayName() + " to " + after->displayName();
	if( defaultValue() != after->defaultValue() )
		ret += "Default Value changed from " + defaultValueString() + " to " + after->defaultValueString();
	if( (bool(foreignKeyTable()) != bool(after->foreignKeyTable())) || (foreignKeyTable() && foreignKeyTable()->tableName().toLower() != after->foreignKeyTable()->tableName().toLower()) )
		ret += "Foreign Key Table changed from " + (foreignKeyTable() ? foreignKeyTable()->tableName() : "") + " to " + (after->foreignKeyTable() ? after->foreignKeyTable()->tableName() : "");
	return ret.isEmpty() ? QString() : ("\t" + table()->tableName() + "." + name() + " Changes:\n\t\t" + ret.join("\n\t\t"));
}
Example #19
0
SEXP rCallStaticMethod(SEXP p) {
	
	// 1 - Get data from SEXP
	p = CDR(p); // Skip the first parameter: because function name
	char* strTypeName = readStringFromSexp(p); p = CDR(p);
	char* strMethodName = readStringFromSexp(p); p = CDR(p);
	SAFEARRAY* parameters = readParametersFromSexp(p);

	// 2 - Prepare arguments to call proxy
	SAFEARRAY* args = SafeArrayCreateVector(VT_VARIANT, 0, 3);
	long i = 0;
	
	// 2.1 - Type name
	variant_t typeName(strTypeName);
	SafeArrayPutElement(args, &i, &typeName); i++;
	
	// 2.2 - Method name
	variant_t methodName(strMethodName);
	SafeArrayPutElement(args, &i, &methodName); i++;

	// 2.3 parameters
	VARIANT* pvt = new variant_t();
	VariantInit(pvt);
	pvt->vt = VT_ARRAY | VT_I8;
	pvt->parray = parameters;
	SafeArrayPutElement(args, &i, pvt); i++;

	// 3 - Call the proxy
	CLR_OBJ result;
	char* errorMsg;
	HRESULT hr = callProxy(L"CallStaticMethod", args, &result, &errorMsg);
	
	if(FAILED(hr)) {
		Rprintf(errorMsg);
		error("Exception during netCallStatic !");
		free(errorMsg);
		return R_NilValue;
	}

	// 4 - Free memory
	SafeArrayDestroy(parameters);
	SafeArrayDestroy(args);
	//free_variant_array(pvt);
	//free(strTypeName);
	//free(strMethodName);

	return convertToSEXP(result);
}
Example #20
0
Activity * BfActStrategy::getNextActivity(
   NssComponentTree *nssComponentTree)
{
   string methodName("BfActStrategy::getNextActivity");

   // set activity type (for logging purposes)
   if (! nssParameters_.act_->setActivityType(actType_))
   {
      throw SseException("tried to set invalid activity type: " + actType_
                         + " in " + methodName + "\n", __FILE__, __LINE__);
   }    

   Activity *act = createNewActivity(nssComponentTree);

   return act;
}
Example #21
0
    shared_ptr<MethodBody> ContextBuilder::buildMethod(
        const shared_ptr<MethodDeclaration> &method) {
        std::map< PropertyName, ClassName > args;
        for (auto elem : method->getArgs()) {
            args[PropertyName(elem.first)] = ClassName(elem.second);
        }
        MethodName methodName(method->getName());

        auto term = buildMethodBody(method->getBodyTerm());

        return std::make_shared< MethodBody >(
            methodName,
            term,
            args
        );
    }
Activity * TscopeSetupActStrategy::getNextActivity(
   NssComponentTree *nssComponentTree)
{
   string methodName("TscopeSetupActStrategy::getNextActivity");

   // set activity type (for logging purposes)
   string actType("tscopesetup");
   if (! nssParameters_.act_->setActivityType(actType))
   {
      throw SseException("tried to set invalid activity type: " + actType
                         + " in " + methodName + "\n", __FILE__, __LINE__);
   }    

   Activity *act = NewTscopeSetupActWrapper(
      getNextActId(), this,
      nssComponentTree, nssParameters_,
      getVerboseLevel());

   return act;
}
void BfAutoattenActStrategy::setTuningFreqInParams(double freqMhz)
{
   string methodName("BfAutoattenActStrategy::setTuningFreqInParams");

   // Set freq on all tunings (this should do no harm for tunings
   // that are not enabled).
   // TBD get tuning names from TscopeParameters

   const char *tunings[] = {"tuninga", "tuningb", "tuningc", "tuningd"};
   for (int i=0; i<ARRAY_LENGTH(tunings); ++i)
   {
      if (! getNssParameters().tscope_->setTuningSkyFreqMhz(
             tunings[i], freqMhz))
      {
         throw SseException("error trying to set skyfreq on tscope tuning: " 
                            + string(tunings[i]) + " in " + methodName + "\n",
                            __FILE__,__LINE__);
      }
   }
}
Example #24
0
int competition2Stage ()
{
    TString trainingFileName ("training");
    auto resultPre = TMVAClassification (trainingFileName, AnalysisType::DIRECT);
    std::string fileName (resultPre.first);
    std::string methodName (resultPre.second);
    std::cout << "filename = " << fileName << std::endl;
    std::cout << "methodName = " << methodName << std::endl;
//    return 0;
    auto interRootFileName = TMVAPredict (methodName, EnumPredictMode::INTERMEDIATE);
    std::cout << "inter file name = " << interRootFileName << std::endl;
//    return 0;
    auto tonbkgResult = TMVAClassification (trainingFileName, AnalysisType::BACKGROUND, interRootFileName);
    std::string backFileName (tonbkgResult.first);
    std::string backMethodName (tonbkgResult.second);
    std::cout << "BACK filename = " << backFileName << std::endl;
    std::cout << "BACK methodName = " << backMethodName << std::endl;
    TMVAPredict (backMethodName, EnumPredictMode::FINAL);

    return 0;
}
Example #25
0
void invokeNativeFunction(METHOD thisMethod)
{
#if INCLUDEDEBUGCODE
    int saved_TemporaryRootsLength;
#endif
    NativeFunctionPtr native = thisMethod->u.native.code;

    if (native == NULL) {
        /*  Native function not found; throw error */

        /* The GC may get confused by the arguments on the stack */
        setSP(getSP() - thisMethod->argCount);

        START_TEMPORARY_ROOTS
            DECLARE_TEMPORARY_ROOT(char*, className, 
                     getClassName((CLASS)(thisMethod->ofClass)));
            sprintf(str_buffer,
                    KVM_MSG_NATIVE_METHOD_NOT_FOUND_2STRPARAMS,
                    className, methodName(thisMethod));
        END_TEMPORARY_ROOTS
        fatalError(str_buffer);
    }
Example #26
0
Service::Result Service::fetch()
{
	Result result;
	result.first = false;
	
	std::string url = apiUrl;
	url += methodName();
	for (auto &arg : m_arguments)
	{
		url += "&";
		url += arg.first;
		url += "=";
		url += Curl::escape(arg.second);
	}
	
	std::string data;
	CURLcode code = Curl::perform(data, url);
	
	if (code != CURLE_OK)
		result.second = curl_easy_strerror(code);
	else if (actionFailed(data))
		result.second = msgInvalidResponse;
	else
	{
		result = processData(data);
		
		// if relevant part of data was not found and one of arguments
		// was language, try to fetch it again without that parameter.
		// otherwise just report failure.
		if (!result.first && !m_arguments["lang"].empty())
		{
			m_arguments.erase("lang");
			result = fetch();
		}
	}
	
	return result;
}
Example #27
0
/*
 * Dump stack frames, starting from the specified frame and moving down.
 *
 * Each frame holds a pointer to the currently executing method, and the
 * saved program counter from the caller ("previous" frame).  This means
 * we don't have the PC for the current method on the stack, which is
 * pretty reasonable since it's in the "PC register" for the VM.  Because
 * exceptions need to show the correct line number we actually *do* have
 * an updated version in the fame's "xtra.currentPc", but it's unreliable.
 *
 * Note "framePtr" could be NULL in rare circumstances.
 */
static void dumpFrames(const DebugOutputTarget* target, void* framePtr,
    Thread* thread)
{
    const StackSaveArea* saveArea;
    const Method* method;
    int checkCount = 0;
    const u2* currentPc = NULL;
    bool first = true;

    /*
     * We call functions that require us to be holding the thread list lock.
     * It's probable that the caller has already done so, but it's not
     * guaranteed.  If it's not locked, lock it now.
     */
    bool needThreadUnlock = dvmTryLockThreadList();

    /*
     * The "currentPc" is updated whenever we execute an instruction that
     * might throw an exception.  Show it here.
     */
    if (framePtr != NULL && !dvmIsBreakFrame((u4*)framePtr)) {
        saveArea = SAVEAREA_FROM_FP(framePtr);

        if (saveArea->xtra.currentPc != NULL)
            currentPc = saveArea->xtra.currentPc;
    }

    while (framePtr != NULL) {
        saveArea = SAVEAREA_FROM_FP(framePtr);
        method = saveArea->method;

        if (dvmIsBreakFrame((u4*)framePtr)) {
            //dvmPrintDebugMessage(target, "  (break frame)\n");
        } else {
            int relPc;

            if (currentPc != NULL)
                relPc = currentPc - saveArea->method->insns;
            else
                relPc = -1;

            std::string methodName(dvmHumanReadableMethod(method, false));
            if (dvmIsNativeMethod(method)) {
                dvmPrintDebugMessage(target, "  at %s(Native Method)\n",
                        methodName.c_str());
            } else {
                dvmPrintDebugMessage(target, "  at %s(%s:%s%d)\n",
                        methodName.c_str(), dvmGetMethodSourceFile(method),
                        (relPc >= 0 && first) ? "~" : "",
                        relPc < 0 ? -1 : dvmLineNumFromPC(method, relPc));
            }

            if (first) {
                /*
                 * Decorate WAIT and MONITOR threads with some detail on
                 * the first frame.
                 *
                 * warning: wait status not stable, even in suspend
                 */
                if (thread->status == THREAD_WAIT ||
                    thread->status == THREAD_TIMED_WAIT)
                {
                    Monitor* mon = thread->waitMonitor;
                    Object* obj = dvmGetMonitorObject(mon);
                    if (obj != NULL) {
                        Thread* joinThread = NULL;
                        if (obj->clazz == gDvm.classJavaLangVMThread) {
                            joinThread = dvmGetThreadFromThreadObject(obj);
                        }
                        if (joinThread == NULL) {
                            joinThread = dvmGetObjectLockHolder(obj);
                        }
                        printWaitMessage(target, "on", obj, joinThread);
                    }
                } else if (thread->status == THREAD_MONITOR) {
                    Object* obj;
                    Thread* owner;
                    if (extractMonitorEnterObject(thread, &obj, &owner)) {
                        printWaitMessage(target, "to lock", obj, owner);
                    }
                }
            }
        }

        /*
         * Get saved PC for previous frame.  There's no savedPc in a "break"
         * frame, because that represents native or interpreted code
         * invoked by the VM.  The saved PC is sitting in the "PC register",
         * a local variable on the native stack.
         */
        currentPc = saveArea->savedPc;

        first = false;

        if (saveArea->prevFrame != NULL && saveArea->prevFrame <= framePtr) {
            ALOGW("Warning: loop in stack trace at frame %d (%p -> %p)",
                checkCount, framePtr, saveArea->prevFrame);
            break;
        }
        framePtr = saveArea->prevFrame;

        checkCount++;
        if (checkCount > 300) {
            dvmPrintDebugMessage(target,
                "  ***** printed %d frames, not showing any more\n",
                checkCount);
            break;
        }
    }

    if (needThreadUnlock) {
        dvmUnlockThreadList();
    }
}
Example #28
0
bool
HTTPRemotingHandler::advance()
{

#ifdef GNASH_DEBUG_REMOTING
    log_debug("advancing HTTPRemotingHandler");
#endif
    if (_connection) {

#ifdef GNASH_DEBUG_REMOTING
        log_debug("have connection");
#endif

        // Fill last chunk before reading in the next
        size_t toRead = reply.capacity() - reply.size();
        if (! toRead) toRead = NCCALLREPLYCHUNK;

#ifdef GNASH_DEBUG_REMOTING
        log_debug("Attempt to read %d bytes", toRead);
#endif

        // See if we need to allocate more bytes for the next
        // read chunk
        if (reply.capacity() < reply.size() + toRead) {
            // if _connection->size() >= 0, reserve for it, so
            // if HTTP Content-Length response header is correct
            // we'll be allocating only once for all.
            const size_t newCapacity = reply.size() + toRead;

#ifdef GNASH_DEBUG_REMOTING
            log_debug("NetConnection.call: reply buffer capacity (%d) "
                      "is too small to accept next %d bytes of chunk "
                      "(current size is %d). Reserving %d bytes.",
                reply.capacity(), toRead, reply.size(), newCapacity);
#endif

            reply.reserve(newCapacity);

#ifdef GNASH_DEBUG_REMOTING
            log_debug(" after reserve, new capacity is %d", reply.capacity());
#endif
        }

        const int read =
            _connection->readNonBlocking(reply.data() + reply.size(), toRead);

        if (read > 0) {
#ifdef GNASH_DEBUG_REMOTING
            log_debug("read '%1%' bytes: %2%", read, 
                    hexify(reply.data() + reply.size(), read, false));
#endif
            reply.resize(reply.size() + read);
        }

        // There is no way to tell if we have a whole amf reply without
        // parsing everything
        //
        // The reply format has a header field which specifies the
        // number of bytes in the reply, but potlatch sends 0xffffffff
        // and works fine in the proprietary player
        //
        // For now we just wait until we have the full reply.
        //
        // FIXME make this parse on other conditions, including: 1) when
        // the buffer is full, 2) when we have a "length in bytes" value
        // thas is satisfied

        if (_connection->bad()) {
            log_debug("connection is in error condition, calling "
                    "NetConnection.onStatus");
            reply.resize(0);
            reply_start = 0;
            // reset connection before calling the callback
            _connection.reset();

            // This is just a guess, but is better than sending
            // 'undefined'
            _nc.notifyStatus(NetConnection_as::CALL_FAILED);
        }
        else if (_connection->eof()) {

            if (reply.size() > 8) {


#ifdef GNASH_DEBUG_REMOTING
                log_debug("hit eof");
#endif
                boost::uint16_t li;
                const boost::uint8_t *b = reply.data() + reply_start;
                const boost::uint8_t *end = reply.data() + reply.size();
                
                amf::Reader rd(b, end, getGlobal(_nc.owner()));

                // parse header
                b += 2; // skip version indicator and client id

                // NOTE: this looks much like parsing of an OBJECT_AMF0
                boost::int16_t si = readNetworkShort(b);
                b += 2; // number of headers
                uint8_t headers_ok = 1;
                if (si != 0) {

#ifdef GNASH_DEBUG_REMOTING
                    log_debug("NetConnection::call(): amf headers "
                            "section parsing");
#endif
                    as_value tmp;
                    for (size_t i = si; i > 0; --i) {
                        if(b + 2 > end) {
                            headers_ok = 0;
                            break;
                        }
                        si = readNetworkShort(b); b += 2; // name length
                        if(b + si > end) {
                            headers_ok = 0;
                            break;
                        }
                        std::string headerName((char*)b, si); // end-b);
#ifdef GNASH_DEBUG_REMOTING
                        log_debug("Header name %s", headerName);
#endif
                        b += si;
                        if ( b + 5 > end ) {
                            headers_ok = 0;
                            break;
                        }
                        b += 5; // skip past bool and length long
                        if(!rd(tmp)) {
                            headers_ok = 0;
                            break;
                        }
#ifdef GNASH_DEBUG_REMOTING
                        log_debug("Header value %s", tmp);
#endif

                        { // method call for each header
                          // FIXME: it seems to me that the call should happen
                            VM& vm = getVM(_nc.owner());
                            string_table& st = vm.getStringTable();
                            string_table::key key = st.find(headerName);
#ifdef GNASH_DEBUG_REMOTING
                            log_debug("Calling NetConnection.%s(%s)",
                                    headerName, tmp);
#endif
                            callMethod(&_nc.owner(), key, tmp);
                        }
                    }
                }

                if(headers_ok == 1) {

                    si = readNetworkShort(b); b += 2; // number of replies

                    // TODO consider counting number of replies we
                    // actually parse and doing something if it
                    // doesn't match this value (does it matter?
                    if(si > 0) {
                        // parse replies until we get a parse error or we reach the end of the buffer
                        while(b < end) {
                            if(b + 2 > end) break;
                            si = readNetworkShort(b); b += 2; // reply length
                            if(si < 4) { // shorted valid response is '/1/a'
                                log_error("NetConnection::call(): reply message name too short");
                                break;
                            }
                            if(b + si > end) break;

                            // Reply message is: '/id/methodName'

                            int ns = 1; // next slash position
                            while (ns<si-1 && *(b+ns) != '/') ++ns;
                            if ( ns >= si-1 ) {
                                std::string msg(
                                        reinterpret_cast<const char*>(b), si);
                                log_error("NetConnection::call(): invalid "
                                        "reply message name (%s)", msg);
                                break;
                            }

                            std::string id(reinterpret_cast<const char*>(b),
                                    ns);

                            std::string methodName(
                                    reinterpret_cast<const char*>(b+ns+1),
                                    si-ns-1);

                            b += si;

                            // parse past unused string in header
                            if(b + 2 > end) break;
                            si = readNetworkShort(b); b += 2; // reply length
                            if(b + si > end) break;
                            b += si;

                            // this field is supposed to hold the
                            // total number of bytes in the rest of
                            // this particular reply value, but
                            // openstreetmap.org (which works great
                            // in the adobe player) sends
                            // 0xffffffff. So we just ignore it
                            if(b + 4 > end) break;
                            li = readNetworkLong(b); b += 4; // reply length

#ifdef GNASH_DEBUG_REMOTING
                            log_debug("about to parse amf value");
#endif
                            // this updates b to point to the next unparsed byte
                            as_value replyval;
                            if (!rd(replyval)) {
                                log_error("parse amf failed");
                                // this will happen if we get
                                // bogus data, or if the data runs
                                // off the end of the buffer
                                // provided, or if we get data we
                                // don't know how to parse
                                break;
                            }
#ifdef GNASH_DEBUG_REMOTING
                            log_debug("parsed amf");
#endif

                            // update variable to show how much we've parsed
                            reply_start = b - reply.data();

                            // if actionscript specified a callback object,
                            // call it
                            as_object* callback = pop_callback(id);
                            if (callback) {

                                string_table::key methodKey;
                                if ( methodName == "onResult" ) {
                                    methodKey = NSV::PROP_ON_RESULT;
                                }
                                else if (methodName == "onStatus") {
                                    methodKey = NSV::PROP_ON_STATUS;
                                }
                                else {
                                    // NOTE: the pp is known to actually
                                    // invoke the custom method, but with 7
                                    // undefined arguments (?)
                                    log_error("Unsupported HTTP Remoting "
                                            "response callback: '%s' "
                                            "(size %d)", methodName,
                                            methodName.size());
                                    continue;
                                }

#ifdef GNASH_DEBUG_REMOTING
                                log_debug("calling onResult callback");
#endif
                                // FIXME check if above line can fail and we
                                // have to react
                                callMethod(callback, methodKey, replyval);
#ifdef GNASH_DEBUG_REMOTING
                                log_debug("callback called");
#endif
                            } else {
                                log_error("Unknown HTTP Remoting response identifier '%s'", id);
                            }
                        }
                    }
                }
            }
            else
            {
                log_error("Response from remoting service < 8 bytes");
            }

#ifdef GNASH_DEBUG_REMOTING
            log_debug("deleting connection");
#endif
            _connection.reset();
            reply.resize(0);
            reply_start = 0;
        }
    }

    if(!_connection && queued_count > 0) {
//#ifdef GNASH_DEBUG_REMOTING
        log_debug("creating connection");
//#endif
        // set the "number of bodies" header

        (reinterpret_cast<boost::uint16_t*>(_postdata.data() + 4))[0] = htons(queued_count);
        std::string postdata_str(reinterpret_cast<char*>(_postdata.data()), _postdata.size());
#ifdef GNASH_DEBUG_REMOTING
        log_debug("NetConnection.call(): encoded args from %1% calls: %2%", queued_count, hexify(postdata.data(), postdata.size(), false));
#endif
        queued_count = 0;

        // TODO: it might be useful for a Remoting Handler to have a 
        // StreamProvider member
        const StreamProvider& sp =
            getRunResources(_nc.owner()).streamProvider();

        _connection.reset(sp.getStream(_url, postdata_str, _headers).release());

        _postdata.resize(6);
#ifdef GNASH_DEBUG_REMOTING
        log_debug("connection created");
#endif
    }

    if (_connection == 0) {
        // nothing more to do
        return false;
    }

    return true;
}
/**
 * Read attributes of a node.
 * @param initialArgs  Tokens on the line of the opening "(" of the node
 *                   but with leading whitespace and the opening "(" removed.
 * @param stream     The QTextStream from which to read following lines.
 * @return           Pointer to the created PetalNode or NULL on error.
 */
PetalNode *readAttributes(QStringList initialArgs, QTextStream& stream)
{
    methodName(QLatin1String("readAttributes"));
    if (initialArgs.count() == 0) {
        uError() << loc() << "initialArgs is empty";
        return NULL;
    }
    PetalNode::NodeType nt;
    QString type = shift(initialArgs);
    if (type == QLatin1String("object"))
        nt = PetalNode::nt_object;
    else if (type == QLatin1String("list"))
        nt = PetalNode::nt_list;
    else {
        uError() << loc() << "unknown node type " << type;
        return NULL;
    }
    PetalNode *node = new PetalNode(nt);
    bool seenClosing = checkClosing(initialArgs);
    node->setInitialArgs(initialArgs);
    if (seenClosing)
        return node;
    PetalNode::NameValueList attrs;
    QString line;
    while (!(line = stream.readLine()).isNull()) {
        linum++;
        line = line.trimmed();
        if (line.isEmpty())
            continue;
        QStringList tokens = scan(line);
        QString stringOrNodeOpener = shift(tokens);
        QString name;
        if (nt == PetalNode::nt_object && !stringOrNodeOpener.contains(QRegExp(QLatin1String("^[A-Za-z]")))) {
            uError() << loc() << "unexpected line " << line;
            delete node;
            return NULL;
        }
        PetalNode::StringOrNode value;
        if (nt == PetalNode::nt_object) {
            name = stringOrNodeOpener;
            if (tokens.count() == 0) {  // expect verbatim text to follow on subsequent lines
                value.string = collectVerbatimText(stream);
                PetalNode::NameValue attr(name, value);
                attrs.append(attr);
                if (nClosures) {
                    // Decrement nClosures exactly once, namely for the own scope.
                    // Each recursion of readAttributes() is only responsible for
                    // its own scope. I.e. each further scope closing is handled by
                    // an outer recursion in case of multiple closing parentheses.
                    nClosures--;
                    break;
                }
                continue;
            }
            stringOrNodeOpener = shift(tokens);
        } else if (stringOrNodeOpener != QLatin1String("(")) {
            value.string = stringOrNodeOpener;
            PetalNode::NameValue attr;
            attr.second = value;
            attrs.append(attr);
            if (tokens.count() && tokens.first() != QLatin1String(")")) {
                uDebug() << loc()
                    << "NYI - immediate list entry with more than one item";
            }
            if (checkClosing(tokens))
                break;
            continue;
        }
        if (stringOrNodeOpener == QLatin1String("(")) {
            QString nxt = tokens.first();
            if (isImmediateValue(nxt)) {
                value.string = extractImmediateValues(tokens);
            } else if (nxt == QLatin1String("value") || nxt.startsWith(QLatin1Char('"'))) {
                value.string = extractValue(tokens, stream);
            } else {
                value.node = readAttributes(tokens, stream);
                if (value.node == NULL) {
                    delete node;
                    return NULL;
                }
            }
            PetalNode::NameValue attr(name, value);
            attrs.append(attr);
            if (nClosures) {
                // Decrement nClosures exactly once, namely for the own scope.
                // Each recursion of readAttributes() is only responsible for
                // its own scope. I.e. each further scope closing is handled by
                // an outer recursion in case of multiple closing parentheses.
                nClosures--;
                break;
            }
        } else {
            value.string = stringOrNodeOpener;
            bool seenClosing = checkClosing(tokens);
            PetalNode::NameValue attr(name, value);
            attrs.append(attr);
            if (seenClosing) {
                break;
            }
        }
    }
    node->setAttributes(attrs);
    return node;
}
Example #30
0
QString Field::generatedDisplayName() const
{
	return fieldToDisplayName( methodName() );
}