Example #1
0
/// @brief Platform-level implementation called by modifyRing()
ReturnCode platModifyRing(const Target<TARGET_TYPE_ALL>& i_target,
                          const scanRingId_t i_address,
                          const variable_buffer& i_data,
                          const ChipOpModifyMode i_modifyMode,
                          const RingMode i_ringMode)
{
    FAPI_DBG(ENTER_MRK "platModifyRing");

    // TODO RTC:152489 - story to finish this modifyRing
    FAPI_ERR("platModifyRing: not supported yet");
    assert(0,"platModifyRing not supported yet.");

    ReturnCode l_rc;
    errlHndl_t l_err = NULL;
    variable_buffer l_current_data(i_data);

    // Note: Trace is placed here in plat code because PPE doesn't support
    //       trace in common fapi2_hw_access.H
    bool l_traceit = platIsScanTraceEnabled();

    // Grab the name of the target
    TARGETING::ATTR_FAPI_NAME_type l_targName = {0};
    fapi2::toString(i_target, l_targName, sizeof(l_targName));

    do
    {
        // Extract the component pointer
        TARGETING::Target* l_target =
                reinterpret_cast<TARGETING::Target*>(i_target.get());

        // --------------------
        // Read current value
        // --------------------
        uint64_t l_ringLen = l_current_data.getBitLength();
        uint64_t l_flag = platGetDDScanMode(i_ringMode);
        size_t l_size = l_current_data.getLength<uint8_t>();
        l_err = deviceRead(l_target,
                           l_current_data.pointer(),
                           l_size,
                           DEVICE_SCAN_ADDRESS(i_address, l_ringLen, l_flag));
        if (l_err)
        {
            FAPI_ERR("platModifyRing: deviceRead returns error!");
            FAPI_ERR("platModifyRing failed - Target %s, Addr %.16llX",
                  l_targName, i_address);

            // Add the error log pointer as data to the ReturnCode
            l_rc.setPlatDataPtr(reinterpret_cast<void *> (l_err));

            // break out if read fails
            break;
        }

        // ----------------------
        // Applying modification
        // ----------------------
        /* TODO-RTC:151261 - re-enable when variable_buffer operations supported
        if (fapi2::CHIP_OP_MODIFY_MODE_OR == i_modifyMode)
        {
            l_current_data |= i_data;
        }
        else if (fapi2::CHIP_OP_MODIFY_MODE_AND == i_modifyMode)
        {
            l_current_data &= i_data;
        }
        else
        {
            l_current_data ^= i_data;
        } */


        // -------------------------
        // Write back updated data
        // -------------------------
        l_err = deviceWrite(l_target,
                        l_current_data.pointer(),
                        l_size,
                        DEVICE_SCAN_ADDRESS(i_address, l_ringLen, l_flag));
        if (l_err)
        {
            FAPI_ERR("platModifyRing: deviceWrite returns error!");
            FAPI_ERR("platModifyRing failed - Target %s, Addr %.16llX",
                  l_targName, i_address);
            // Add the error log pointer as data to the ReturnCode
            l_rc.setPlatDataPtr(reinterpret_cast<void *> (l_err));
            break;
        }

    } while (0);

    if (l_traceit)
    {
        uint64_t l_data = l_current_data.get<uint64_t>();
        FAPI_SCAN("TRACE : MODIFYRING  :  %s : %.16llX %.16llX",
                  l_targName,
                  i_address,
                  l_data);
    }
    FAPI_DBG(EXIT_MRK "platModifyRing");
    return l_rc;
}
Error
ClangExpressionParser::PrepareForExecution (lldb::addr_t &func_addr,
                                            lldb::addr_t &func_end,
                                            std::shared_ptr<IRExecutionUnit> &execution_unit_sp,
                                            ExecutionContext &exe_ctx,
                                            bool &can_interpret,
                                            ExecutionPolicy execution_policy)
{
	func_addr = LLDB_INVALID_ADDRESS;
	func_end = LLDB_INVALID_ADDRESS;
    Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));

    Error err;

    std::unique_ptr<llvm::Module> llvm_module_ap (m_code_generator->ReleaseModule());

    if (!llvm_module_ap.get())
    {
        err.SetErrorToGenericError();
        err.SetErrorString("IR doesn't contain a module");
        return err;
    }

    // Find the actual name of the function (it's often mangled somehow)

    ConstString function_name;

    if (!FindFunctionInModule(function_name, llvm_module_ap.get(), m_expr.FunctionName()))
    {
        err.SetErrorToGenericError();
        err.SetErrorStringWithFormat("Couldn't find %s() in the module", m_expr.FunctionName());
        return err;
    }
    else
    {
        if (log)
            log->Printf("Found function %s for %s", function_name.AsCString(), m_expr.FunctionName());
    }

    execution_unit_sp.reset(new IRExecutionUnit (m_llvm_context, // handed off here
                                                 llvm_module_ap, // handed off here
                                                 function_name,
                                                 exe_ctx.GetTargetSP(),
                                                 m_compiler->getTargetOpts().Features));

    ClangExpressionDeclMap *decl_map = m_expr.DeclMap(); // result can be NULL

    if (decl_map)
    {
        Stream *error_stream = NULL;
        Target *target = exe_ctx.GetTargetPtr();
        if (target)
            error_stream = target->GetDebugger().GetErrorFile().get();

        IRForTarget ir_for_target(decl_map,
                                  m_expr.NeedsVariableResolution(),
                                  *execution_unit_sp,
                                  error_stream,
                                  function_name.AsCString());

        bool ir_can_run = ir_for_target.runOnModule(*execution_unit_sp->GetModule());

        Error interpret_error;

        can_interpret = IRInterpreter::CanInterpret(*execution_unit_sp->GetModule(), *execution_unit_sp->GetFunction(), interpret_error);

        Process *process = exe_ctx.GetProcessPtr();

        if (!ir_can_run)
        {
            err.SetErrorString("The expression could not be prepared to run in the target");
            return err;
        }

        if (!can_interpret && execution_policy == eExecutionPolicyNever)
        {
            err.SetErrorStringWithFormat("Can't run the expression locally: %s", interpret_error.AsCString());
            return err;
        }

        if (!process && execution_policy == eExecutionPolicyAlways)
        {
            err.SetErrorString("Expression needed to run in the target, but the target can't be run");
            return err;
        }

        if (execution_policy == eExecutionPolicyAlways || !can_interpret)
        {
            if (m_expr.NeedsValidation() && process)
            {
                if (!process->GetDynamicCheckers())
                {
                    DynamicCheckerFunctions *dynamic_checkers = new DynamicCheckerFunctions();

                    StreamString install_errors;

                    if (!dynamic_checkers->Install(install_errors, exe_ctx))
                    {
                        if (install_errors.GetString().empty())
                            err.SetErrorString ("couldn't install checkers, unknown error");
                        else
                            err.SetErrorString (install_errors.GetString().c_str());

                        return err;
                    }

                    process->SetDynamicCheckers(dynamic_checkers);

                    if (log)
                        log->Printf("== [ClangUserExpression::Evaluate] Finished installing dynamic checkers ==");
                }

                IRDynamicChecks ir_dynamic_checks(*process->GetDynamicCheckers(), function_name.AsCString());

                if (!ir_dynamic_checks.runOnModule(*execution_unit_sp->GetModule()))
                {
                    err.SetErrorToGenericError();
                    err.SetErrorString("Couldn't add dynamic checks to the expression");
                    return err;
                }
            }

            execution_unit_sp->GetRunnableInfo(err, func_addr, func_end);
        }
    }
    else
    {
        execution_unit_sp->GetRunnableInfo(err, func_addr, func_end);
    }

    return err;
}
bool
ValueObjectDynamicValue::UpdateValue ()
{
    SetValueIsValid (false);
    m_error.Clear();

    if (!m_parent->UpdateValueIfNeeded(false))
    {
        // The dynamic value failed to get an error, pass the error along
        if (m_error.Success() && m_parent->GetError().Fail())
            m_error = m_parent->GetError();
        return false;
    }

    // Setting our type_sp to NULL will route everything back through our
    // parent which is equivalent to not using dynamic values.
    if (m_use_dynamic == lldb::eNoDynamicValues)
    {
        m_dynamic_type_info.Clear();
        return true;
    }

    ExecutionContext exe_ctx (GetExecutionContextRef());
    Target *target = exe_ctx.GetTargetPtr();
    if (target)
    {
        m_data.SetByteOrder(target->GetArchitecture().GetByteOrder());
        m_data.SetAddressByteSize(target->GetArchitecture().GetAddressByteSize());
    }

    // First make sure our Type and/or Address haven't changed:
    Process *process = exe_ctx.GetProcessPtr();
    if (!process)
        return false;

    TypeAndOrName class_type_or_name;
    Address dynamic_address;
    bool found_dynamic_type = false;

    lldb::LanguageType known_type = m_parent->GetObjectRuntimeLanguage();
    if (known_type != lldb::eLanguageTypeUnknown && known_type != lldb::eLanguageTypeC)
    {
        LanguageRuntime *runtime = process->GetLanguageRuntime (known_type);
        if (runtime)
            found_dynamic_type = runtime->GetDynamicTypeAndAddress (*m_parent, m_use_dynamic, class_type_or_name, dynamic_address);
    }
    else
    {
        LanguageRuntime *cpp_runtime = process->GetLanguageRuntime (lldb::eLanguageTypeC_plus_plus);
        if (cpp_runtime)
            found_dynamic_type = cpp_runtime->GetDynamicTypeAndAddress (*m_parent, m_use_dynamic, class_type_or_name, dynamic_address);

        if (!found_dynamic_type)
        {
            LanguageRuntime *objc_runtime = process->GetLanguageRuntime (lldb::eLanguageTypeObjC);
            if (objc_runtime)
                found_dynamic_type = objc_runtime->GetDynamicTypeAndAddress (*m_parent, m_use_dynamic, class_type_or_name, dynamic_address);
        }
    }

    // Getting the dynamic value may have run the program a bit, and so marked us as needing updating, but we really
    // don't...

    m_update_point.SetUpdated();

    if (found_dynamic_type)
    {
        if (class_type_or_name.HasType())
        {
            m_type_impl = TypeImpl(m_parent->GetClangType(),FixupTypeAndOrName(class_type_or_name, *m_parent).GetClangASTType());
        }
        else
        {
            m_type_impl.Clear();
        }
    }
    else
    {
        m_type_impl.Clear();
    }

    // If we don't have a dynamic type, then make ourselves just a echo of our parent.
    // Or we could return false, and make ourselves an echo of our parent?
    if (!found_dynamic_type)
    {
        if (m_dynamic_type_info)
            SetValueDidChange(true);
        ClearDynamicTypeInformation();
        m_dynamic_type_info.Clear();
        m_value = m_parent->GetValue();
        m_error = m_value.GetValueAsData (&exe_ctx, m_data, 0, GetModule().get());
        return m_error.Success();
    }

    Value old_value(m_value);

    Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_TYPES));

    bool has_changed_type = false;

    if (!m_dynamic_type_info)
    {
        m_dynamic_type_info = class_type_or_name;
        has_changed_type = true;
    }
    else if (class_type_or_name != m_dynamic_type_info)
    {
        // We are another type, we need to tear down our children...
        m_dynamic_type_info = class_type_or_name;
        SetValueDidChange (true);
        has_changed_type = true;
    }

    if (has_changed_type)
        ClearDynamicTypeInformation ();

    if (!m_address.IsValid() || m_address != dynamic_address)
    {
        if (m_address.IsValid())
            SetValueDidChange (true);

        // We've moved, so we should be fine...
        m_address = dynamic_address;
        lldb::TargetSP target_sp (GetTargetSP());
        lldb::addr_t load_address = m_address.GetLoadAddress(target_sp.get());
        m_value.GetScalar() = load_address;
    }

    m_dynamic_type_info = FixupTypeAndOrName(m_dynamic_type_info, *m_parent);

    //m_value.SetContext (Value::eContextTypeClangType, corrected_type);
    m_value.SetClangType (m_dynamic_type_info.GetClangASTType());

    // Our address is the location of the dynamic type stored in memory.  It isn't a load address,
    // because we aren't pointing to the LOCATION that stores the pointer to us, we're pointing to us...
    m_value.SetValueType(Value::eValueTypeScalar);

    if (has_changed_type && log)
        log->Printf("[%s %p] has a new dynamic type %s", GetName().GetCString(),
                    static_cast<void*>(this), GetTypeName().GetCString());

    if (m_address.IsValid() && m_dynamic_type_info)
    {
        // The variable value is in the Scalar value inside the m_value.
        // We can point our m_data right to it.
        m_error = m_value.GetValueAsData (&exe_ctx, m_data, 0, GetModule().get());
        if (m_error.Success())
        {
            if (!CanProvideValue())
            {
                // this value object represents an aggregate type whose
                // children have values, but this object does not. So we
                // say we are changed if our location has changed.
                SetValueDidChange (m_value.GetValueType() != old_value.GetValueType() || m_value.GetScalar() != old_value.GetScalar());
            }

            SetValueIsValid (true);
            return true;
        }
    }

    // We get here if we've failed above...
    SetValueIsValid (false);
    return false;
}
Example #4
0
void
MoonEGLContext::SyncDrawable ()
{
	Target      *target = Top ()->GetTarget ();
	Target      *cairo = target->GetCairoTarget ();
	MoonSurface *ms;
	Rect        r = target->GetData (&ms);
	MoonEGLSurface  *dst = (MoonEGLSurface  *) ms;

	// clear target contents
	if (!target->GetInit ()) {
		if (!dst->GetEGLDisplay ())
			GLContext::SetFramebuffer ();

		glClearColor (0.0, 0.0, 0.0, 0.0);
		glClear (GL_COLOR_BUFFER_BIT);

		// mark target contents as initialized
		target->SetInit (ms);
	}

	// initialize target contents with surface
	if (target->GetInit () != ms) {
		MoonEGLSurface *src = (MoonEGLSurface  *) target->GetInit ();
		GLuint     texture0 = src->Texture ();
		GLuint     program = GetProjectProgram (1.0, 0);
		GLsizei    width0 = src->Width ();
		GLsizei    height0 = src->Height ();

		if (!dst->GetEGLDisplay ())
			GLContext::SetFramebuffer ();

		SetViewport ();

		glUseProgram (program);

		SetupVertexData (NULL, 0, 0, width0, height0);
		SetupTexCoordData ();

		glVertexAttribPointer (0, 4,
				       GL_FLOAT, GL_FALSE, 0,
				       vertices);
		glVertexAttribPointer (1, 4,
				       GL_FLOAT, GL_FALSE, 0,
				       texcoords);

		glBindTexture (GL_TEXTURE_2D, texture0);
		glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,
				 GL_NEAREST);
		glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
				 GL_NEAREST);
		glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,
				 GL_CLAMP_TO_EDGE);
		glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,
				 GL_CLAMP_TO_EDGE);
		glUniform1i (glGetUniformLocation (program, "sampler0"), 0);

		glEnableVertexAttribArray (0);
		glEnableVertexAttribArray (1);

		glDrawArrays (GL_TRIANGLE_FAN, 0, 4);

		glDisableVertexAttribArray (1);
		glDisableVertexAttribArray (0);

		glBindTexture (GL_TEXTURE_2D, 0);

		glUseProgram (0);

		glBindFramebuffer (GL_FRAMEBUFFER, 0);

		// mark target contents as initialized
		target->SetInit (ms);
	}

	// render any cairo contents onto target
	if (cairo) {
		MoonSurface *mSrc;
		Rect        rSrc = cairo->GetData (&mSrc);
		MoonEGLSurface  *src = (MoonEGLSurface  *) mSrc;
		GLuint      texture0 = src->Texture ();
		GLuint      program = GetProjectProgram (1.0, 0);
		GLsizei     width0 = src->Width ();
		GLsizei     height0 = src->Height ();

		if (!dst->GetEGLDisplay ())
			GLContext::SetFramebuffer ();

		SetViewport ();

		glUseProgram (program);

		SetupVertexData (NULL, rSrc.x - r.x, rSrc.y - r.y, width0, height0);
		SetupTexCoordData ();

		glVertexAttribPointer (0, 4,
				       GL_FLOAT, GL_FALSE, 0,
				       vertices);
		glVertexAttribPointer (1, 4,
				       GL_FLOAT, GL_FALSE, 0,
				       texcoords);

		glBindTexture (GL_TEXTURE_2D, texture0);
		glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,
				 GL_NEAREST);
		glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
				 GL_NEAREST);
		glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,
				 GL_CLAMP_TO_EDGE);
		glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,
				 GL_CLAMP_TO_EDGE);
		glUniform1i (glGetUniformLocation (program, "sampler0"), 0);

		glEnableVertexAttribArray (0);
		glEnableVertexAttribArray (1);

		glEnable (GL_BLEND);
		glBlendFunc (GL_ONE, GL_ONE_MINUS_SRC_ALPHA);

		glDrawArrays (GL_TRIANGLE_FAN, 0, 4);

		glDisable (GL_BLEND);

		glDisableVertexAttribArray (1);
		glDisableVertexAttribArray (0);

		glBindTexture (GL_TEXTURE_2D, 0);

		glUseProgram (0);

		glBindFramebuffer (GL_FRAMEBUFFER, 0);

		mSrc->unref ();

		target->SetCairoTarget (NULL);
	}

	ms->unref ();
}
Example #5
0
int main(int argc, char **argv) {

    Target target = get_jit_target_from_environment();

    // We want to test all possible data flows for a buffer:

    // input -> host
    // input -> dev
    // host -> host
    // host -> dev
    // dev -> host
    // dev -> dev
    // dev -> output
    // host -> output

    // We can't really test the last two in the same routine, so we'll
    // run two routines.

    {
        // Pipeline 1 will do input -> host -> dev -> host -> output
        ImageParam in(Int(32), 1);

        Func f, g, out;
        Var x, xi;
        f(x) = in(x) + 1;
        g(x) = f(x) * 2;
        out(x) = g(x) + 3;

        f.compute_root();
        if (target.has_gpu_feature()) {
            g.compute_root().gpu_tile(x, xi, 16);
        } else if (target.features_any_of({Target::HVX_64, Target::HVX_128})) {
            g.compute_root().hexagon();
        }
        out.compute_root();

        Buffer<int> input(1024);
        lambda(x, x * 17 + 83).realize(input);
        in.set(input);

        Buffer<int> output1(1024);
        out.realize(output1);
        output1.copy_to_host();

        for (int x = 0; x < 1024; x++) {
            int correct = (input(x) + 1) * 2 + 3;
            if (output1(x) != correct) {
                printf("output1(%d) = %d instead of %d\n", x, output1(x), correct);
                return -1;
            }
        }
    }


    {
        // Pipeline 2 will do input -> dev -> dev -> output
        ImageParam in(Int(32), 1);
        Func f, out;
        Var x, xi;
        f(x) = in(x) + 1;
        out(x) = f(x) * 2;

        if (target.has_gpu_feature()) {
            f.compute_root().gpu_tile(x, xi, 16);
            out.compute_root().gpu_tile(x, xi, 16);
        } else if (target.features_any_of({Target::HVX_64, Target::HVX_128})) {
            f.compute_root().hexagon();
            out.compute_root().hexagon();
        }

        Buffer<int> input(1024);
        lambda(x, x * 17 + 83).realize(input);
        in.set(input);

        Buffer<int> output2(1024);
        out.realize(output2);
        output2.copy_to_host();

        for (int x = 0; x < 1024; x++) {
            int correct = (input(x) + 1) * 2;
            if (output2(x) != correct) {
                printf("output2(%d) = %d instead of %d\n", x, output2(x), correct);
                return -1;
            }
        }
    }

    printf("Success!\n");
    return 0;
}
Example #6
0
LLVMTargetMachine::LLVMTargetMachine(const Target &T,
                                     const std::string &Triple)
  : TargetMachine(T), TargetTriple(Triple) {
  AsmInfo = T.createAsmInfo(TargetTriple);
}
bool
AppleObjCRuntime::GetObjectDescription (Stream &strm, Value &value, ExecutionContextScope *exe_scope)
{
    if (!m_read_objc_library)
        return false;
        
    ExecutionContext exe_ctx;
    exe_scope->CalculateExecutionContext(exe_ctx);
    Process *process = exe_ctx.GetProcessPtr();
    if (!process)
        return false;
    
    // We need other parts of the exe_ctx, but the processes have to match.
    assert (m_process == process);
    
    // Get the function address for the print function.
    const Address *function_address = GetPrintForDebuggerAddr();
    if (!function_address)
        return false;
    
    Target *target = exe_ctx.GetTargetPtr();
    ClangASTType clang_type = value.GetClangType();
    if (clang_type)
    {
        if (!clang_type.IsObjCObjectPointerType())
        {
            strm.Printf ("Value doesn't point to an ObjC object.\n");
            return false;
        }
    }
    else 
    {
        // If it is not a pointer, see if we can make it into a pointer.
        ClangASTContext *ast_context = target->GetScratchClangASTContext();
        ClangASTType opaque_type = ast_context->GetBasicType(eBasicTypeObjCID);
        if (!opaque_type)
            opaque_type = ast_context->GetBasicType(eBasicTypeVoid).GetPointerType();
        //value.SetContext(Value::eContextTypeClangType, opaque_type_ptr);
        value.SetClangType (opaque_type);
    }

    ValueList arg_value_list;
    arg_value_list.PushValue(value);
    
    // This is the return value:
    ClangASTContext *ast_context = target->GetScratchClangASTContext();
    
    ClangASTType return_clang_type = ast_context->GetCStringType(true);
    Value ret;
//    ret.SetContext(Value::eContextTypeClangType, return_clang_type);
    ret.SetClangType (return_clang_type);
    
    if (exe_ctx.GetFramePtr() == NULL)
    {
        Thread *thread = exe_ctx.GetThreadPtr();
        if (thread == NULL)
        {
            exe_ctx.SetThreadSP(process->GetThreadList().GetSelectedThread());
            thread = exe_ctx.GetThreadPtr();
        }
        if (thread)
        {
            exe_ctx.SetFrameSP(thread->GetSelectedFrame());
        }
    }
    
    // Now we're ready to call the function:
    ClangFunction func (*exe_ctx.GetBestExecutionContextScope(),
                        return_clang_type, 
                        *function_address, 
                        arg_value_list);

    StreamString error_stream;
    
    lldb::addr_t wrapper_struct_addr = LLDB_INVALID_ADDRESS;
    func.InsertFunction(exe_ctx, wrapper_struct_addr, error_stream);

    EvaluateExpressionOptions options;
    options.SetUnwindOnError(true);
    options.SetTryAllThreads(true);
    options.SetStopOthers(true);
    options.SetIgnoreBreakpoints(true);
    options.SetTimeoutUsec(PO_FUNCTION_TIMEOUT_USEC);
    
    ExecutionResults results = func.ExecuteFunction (exe_ctx, 
                                                     &wrapper_struct_addr,
                                                     options,
                                                     error_stream, 
                                                     ret);
    if (results != eExecutionCompleted)
    {
        strm.Printf("Error evaluating Print Object function: %d.\n", results);
        return false;
    }
       
    addr_t result_ptr = ret.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
    
    char buf[512];
    size_t cstr_len = 0;    
    size_t full_buffer_len = sizeof (buf) - 1;
    size_t curr_len = full_buffer_len;
    while (curr_len == full_buffer_len)
    {
        Error error;
        curr_len = process->ReadCStringFromMemory(result_ptr + cstr_len, buf, sizeof(buf), error);
        strm.Write (buf, curr_len);
        cstr_len += curr_len;
    }
    return cstr_len > 0;
}
Example #8
0
void
BreakpointLocation::GetDescription (Stream *s, lldb::DescriptionLevel level)
{
    SymbolContext sc;
    s->Indent();
    BreakpointID::GetCanonicalReference(s, m_owner.GetID(), GetID());

    if (level == lldb::eDescriptionLevelBrief)
        return;

    s->PutCString(": ");

    if (level == lldb::eDescriptionLevelVerbose)
        s->IndentMore();

    if (m_address.IsSectionOffset())
    {
        m_address.CalculateSymbolContext(&sc);

        if (level == lldb::eDescriptionLevelFull)
        {
            s->PutCString("where = ");
            sc.DumpStopContext (s, m_owner.GetTarget().GetProcessSP().get(), m_address, false, true, false);
        }
        else
        {
            if (sc.module_sp)
            {
                s->EOL();
                s->Indent("module = ");
                sc.module_sp->GetFileSpec().Dump (s);
            }

            if (sc.comp_unit != NULL)
            {
                s->EOL();
                s->Indent("compile unit = ");
                static_cast<FileSpec*>(sc.comp_unit)->GetFilename().Dump (s);

                if (sc.function != NULL)
                {
                    s->EOL();
                    s->Indent("function = ");
                    s->PutCString (sc.function->GetMangled().GetName().AsCString("<unknown>"));
                }

                if (sc.line_entry.line > 0)
                {
                    s->EOL();
                    s->Indent("location = ");
                    sc.line_entry.DumpStopContext (s, true);
                }

            }
            else
            {
                // If we don't have a comp unit, see if we have a symbol we can print.
                if (sc.symbol)
                {
                    s->EOL();
                    s->Indent("symbol = ");
                    s->PutCString(sc.symbol->GetMangled().GetName().AsCString("<unknown>"));
                }
            }
        }
    }

    if (level == lldb::eDescriptionLevelVerbose)
    {
        s->EOL();
        s->Indent();
    }
    s->Printf ("%saddress = ", (level == lldb::eDescriptionLevelFull && m_address.IsSectionOffset()) ? ", " : "");
    ExecutionContextScope *exe_scope = NULL;
    Target *target = &m_owner.GetTarget();
    if (target)
        exe_scope = target->GetProcessSP().get();
    if (exe_scope == NULL)
        exe_scope = target;

    m_address.Dump(s, exe_scope, Address::DumpStyleLoadAddress, Address::DumpStyleModuleWithFileAddress);

    if (level == lldb::eDescriptionLevelVerbose)
    {
        s->EOL();
        s->Indent();
        s->Printf("resolved = %s\n", IsResolved() ? "true" : "false");

        s->Indent();
        s->Printf ("hit count = %-4u\n", GetHitCount());

        if (m_options_ap.get())
        {
            s->Indent();
            m_options_ap->GetDescription (s, level);
            s->EOL();
        }
        s->IndentLess();
    }
    else
    {
        s->Printf(", %sresolved, hit count = %u ",
                  (IsResolved() ? "" : "un"),
                  GetHitCount());
        if (m_options_ap.get())
        {
            m_options_ap->GetDescription (s, level);
        }
    }
}
bool
ClangUserExpression::Parse (Stream &error_stream,
                            ExecutionContext &exe_ctx,
                            lldb_private::ExecutionPolicy execution_policy,
                            bool keep_result_in_memory,
                            bool generate_debug_info)
{
    Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));

    Error err;

    InstallContext(exe_ctx);
    
    if (Target *target = exe_ctx.GetTargetPtr())
    {
        if (PersistentExpressionState *persistent_state = target->GetPersistentExpressionStateForLanguage(lldb::eLanguageTypeC))
        {
            m_result_delegate.RegisterPersistentState(persistent_state);
        }
        else
        {
            error_stream.PutCString ("error: couldn't start parsing (no persistent data)");
            return false;
        }
    }
    else
    {
        error_stream.PutCString ("error: couldn't start parsing (no target)");
        return false;
    }

    ScanContext(exe_ctx, err);

    if (!err.Success())
    {
        error_stream.Printf("warning: %s\n", err.AsCString());
    }

    StreamString m_transformed_stream;

    ////////////////////////////////////
    // Generate the expression
    //

    ApplyObjcCastHack(m_expr_text);
    //ApplyUnicharHack(m_expr_text);

    std::string prefix = m_expr_prefix;
    
    if (ClangModulesDeclVendor *decl_vendor = m_target->GetClangModulesDeclVendor())
    {
        const ClangModulesDeclVendor::ModuleVector &hand_imported_modules = llvm::cast<ClangPersistentVariables>(m_target->GetPersistentExpressionStateForLanguage(lldb::eLanguageTypeC))->GetHandLoadedClangModules();
        ClangModulesDeclVendor::ModuleVector modules_for_macros;
        
        for (ClangModulesDeclVendor::ModuleID module : hand_imported_modules)
        {
            modules_for_macros.push_back(module);
        }

        if (m_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);
                    }
                }
            }
        }
    }
    
    std::unique_ptr<ExpressionSourceCode> source_code (ExpressionSourceCode::CreateWrapped(prefix.c_str(), m_expr_text.c_str()));
    
    lldb::LanguageType lang_type;

    if (m_in_cplusplus_method)
        lang_type = lldb::eLanguageTypeC_plus_plus;
    else if (m_in_objectivec_method)
        lang_type = lldb::eLanguageTypeObjC;
    else
        lang_type = lldb::eLanguageTypeC;

    if (!source_code->GetText(m_transformed_text, lang_type, m_const_object, m_in_static_method, exe_ctx))
    {
        error_stream.PutCString ("error: couldn't construct expression body");
        return false;
    }

    if (log)
        log->Printf("Parsing the following code:\n%s", m_transformed_text.c_str());

    ////////////////////////////////////
    // Set up the target and compiler
    //

    Target *target = exe_ctx.GetTargetPtr();

    if (!target)
    {
        error_stream.PutCString ("error: invalid target\n");
        return false;
    }

    //////////////////////////
    // Parse the expression
    //

    m_materializer_ap.reset(new Materializer());

    ResetDeclMap(exe_ctx, m_result_delegate, keep_result_in_memory);

    class OnExit
    {
    public:
        typedef std::function <void (void)> Callback;

        OnExit (Callback const &callback) :
            m_callback(callback)
        {
        }

        ~OnExit ()
        {
            m_callback();
        }
    private:
        Callback m_callback;
    };

    OnExit on_exit([this]() { ResetDeclMap(); });

    if (!DeclMap()->WillParse(exe_ctx, m_materializer_ap.get()))
    {
        error_stream.PutCString ("error: current process state is unsuitable for expression parsing\n");

        ResetDeclMap(); // We are being careful here in the case of breakpoint conditions.

        return false;
    }

    Process *process = exe_ctx.GetProcessPtr();
    ExecutionContextScope *exe_scope = process;

    if (!exe_scope)
        exe_scope = exe_ctx.GetTargetPtr();

    ClangExpressionParser parser(exe_scope, *this, generate_debug_info);

    unsigned num_errors = parser.Parse (error_stream);

    if (num_errors)
    {
        error_stream.Printf ("error: %d errors parsing expression\n", num_errors);

        ResetDeclMap(); // We are being careful here in the case of breakpoint conditions.

        return false;
    }

    //////////////////////////////////////////////////////////////////////////////////////////
    // Prepare the output of the parser for execution, evaluating it statically if possible
    //

    Error jit_error = parser.PrepareForExecution (m_jit_start_addr,
                                                  m_jit_end_addr,
                                                  m_execution_unit_sp,
                                                  exe_ctx,
                                                  m_can_interpret,
                                                  execution_policy);

    if (generate_debug_info)
    {
        lldb::ModuleSP jit_module_sp ( m_execution_unit_sp->GetJITModule());

        if (jit_module_sp)
        {
            ConstString const_func_name(FunctionName());
            FileSpec jit_file;
            jit_file.GetFilename() = const_func_name;
            jit_module_sp->SetFileSpecAndObjectName (jit_file, ConstString());
            m_jit_module_wp = jit_module_sp;
            target->GetImages().Append(jit_module_sp);
        }
//        lldb_private::ObjectFile *jit_obj_file = jit_module_sp->GetObjectFile();
//        StreamFile strm (stdout, false);
//        if (jit_obj_file)
//        {
//            jit_obj_file->GetSectionList();
//            jit_obj_file->GetSymtab();
//            jit_obj_file->Dump(&strm);
//        }
//        lldb_private::SymbolVendor *jit_sym_vendor = jit_module_sp->GetSymbolVendor();
//        if (jit_sym_vendor)
//        {
//            lldb_private::SymbolContextList sc_list;
//            jit_sym_vendor->FindFunctions(const_func_name, NULL, lldb::eFunctionNameTypeFull, true, false, sc_list);
//            sc_list.Dump(&strm, target);
//            jit_sym_vendor->Dump(&strm);
//        }
    }

    ResetDeclMap(); // Make this go away since we don't need any of its state after parsing.  This also gets rid of any ClangASTImporter::Minions.

    if (jit_error.Success())
    {
        if (process && m_jit_start_addr != LLDB_INVALID_ADDRESS)
            m_jit_process_wp = lldb::ProcessWP(process->shared_from_this());
        return true;
    }
    else
    {
        const char *error_cstr = jit_error.AsCString();
        if (error_cstr && error_cstr[0])
            error_stream.Printf ("error: %s\n", error_cstr);
        else
            error_stream.Printf ("error: expression can't be interpreted or run\n");
        return false;
    }
}
Example #10
0
bool CFPatch::apply(codeGen &gen, CodeBuffer *buf) {

  if (needsTOCUpdate()) {
     relocation_cerr << "\t\t\t isSpecialCase..." << endl;
     gen.setFunction(const_cast<func_instance *>(func));
     if (!handleTOCUpdate(gen)) {
       relocation_cerr << "TOC special case handling in PPC64 failed" << endl;
       return false;
     }
     return true;
   }

   // Question: are we doing an inter-module static control transfer?
   // If so, things get... complicated
   if (isPLT(gen)) {
     relocation_cerr << "\t\t\t isPLT..." << endl;
      if (!applyPLT(gen, buf)) {
	relocation_cerr << "PLT special case handling in PPC64" << endl;
         return false;
      }
      return true;
   }

   // Otherwise this is a classic, and therefore easy.
   int targetLabel = target->label(buf);
   Address targetAddr = buf->predictedAddr(targetLabel);

   relocation_cerr << "\t\t CFPatch::apply, type " << type << ", origAddr " << hex << origAddr_ 
                   << ", and label " << dec << targetLabel << endl;

   if (orig_insn.isValid()) {
      relocation_cerr << "\t\t\t Currently at " << hex << gen.currAddr() << " and targeting predicted " << targetAddr << dec << endl;
      switch(type) {
         case CFPatch::Jump: {
            relocation_cerr << "\t\t\t Generating CFPatch::Jump from " 
                            << hex << gen.currAddr() << " to " << targetAddr << dec << endl;
            if (!insnCodeGen::modifyJump(targetAddr, *ugly_insn, gen)) {
	      relocation_cerr << "modifyJump failed, ret false" << endl;
               return false;
            }
            return true;
         }
         case CFPatch::JCC: {
            relocation_cerr << "\t\t\t Generating CFPatch::JCC from " 
                            << hex << gen.currAddr() << " to " << targetAddr << dec << endl;            
            if (!insnCodeGen::modifyJcc(targetAddr, *ugly_insn, gen)) {
	      relocation_cerr << "modifyJcc failed, ret false" << endl;
               return false;
            }
            return true;            
         }
         case CFPatch::Call: {
            // Special handling for function call replacement:
            //
            // Here we are certain that we are dealing with
            // an intra-module call. For PIE code, the global entry of 
            // the callee will use R12 to set up R2. Since we do not
            // set R12 to be the global entry, we should use the local entry 
            if (target->type() == TargetInt::BlockTarget) {
                Target<block_instance *> *t = static_cast<Target<block_instance *> *>(target);
                block_instance *tb = t->t();
                func_instance *callee = tb->entryOfFunc();
                if (callee->ifunc()->containsPowerPreamble() && callee->addr() == targetAddr) targetAddr += 8;
            }

            if (!insnCodeGen::modifyCall(targetAddr, *ugly_insn, gen)) {
	      relocation_cerr << "modifyCall failed, ret false" << endl;
               return false;
            }
            return true;
         }
         case CFPatch::Data: {
            if (!insnCodeGen::modifyData(targetAddr, *ugly_insn, gen)) {
	      relocation_cerr << "modifyData failed, ret false" << endl;
               return false;
            }
            return true;
         }
      }
   }
   else {
      switch(type) {
         case CFPatch::Jump:
            insnCodeGen::generateBranch(gen, gen.currAddr(), targetAddr);
            break;
         case CFPatch::Call:
            insnCodeGen::generateCall(gen, gen.currAddr(), targetAddr);
            break;
         default:
            assert(0);
      }
   }
   
   return true;
}
Example #11
0
int main(int argc, char **argv) {

    if (1) {
        // Test a tuple reduction on the gpu
        Func f;
        Var x, y;

        f(x, y) = Tuple(x + y, x - y);

        // Updates to a reduction are atomic.
        f(x, y) = Tuple(f(x, y)[1]*2, f(x, y)[0]*2);
        // now equals ((x - y)*2, (x + y)*2)

        Target target = get_jit_target_from_environment();
        if (target.has_gpu_feature()) {
            f.gpu_tile(x, y, 16, 16, GPU_DEFAULT);
            f.update().gpu_tile(x, y, 16, 16, GPU_DEFAULT);
        }

        Realization result = f.realize(1024, 1024);

        Image<int> a = result[0], b = result[1];

        for (int y = 0; y < a.height(); y++) {
            for (int x = 0; x < a.width(); x++) {
                int correct_a = (x - y)*2;
                int correct_b = (x + y)*2;
                if (a(x, y) != correct_a || b(x, y) != correct_b) {
                    printf("result(%d, %d) = (%d, %d) instead of (%d, %d)\n",
                           x, y, a(x, y), b(x, y), correct_a, correct_b);
                    return -1;
                }
            }
        }
    }

    if (1) {
        // Now test one that alternates between cpu and gpu per update step
        Func f;
        Var x, y;

        f(x, y) = Tuple(x + y, x - y);

        for (size_t i = 0; i < 10; i++) {
            // Swap the tuple elements and increment both
            f(x, y) = Tuple(f(x, y)[1] + 1, f(x, y)[0] + 1);
        }

        // Schedule the pure step and the odd update steps on the gpu
        f.gpu_tile(x, y, 16, 16, GPU_DEFAULT);
        for (int i = 0; i < 10; i ++) {
	    if (i & 1) {
		f.update(i).gpu_tile(x, y, 16, 16, GPU_DEFAULT);
	    } else {
		f.update(i);
	    }
        }

        Realization result = f.realize(1024, 1024);

        Image<int> a = result[0], b = result[1];

        for (int y = 0; y < a.height(); y++) {
            for (int x = 0; x < a.width(); x++) {
                int correct_a = (x + y) + 10;
                int correct_b = (x - y) + 10;
                if (a(x, y) != correct_a || b(x, y) != correct_b) {
                    printf("result(%d, %d) = (%d, %d) instead of (%d, %d)\n",
                           x, y, a(x, y), b(x, y), correct_a, correct_b);
                    return -1;
                }
            }
        }

    }

    if (1) {
        // Same as above, but switches which steps are gpu and cpu
        Func f;
        Var x, y;

        f(x, y) = Tuple(x + y, x - y);

        for (size_t i = 0; i < 10; i++) {
            // Swap the tuple elements and increment both
            f(x, y) = Tuple(f(x, y)[1] + 1, f(x, y)[0] + 1);
        }

        // Schedule the even update steps on the gpu
        for (int i = 0; i < 10; i ++) {
            if (i & 1) {
                f.update(i).gpu_tile(x, y, 16, 16, GPU_DEFAULT);
            } else {
                f.update(i);
            }
        }

        Realization result = f.realize(1024, 1024);

        Image<int> a = result[0], b = result[1];

        for (int y = 0; y < a.height(); y++) {
            for (int x = 0; x < a.width(); x++) {
                int correct_a = (x + y) + 10;
                int correct_b = (x - y) + 10;
                if (a(x, y) != correct_a || b(x, y) != correct_b) {
                    printf("result(%d, %d) = (%d, %d) instead of (%d, %d)\n",
                           x, y, a(x, y), b(x, y), correct_a, correct_b);
                    return -1;
                }
            }
        }

    }

    if (1) {
        // In this one, each step only uses one of the tuple elements
        // of the previous step, so only that buffer should get copied
        // back to host or copied to device.
        Func f;
        Var x, y;

        f(x, y) = Tuple(x + y - 1000, x - y + 1000);

        for (size_t i = 0; i < 10; i++) {
            f(x, y) = Tuple(f(x, y)[1] - 1, f(x, y)[1] + 1);
        }

        // Schedule the even update steps on the gpu
        for (int i = 0; i < 10; i++) {
            if (i & 1) {
                f.update(i);
            } else {
                f.update(i).gpu_tile(x, y, 16, 16, GPU_DEFAULT);
            }
        }

        Realization result = f.realize(1024, 1024);

        Image<int> a = result[0], b = result[1];

        for (int y = 0; y < a.height(); y++) {
            for (int x = 0; x < a.width(); x++) {
                int correct_a = (x - y + 1000) + 8;
                int correct_b = (x - y + 1000) + 10;
                if (a(x, y) != correct_a || b(x, y) != correct_b) {
                    printf("result(%d, %d) = (%d, %d) instead of (%d, %d)\n",
                           x, y, a(x, y), b(x, y), correct_a, correct_b);
                    return -1;
                }
            }
        }

    }

    return 0;
}
Example #12
0
//------------------------------------------------------------------
/// Install the utility function into a process
///
/// @param[in] diagnostic_manager
///     A diagnostic manager to report errors and warnings to.
///
/// @param[in] exe_ctx
///     The execution context to install the utility function to.
///
/// @return
///     True on success (no errors); false otherwise.
//------------------------------------------------------------------
bool ClangUtilityFunction::Install(DiagnosticManager &diagnostic_manager,
                                   ExecutionContext &exe_ctx) {
  if (m_jit_start_addr != LLDB_INVALID_ADDRESS) {
    diagnostic_manager.PutCString(eDiagnosticSeverityWarning,
                                  "already installed");
    return false;
  }

  ////////////////////////////////////
  // Set up the target and compiler
  //

  Target *target = exe_ctx.GetTargetPtr();

  if (!target) {
    diagnostic_manager.PutCString(eDiagnosticSeverityError, "invalid target");
    return false;
  }

  Process *process = exe_ctx.GetProcessPtr();

  if (!process) {
    diagnostic_manager.PutCString(eDiagnosticSeverityError, "invalid process");
    return false;
  }

  //////////////////////////
  // Parse the expression
  //

  bool keep_result_in_memory = false;

  ResetDeclMap(exe_ctx, keep_result_in_memory);

  if (!DeclMap()->WillParse(exe_ctx, NULL)) {
    diagnostic_manager.PutCString(
        eDiagnosticSeverityError,
        "current process state is unsuitable for expression parsing");
    return false;
  }

  const bool generate_debug_info = true;
  ClangExpressionParser parser(exe_ctx.GetBestExecutionContextScope(), *this,
                               generate_debug_info);

  unsigned num_errors = parser.Parse(diagnostic_manager);

  if (num_errors) {
    ResetDeclMap();

    return false;
  }

  //////////////////////////////////
  // JIT the output of the parser
  //

  bool can_interpret = false; // should stay that way

  Error jit_error = parser.PrepareForExecution(
      m_jit_start_addr, m_jit_end_addr, m_execution_unit_sp, exe_ctx,
      can_interpret, eExecutionPolicyAlways);

  if (m_jit_start_addr != LLDB_INVALID_ADDRESS) {
    m_jit_process_wp = process->shared_from_this();
    if (parser.GetGenerateDebugInfo()) {
      lldb::ModuleSP jit_module_sp(m_execution_unit_sp->GetJITModule());

      if (jit_module_sp) {
        ConstString const_func_name(FunctionName());
        FileSpec jit_file;
        jit_file.GetFilename() = const_func_name;
        jit_module_sp->SetFileSpecAndObjectName(jit_file, ConstString());
        m_jit_module_wp = jit_module_sp;
        target->GetImages().Append(jit_module_sp);
      }
    }
  }

#if 0
	// jingham: look here
    StreamFile logfile ("/tmp/exprs.txt", "a");
    logfile.Printf ("0x%16.16" PRIx64 ": func = %s, source =\n%s\n",
                    m_jit_start_addr, 
                    m_function_name.c_str(), 
                    m_function_text.c_str());
#endif

  DeclMap()->DidParse();

  ResetDeclMap();

  if (jit_error.Success()) {
    return true;
  } else {
    const char *error_cstr = jit_error.AsCString();
    if (error_cstr && error_cstr[0]) {
      diagnostic_manager.Printf(eDiagnosticSeverityError, "%s", error_cstr);
    } else {
      diagnostic_manager.PutCString(eDiagnosticSeverityError,
                                    "expression can't be interpreted or run");
    }
    return false;
  }
}
 bool close()
 {
     target.stop();
     return true;
 }
Example #14
0
int main(int argc, char **argv) {
    if (argc < 2) {
        printf("Usage: bilateral_grid <s_sigma>\n");
        // printf("Spatial sigma is a compile-time parameter, please provide it as an argument.\n"
        //        "(llvm's ptx backend doesn't handle integer mods by non-consts yet)\n");
        return 0;
    }

    ImageParam input(Float(32), 2);
    Param<float> r_sigma("r_sigma");
    int s_sigma = atoi(argv[1]);
    Var x("x"), y("y"), z("z"), c("c");

    // Add a boundary condition
    Func clamped("clamped");
    clamped(x, y) = input(clamp(x, 0, input.width()-1),
                          clamp(y, 0, input.height()-1));

    // Construct the bilateral grid
    RDom r(0, s_sigma, 0, s_sigma);
    Expr val = clamped(x * s_sigma + r.x - s_sigma/2, y * s_sigma + r.y - s_sigma/2);
    val = clamp(val, 0.0f, 1.0f);
    Expr zi = cast<int>(val * (1.0f/r_sigma) + 0.5f);
    Func histogram("histogram");
    histogram(x, y, z, c) = 0.0f;
    histogram(x, y, zi, c) += select(c == 0, val, 1.0f);

    // Blur the grid using a five-tap filter
    Func blurx("blurx"), blury("blury"), blurz("blurz");
    blurz(x, y, z, c) = (histogram(x, y, z-2, c) +
                         histogram(x, y, z-1, c)*4 +
                         histogram(x, y, z  , c)*6 +
                         histogram(x, y, z+1, c)*4 +
                         histogram(x, y, z+2, c));
    blurx(x, y, z, c) = (blurz(x-2, y, z, c) +
                         blurz(x-1, y, z, c)*4 +
                         blurz(x  , y, z, c)*6 +
                         blurz(x+1, y, z, c)*4 +
                         blurz(x+2, y, z, c));
    blury(x, y, z, c) = (blurx(x, y-2, z, c) +
                         blurx(x, y-1, z, c)*4 +
                         blurx(x, y  , z, c)*6 +
                         blurx(x, y+1, z, c)*4 +
                         blurx(x, y+2, z, c));

    // Take trilinear samples to compute the output
    val = clamp(input(x, y), 0.0f, 1.0f);
    Expr zv = val * (1.0f/r_sigma);
    zi = cast<int>(zv);
    Expr zf = zv - zi;
    Expr xf = cast<float>(x % s_sigma) / s_sigma;
    Expr yf = cast<float>(y % s_sigma) / s_sigma;
    Expr xi = x/s_sigma;
    Expr yi = y/s_sigma;
    Func interpolated("interpolated");
    interpolated(x, y, c) =
        lerp(lerp(lerp(blury(xi, yi, zi, c), blury(xi+1, yi, zi, c), xf),
                  lerp(blury(xi, yi+1, zi, c), blury(xi+1, yi+1, zi, c), xf), yf),
             lerp(lerp(blury(xi, yi, zi+1, c), blury(xi+1, yi, zi+1, c), xf),
                  lerp(blury(xi, yi+1, zi+1, c), blury(xi+1, yi+1, zi+1, c), xf), yf), zf);

    // Normalize
    Func bilateral_grid("bilateral_grid");
    bilateral_grid(x, y) = interpolated(x, y, 0)/interpolated(x, y, 1);

    Target target = get_target_from_environment();
    if (target.has_gpu_feature()) {
        histogram.compute_root().reorder(c, z, x, y).gpu_tile(x, y, 8, 8);
        histogram.update().reorder(c, r.x, r.y, x, y).gpu_tile(x, y, 8, 8).unroll(c);
        blurx.compute_root().gpu_tile(x, y, z, 16, 16, 1);
        blury.compute_root().gpu_tile(x, y, z, 16, 16, 1);
        blurz.compute_root().gpu_tile(x, y, z, 8, 8, 4);
        bilateral_grid.compute_root().gpu_tile(x, y, s_sigma, s_sigma);
    } else {

        // CPU schedule
        histogram.compute_at(blurz, y);
        histogram.update().reorder(c, r.x, r.y, x, y).unroll(c);
        blurz.compute_root().reorder(c, z, x, y).parallel(y).vectorize(x, 4).unroll(c);
        blurx.compute_root().reorder(c, x, y, z).parallel(z).vectorize(x, 4).unroll(c);
        blury.compute_root().reorder(c, x, y, z).parallel(z).vectorize(x, 4).unroll(c);
        bilateral_grid.compute_root().parallel(y).vectorize(x, 4);
    }
    
    bilateral_grid.compile_to_file("bilateral_grid", r_sigma, input, target);

    return 0;
}
Example #15
0
ValueObjectSP ABISysV_ppc64::GetReturnValueObjectImpl(
    Thread &thread, CompilerType &return_compiler_type) const {
  ValueObjectSP return_valobj_sp;

  if (!return_compiler_type)
    return return_valobj_sp;

  ExecutionContext exe_ctx(thread.shared_from_this());
  return_valobj_sp = GetReturnValueObjectSimple(thread, return_compiler_type);
  if (return_valobj_sp)
    return return_valobj_sp;

  RegisterContextSP reg_ctx_sp = thread.GetRegisterContext();
  if (!reg_ctx_sp)
    return return_valobj_sp;

  const size_t bit_width = return_compiler_type.GetBitSize(&thread);
  if (return_compiler_type.IsAggregateType()) {
    Target *target = exe_ctx.GetTargetPtr();
    bool is_memory = true;
    if (bit_width <= 128) {
      ByteOrder target_byte_order = target->GetArchitecture().GetByteOrder();
      DataBufferSP data_sp(new DataBufferHeap(16, 0));
      DataExtractor return_ext(data_sp, target_byte_order,
                               target->GetArchitecture().GetAddressByteSize());

      const RegisterInfo *r3_info = reg_ctx_sp->GetRegisterInfoByName("r3", 0);
      const RegisterInfo *rdx_info =
          reg_ctx_sp->GetRegisterInfoByName("rdx", 0);

      RegisterValue r3_value, rdx_value;
      reg_ctx_sp->ReadRegister(r3_info, r3_value);
      reg_ctx_sp->ReadRegister(rdx_info, rdx_value);

      DataExtractor r3_data, rdx_data;

      r3_value.GetData(r3_data);
      rdx_value.GetData(rdx_data);

      uint32_t fp_bytes =
          0; // Tracks how much of the xmm registers we've consumed so far
      uint32_t integer_bytes =
          0; // Tracks how much of the r3/rds registers we've consumed so far

      const uint32_t num_children = return_compiler_type.GetNumFields();

      // Since we are in the small struct regime, assume we are not in memory.
      is_memory = false;

      for (uint32_t idx = 0; idx < num_children; idx++) {
        std::string name;
        uint64_t field_bit_offset = 0;
        bool is_signed;
        bool is_complex;
        uint32_t count;

        CompilerType field_compiler_type = return_compiler_type.GetFieldAtIndex(
            idx, name, &field_bit_offset, nullptr, nullptr);
        const size_t field_bit_width = field_compiler_type.GetBitSize(&thread);

        // If there are any unaligned fields, this is stored in memory.
        if (field_bit_offset % field_bit_width != 0) {
          is_memory = true;
          break;
        }

        uint32_t field_byte_width = field_bit_width / 8;
        uint32_t field_byte_offset = field_bit_offset / 8;

        DataExtractor *copy_from_extractor = nullptr;
        uint32_t copy_from_offset = 0;

        if (field_compiler_type.IsIntegerOrEnumerationType(is_signed) ||
            field_compiler_type.IsPointerType()) {
          if (integer_bytes < 8) {
            if (integer_bytes + field_byte_width <= 8) {
              // This is in RAX, copy from register to our result structure:
              copy_from_extractor = &r3_data;
              copy_from_offset = integer_bytes;
              integer_bytes += field_byte_width;
            } else {
              // The next field wouldn't fit in the remaining space, so we
              // pushed it to rdx.
              copy_from_extractor = &rdx_data;
              copy_from_offset = 0;
              integer_bytes = 8 + field_byte_width;
            }
          } else if (integer_bytes + field_byte_width <= 16) {
            copy_from_extractor = &rdx_data;
            copy_from_offset = integer_bytes - 8;
            integer_bytes += field_byte_width;
          } else {
            // The last field didn't fit.  I can't see how that would happen w/o
            // the overall size being
            // greater than 16 bytes.  For now, return a nullptr return value
            // object.
            return return_valobj_sp;
          }
        } else if (field_compiler_type.IsFloatingPointType(count, is_complex)) {
          // Structs with long doubles are always passed in memory.
          if (field_bit_width == 128) {
            is_memory = true;
            break;
          } else if (field_bit_width == 64) {
            copy_from_offset = 0;
            fp_bytes += field_byte_width;
          } else if (field_bit_width == 32) {
            // This one is kind of complicated.  If we are in an "eightbyte"
            // with another float, we'll
            // be stuffed into an xmm register with it.  If we are in an
            // "eightbyte" with one or more ints,
            // then we will be stuffed into the appropriate GPR with them.
            bool in_gpr;
            if (field_byte_offset % 8 == 0) {
              // We are at the beginning of one of the eightbytes, so check the
              // next element (if any)
              if (idx == num_children - 1)
                in_gpr = false;
              else {
                uint64_t next_field_bit_offset = 0;
                CompilerType next_field_compiler_type =
                    return_compiler_type.GetFieldAtIndex(idx + 1, name,
                                                         &next_field_bit_offset,
                                                         nullptr, nullptr);
                if (next_field_compiler_type.IsIntegerOrEnumerationType(
                        is_signed))
                  in_gpr = true;
                else {
                  copy_from_offset = 0;
                  in_gpr = false;
                }
              }
            } else if (field_byte_offset % 4 == 0) {
              // We are inside of an eightbyte, so see if the field before us is
              // floating point:
              // This could happen if somebody put padding in the structure.
              if (idx == 0)
                in_gpr = false;
              else {
                uint64_t prev_field_bit_offset = 0;
                CompilerType prev_field_compiler_type =
                    return_compiler_type.GetFieldAtIndex(idx - 1, name,
                                                         &prev_field_bit_offset,
                                                         nullptr, nullptr);
                if (prev_field_compiler_type.IsIntegerOrEnumerationType(
                        is_signed))
                  in_gpr = true;
                else {
                  copy_from_offset = 4;
                  in_gpr = false;
                }
              }
            } else {
              is_memory = true;
              continue;
            }

            // Okay, we've figured out whether we are in GPR or XMM, now figure
            // out which one.
            if (in_gpr) {
              if (integer_bytes < 8) {
                // This is in RAX, copy from register to our result structure:
                copy_from_extractor = &r3_data;
                copy_from_offset = integer_bytes;
                integer_bytes += field_byte_width;
              } else {
                copy_from_extractor = &rdx_data;
                copy_from_offset = integer_bytes - 8;
                integer_bytes += field_byte_width;
              }
            } else {
              fp_bytes += field_byte_width;
            }
          }
        }

        // These two tests are just sanity checks.  If I somehow get the
        // type calculation wrong above it is better to just return nothing
        // than to assert or crash.
        if (!copy_from_extractor)
          return return_valobj_sp;
        if (copy_from_offset + field_byte_width >
            copy_from_extractor->GetByteSize())
          return return_valobj_sp;

        copy_from_extractor->CopyByteOrderedData(
            copy_from_offset, field_byte_width,
            data_sp->GetBytes() + field_byte_offset, field_byte_width,
            target_byte_order);
      }

      if (!is_memory) {
        // The result is in our data buffer.  Let's make a variable object out
        // of it:
        return_valobj_sp = ValueObjectConstResult::Create(
            &thread, return_compiler_type, ConstString(""), return_ext);
      }
    }

    // FIXME: This is just taking a guess, r3 may very well no longer hold the
    // return storage location.
    // If we are going to do this right, when we make a new frame we should
    // check to see if it uses a memory
    // return, and if we are at the first instruction and if so stash away the
    // return location.  Then we would
    // only return the memory return value if we know it is valid.

    if (is_memory) {
      unsigned r3_id =
          reg_ctx_sp->GetRegisterInfoByName("r3", 0)->kinds[eRegisterKindLLDB];
      lldb::addr_t storage_addr =
          (uint64_t)thread.GetRegisterContext()->ReadRegisterAsUnsigned(r3_id,
                                                                        0);
      return_valobj_sp = ValueObjectMemory::Create(
          &thread, "", Address(storage_addr, nullptr), return_compiler_type);
    }
  }

  return return_valobj_sp;
}
Example #16
0
void
LaunchDaemon::_AddInitJob(BJob* job)
{
	fInitTarget->AddDependency(job);
	fJobQueue.AddJob(job);
}
Example #17
0
bool
AppleObjCRuntime::GetObjectDescription (Stream &strm, Value &value, ExecutionContextScope *exe_scope)
{
    if (!m_read_objc_library)
        return false;
        
    ExecutionContext exe_ctx;
    exe_scope->CalculateExecutionContext(exe_ctx);
    Process *process = exe_ctx.GetProcessPtr();
    if (!process)
        return false;
    
    // We need other parts of the exe_ctx, but the processes have to match.
    assert (m_process == process);
    
    // Get the function address for the print function.
    const Address *function_address = GetPrintForDebuggerAddr();
    if (!function_address)
        return false;
    
    Target *target = exe_ctx.GetTargetPtr();
    if (value.GetClangType())
    {
        clang::QualType value_type = clang::QualType::getFromOpaquePtr (value.GetClangType());
        if (!value_type->isObjCObjectPointerType())
        {
            strm.Printf ("Value doesn't point to an ObjC object.\n");
            return false;
        }
    }
    else 
    {
        // If it is not a pointer, see if we can make it into a pointer.
        ClangASTContext *ast_context = target->GetScratchClangASTContext();
        void *opaque_type_ptr = ast_context->GetBuiltInType_objc_id();
        if (opaque_type_ptr == NULL)
            opaque_type_ptr = ast_context->GetVoidPtrType(false);
        value.SetContext(Value::eContextTypeClangType, opaque_type_ptr);    
    }

    ValueList arg_value_list;
    arg_value_list.PushValue(value);
    
    // This is the return value:
    ClangASTContext *ast_context = target->GetScratchClangASTContext();
    
    void *return_qualtype = ast_context->GetCStringType(true);
    Value ret;
    ret.SetContext(Value::eContextTypeClangType, return_qualtype);
    
    // Now we're ready to call the function:
    ClangFunction func (*exe_ctx.GetBestExecutionContextScope(),
                        ast_context, 
                        return_qualtype, 
                        *function_address, 
                        arg_value_list);

    StreamString error_stream;
    
    lldb::addr_t wrapper_struct_addr = LLDB_INVALID_ADDRESS;
    func.InsertFunction(exe_ctx, wrapper_struct_addr, error_stream);

    bool unwind_on_error = true;
    bool try_all_threads = true;
    bool stop_others = true;
    
    ExecutionResults results = func.ExecuteFunction (exe_ctx, 
                                                     &wrapper_struct_addr, 
                                                     error_stream, 
                                                     stop_others, 
                                                     1000000, 
                                                     try_all_threads, 
                                                     unwind_on_error, 
                                                     ret);
    if (results != eExecutionCompleted)
    {
        strm.Printf("Error evaluating Print Object function: %d.\n", results);
        return false;
    }
       
    addr_t result_ptr = ret.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
    
    char buf[512];
    size_t cstr_len = 0;    
    size_t full_buffer_len = sizeof (buf) - 1;
    size_t curr_len = full_buffer_len;
    while (curr_len == full_buffer_len)
    {
        Error error;
        curr_len = process->ReadCStringFromMemory(result_ptr + cstr_len, buf, sizeof(buf), error);
        strm.Write (buf, curr_len);
        cstr_len += curr_len;
    }
    return cstr_len > 0;
}
Example #18
0
Target *createTargetByString (std::string tar_string, bool debug)
{
	Target *rtar = NULL;

	LibnovaRaDec raDec;

	int ret = raDec.parseString (tar_string.c_str ());
	if (ret == 0)
	{
		std::string new_prefix;

		// default prefix for new RTS2 sources
		new_prefix = std::string ("RTS2_");

		// set name..
		ConstTarget *constTarget = new ConstTarget ();
		constTarget->setPosition (raDec.getRa (), raDec.getDec ());
		std::ostringstream os;

		rts2core::Configuration::instance ()->getString ("newtarget", "prefix", new_prefix, "RTS2");
		os << new_prefix << LibnovaRaComp (raDec.getRa ()) << LibnovaDeg90Comp (raDec.getDec ());
		constTarget->setTargetName (os.str ().c_str ());
		constTarget->setTargetType (TYPE_OPORTUNITY);
		return constTarget;
	}
	// if it's MPC ephemeris..
	rtar = new EllTarget ();
	ret = ((EllTarget *) rtar)->orbitFromMPC (tar_string.c_str ());
	if (ret == 0)
		return rtar;

	delete rtar;

	try
	{
		rtar = new TLETarget ();
		((TLETarget *) rtar)->orbitFromTLE (tar_string);
		return rtar;
	}
	catch (rts2core::Error &er)
	{
	}

	delete rtar;

	XmlRpcLogHandler::setVerbosity (debug ? 5 : 0);

	// try to get target from SIMBAD
	try
	{
		rtar = new rts2db::SimbadTargetDb (tar_string.c_str ());
		rtar->load ();
		rtar->setTargetType (TYPE_OPORTUNITY);
		return rtar;
	}
	catch (rts2core::Error &er)
	{
		delete rtar;

		// MPEC fallback
		rtar = new rts2db::MPECTarget (tar_string.c_str ());
		rtar->load ();
		return rtar;
	}
}
Example #19
0
 void reinforce( const Target& obj ) const { obj.reinforce( *this ); }
bool
CommandObjectDisassemble::DoExecute (Args& command, CommandReturnObject &result)
{
    Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
    if (target == NULL)
    {
        result.AppendError ("invalid target, create a debug target using the 'target create' command");
        result.SetStatus (eReturnStatusFailed);
        return false;
    }
    if (!m_options.arch.IsValid())
        m_options.arch = target->GetArchitecture();

    if (!m_options.arch.IsValid())
    {
        result.AppendError ("use the --arch option or set the target architecure to disassemble");
        result.SetStatus (eReturnStatusFailed);
        return false;
    }

    const char *plugin_name = m_options.GetPluginName ();
    const char *flavor_string = m_options.GetFlavorString();

    DisassemblerSP disassembler = Disassembler::FindPlugin(m_options.arch, flavor_string, plugin_name);

    if (!disassembler)
    {
        if (plugin_name)
        {
            result.AppendErrorWithFormat ("Unable to find Disassembler plug-in named '%s' that supports the '%s' architecture.\n",
                                          plugin_name,
                                          m_options.arch.GetArchitectureName());
        }
        else
            result.AppendErrorWithFormat ("Unable to find Disassembler plug-in for the '%s' architecture.\n", 
                                          m_options.arch.GetArchitectureName());
        result.SetStatus (eReturnStatusFailed);
        return false;
    }
    else if (flavor_string != NULL && !disassembler->FlavorValidForArchSpec(m_options.arch, flavor_string))
        result.AppendWarningWithFormat("invalid disassembler flavor \"%s\", using default.\n", flavor_string);

    result.SetStatus (eReturnStatusSuccessFinishResult);

    if (command.GetArgumentCount() != 0)
    {
        result.AppendErrorWithFormat ("\"disassemble\" arguments are specified as options.\n");
        GetOptions()->GenerateOptionUsage (result.GetErrorStream(), this);
        result.SetStatus (eReturnStatusFailed);
        return false;
    }
    
    if (m_options.show_mixed && m_options.num_lines_context == 0)
        m_options.num_lines_context = 1;

    // Always show the PC in the disassembly
    uint32_t options = Disassembler::eOptionMarkPCAddress;

    // Mark the source line for the current PC only if we are doing mixed source and assembly
    if (m_options.show_mixed)
        options |= Disassembler::eOptionMarkPCSourceLine;

    if (m_options.show_bytes)
        options |= Disassembler::eOptionShowBytes;

    if (m_options.raw)
        options |= Disassembler::eOptionRawOuput;

    if (!m_options.func_name.empty())
    {
        ConstString name(m_options.func_name.c_str());
        
        if (Disassembler::Disassemble (m_interpreter.GetDebugger(), 
                                       m_options.arch,
                                       plugin_name,
                                       flavor_string,
                                       m_exe_ctx,
                                       name,
                                       NULL,    // Module *
                                       m_options.num_instructions,
                                       m_options.show_mixed ? m_options.num_lines_context : 0,
                                       options,
                                       result.GetOutputStream()))
        {
            result.SetStatus (eReturnStatusSuccessFinishResult);
        }
        else
        {
            result.AppendErrorWithFormat ("Unable to find symbol with name '%s'.\n", name.GetCString());
            result.SetStatus (eReturnStatusFailed);
        }
    } 
    else
    {
        std::vector<AddressRange> ranges;
        AddressRange range;
        StackFrame *frame = m_exe_ctx.GetFramePtr();
        if (m_options.frame_line)
        {
            if (frame == NULL)
            {
                result.AppendError ("Cannot disassemble around the current line without a selected frame.\n");
                result.SetStatus (eReturnStatusFailed);
                return false;
            }
            LineEntry pc_line_entry (frame->GetSymbolContext(eSymbolContextLineEntry).line_entry);
            if (pc_line_entry.IsValid())
            {
                range = pc_line_entry.range;
            }
            else
            {
                m_options.at_pc = true; // No line entry, so just disassemble around the current pc
                m_options.show_mixed = false;
            }
        }
        else if (m_options.current_function)
        {
            if (frame == NULL)
            {
                result.AppendError ("Cannot disassemble around the current function without a selected frame.\n");
                result.SetStatus (eReturnStatusFailed);
                return false;
            }
            Symbol *symbol = frame->GetSymbolContext(eSymbolContextSymbol).symbol;
            if (symbol)
            {
                range.GetBaseAddress() = symbol->GetAddress();
                range.SetByteSize(symbol->GetByteSize());
            }
        }

        // Did the "m_options.frame_line" find a valid range already? If so
        // skip the rest...
        if (range.GetByteSize() == 0)
        {
            if (m_options.at_pc)
            {
                if (frame == NULL)
                {
                    result.AppendError ("Cannot disassemble around the current PC without a selected frame.\n");
                    result.SetStatus (eReturnStatusFailed);
                    return false;
                }
                range.GetBaseAddress() = frame->GetFrameCodeAddress();
                if (m_options.num_instructions == 0)
                {
                    // Disassembling at the PC always disassembles some number of instructions (not the whole function).
                    m_options.num_instructions = DEFAULT_DISASM_NUM_INS;
                }
                ranges.push_back(range);
            }
            else
            {
                range.GetBaseAddress().SetOffset (m_options.start_addr);
                if (range.GetBaseAddress().IsValid())
                {
                    if (m_options.end_addr != LLDB_INVALID_ADDRESS)
                    {
                        if (m_options.end_addr <= m_options.start_addr)
                        {
                            result.AppendErrorWithFormat ("End address before start address.\n");
                            result.SetStatus (eReturnStatusFailed);
                            return false;            
                        }
                        range.SetByteSize (m_options.end_addr - m_options.start_addr);
                    }
                    ranges.push_back(range);
                }
                else
                {
                    if (m_options.symbol_containing_addr != LLDB_INVALID_ADDRESS 
                        && target)
                    {
                        if (!target->GetSectionLoadList().IsEmpty())
                        {
                            bool failed = false;
                            Address symbol_containing_address;
                            if (target->GetSectionLoadList().ResolveLoadAddress (m_options.symbol_containing_addr, symbol_containing_address))
                            {
                                ModuleSP module_sp (symbol_containing_address.GetModule());
                                SymbolContext sc;
                                bool resolve_tail_call_address = true; // PC can be one past the address range of the function.
                                module_sp->ResolveSymbolContextForAddress (symbol_containing_address, eSymbolContextEverything, sc,
                                                                           resolve_tail_call_address);
                                if (sc.function || sc.symbol)
                                {
                                    sc.GetAddressRange (eSymbolContextFunction | eSymbolContextSymbol, 0, false, range);
                                }
                                else
                                {
                                    failed = true;
                                }
                            }
                            else
                            {
                                failed = true;
                            }
                            if (failed)
                            {
                                result.AppendErrorWithFormat ("Could not find function bounds for address 0x%" PRIx64 "\n", m_options.symbol_containing_addr);
                                result.SetStatus (eReturnStatusFailed);
                                return false;
                            }
                            ranges.push_back(range);
                        }
                        else
                        {
                            for (lldb::ModuleSP module_sp : target->GetImages().Modules())
                            {
                                lldb::addr_t file_addr = m_options.symbol_containing_addr;
                                Address file_address;
                                if (module_sp->ResolveFileAddress(file_addr, file_address))
                                {
                                    SymbolContext sc;
                                    bool resolve_tail_call_address = true; // PC can be one past the address range of the function.
                                    module_sp->ResolveSymbolContextForAddress (file_address, eSymbolContextEverything, sc, resolve_tail_call_address);
                                    if (sc.function || sc.symbol)
                                    {
                                        sc.GetAddressRange (eSymbolContextFunction | eSymbolContextSymbol, 0, false, range);
                                        ranges.push_back(range);
                                    }
                                }
                            }
                            
                        }
                    }
                }
            }
        }
        else
            ranges.push_back(range);

        if (m_options.num_instructions != 0)
        {
            if (ranges.size() == 0)
            {
                // The default action is to disassemble the current frame function.
                if (frame)
                {
                    SymbolContext sc(frame->GetSymbolContext(eSymbolContextFunction | eSymbolContextSymbol));
                    if (sc.function)
                        range.GetBaseAddress() = sc.function->GetAddressRange().GetBaseAddress();
                    else if (sc.symbol && sc.symbol->ValueIsAddress())
                        range.GetBaseAddress() = sc.symbol->GetAddress();
                    else
                        range.GetBaseAddress() = frame->GetFrameCodeAddress();
                }
                
                if (!range.GetBaseAddress().IsValid())
                {
                    result.AppendError ("invalid frame");
                    result.SetStatus (eReturnStatusFailed);
                    return false;
                }
            }
            
            bool print_sc_header = ranges.size() > 1;
            for (AddressRange cur_range : ranges)
            {
                if (Disassembler::Disassemble (m_interpreter.GetDebugger(),
                                               m_options.arch,
                                               plugin_name,
                                               flavor_string,
                                               m_exe_ctx,
                                               cur_range.GetBaseAddress(),
                                               m_options.num_instructions,
                                               m_options.show_mixed ? m_options.num_lines_context : 0,
                                               options,
                                               result.GetOutputStream()))
                {
                    result.SetStatus (eReturnStatusSuccessFinishResult);
                }
                else
                {
                    if (m_options.start_addr != LLDB_INVALID_ADDRESS)
                        result.AppendErrorWithFormat ("Failed to disassemble memory at 0x%8.8" PRIx64 ".\n", m_options.start_addr);
                    else if (m_options.symbol_containing_addr != LLDB_INVALID_ADDRESS)
                        result.AppendErrorWithFormat ("Failed to disassemble memory in function at 0x%8.8" PRIx64 ".\n", m_options.symbol_containing_addr);
                    result.SetStatus (eReturnStatusFailed);
                }
            }
            if (print_sc_header)
                result.AppendMessage("\n");
        }
        else
        {
            if (ranges.size() == 0)
            {
                // The default action is to disassemble the current frame function.
                if (frame)
                {
                    SymbolContext sc(frame->GetSymbolContext(eSymbolContextFunction | eSymbolContextSymbol));
                    if (sc.function)
                        range = sc.function->GetAddressRange();
                    else if (sc.symbol && sc.symbol->ValueIsAddress())
                    {
                        range.GetBaseAddress() = sc.symbol->GetAddress();
                        range.SetByteSize (sc.symbol->GetByteSize());
                    }
                    else
                        range.GetBaseAddress() = frame->GetFrameCodeAddress();
                }
                else
                {
                    result.AppendError ("invalid frame");
                    result.SetStatus (eReturnStatusFailed);
                    return false;
                }
                ranges.push_back(range);
            }
            
            bool print_sc_header = ranges.size() > 1;
            for (AddressRange cur_range : ranges)
            {
                if (cur_range.GetByteSize() == 0)
                    cur_range.SetByteSize(DEFAULT_DISASM_BYTE_SIZE);

                if (Disassembler::Disassemble (m_interpreter.GetDebugger(),
                                               m_options.arch,
                                               plugin_name,
                                               flavor_string,
                                               m_exe_ctx,
                                               cur_range,
                                               m_options.num_instructions,
                                               m_options.show_mixed ? m_options.num_lines_context : 0,
                                               options,
                                               result.GetOutputStream()))
                {
                    result.SetStatus (eReturnStatusSuccessFinishResult);
                }
                else
                {
                    result.AppendErrorWithFormat ("Failed to disassemble memory at 0x%8.8" PRIx64 ".\n", m_options.start_addr);
                    result.SetStatus (eReturnStatusFailed);            
                }
                if (print_sc_header)
                    result.AppendMessage("\n");
            }
        }
    }

    return result.Succeeded();
}
Example #21
0
bool
CommandObjectDisassemble::Execute
(
    CommandInterpreter &interpreter,
    Args& command,
    CommandReturnObject &result
)
{
    Target *target = interpreter.GetDebugger().GetCurrentTarget().get();
    if (target == NULL)
    {
        result.AppendError ("invalid target, set executable file using 'file' command");
        result.SetStatus (eReturnStatusFailed);
        return false;
    }

    ArchSpec arch(target->GetArchitecture());
    if (!arch.IsValid())
    {
        result.AppendError ("target needs valid architecure in order to be able to disassemble");
        result.SetStatus (eReturnStatusFailed);
        return false;
    }

    Disassembler *disassembler = Disassembler::FindPlugin(arch);

    if (disassembler == NULL)
    {
        result.AppendErrorWithFormat ("Unable to find Disassembler plug-in for %s architecture.\n", arch.AsCString());
        result.SetStatus (eReturnStatusFailed);
        return false;
    }

    result.SetStatus (eReturnStatusSuccessFinishResult);

    if (command.GetArgumentCount() != 0)
    {
        result.AppendErrorWithFormat ("\"disassemble\" doesn't take any arguments.\n");
        result.SetStatus (eReturnStatusFailed);
        return false;
    }
    ExecutionContext exe_ctx(interpreter.GetDebugger().GetExecutionContext());

    if (m_options.show_mixed && m_options.num_lines_context == 0)
        m_options.num_lines_context = 3;

    if (!m_options.m_func_name.empty())
    {
        ConstString name(m_options.m_func_name.c_str());
        
        if (Disassembler::Disassemble (interpreter.GetDebugger(), 
                                       arch,
                                       exe_ctx,
                                       name,
                                       NULL,    // Module *
                                       m_options.show_mixed ? m_options.num_lines_context : 0,
                                       m_options.show_bytes,
                                       result.GetOutputStream()))
        {
            result.SetStatus (eReturnStatusSuccessFinishResult);
        }
        else
        {
            result.AppendErrorWithFormat ("Unable to find symbol with name '%s'.\n", name.GetCString());
            result.SetStatus (eReturnStatusFailed);
        }
    } 
    else
    {
        AddressRange range;
        if (m_options.m_start_addr != LLDB_INVALID_ADDRESS)
        {
            range.GetBaseAddress().SetOffset (m_options.m_start_addr);
            if (m_options.m_end_addr != LLDB_INVALID_ADDRESS)
            {
                if (m_options.m_end_addr < m_options.m_start_addr)
                {
                    result.AppendErrorWithFormat ("End address before start address.\n");
                    result.SetStatus (eReturnStatusFailed);
                    return false;            
                }
                range.SetByteSize (m_options.m_end_addr - m_options.m_start_addr);
            }
            else
                range.SetByteSize (DEFAULT_DISASM_BYTE_SIZE);
        } 
        else
        {
            if (exe_ctx.frame)
            {
                SymbolContext sc(exe_ctx.frame->GetSymbolContext(eSymbolContextFunction | eSymbolContextSymbol));
                if (sc.function)
                    range = sc.function->GetAddressRange();
                else if (sc.symbol && sc.symbol->GetAddressRangePtr())
                    range = *sc.symbol->GetAddressRangePtr();
                else
                    range.GetBaseAddress() = exe_ctx.frame->GetPC();
            }
            else
            {
                result.AppendError ("invalid frame");
                result.SetStatus (eReturnStatusFailed);
                return false;
            }
        }
        if (range.GetByteSize() == 0)
            range.SetByteSize(DEFAULT_DISASM_BYTE_SIZE);

        if (Disassembler::Disassemble (interpreter.GetDebugger(), 
                                       arch,
                                       exe_ctx,
                                       range,
                                       m_options.show_mixed ? m_options.num_lines_context : 0,
                                       m_options.show_bytes,
                                       result.GetOutputStream()))
        {
            result.SetStatus (eReturnStatusSuccessFinishResult);
        }
        else
        {
            result.AppendErrorWithFormat ("Failed to disassemble memory at 0x%8.8llx.\n", m_options.m_start_addr);
            result.SetStatus (eReturnStatusFailed);            
        }
    }

    return result.Succeeded();
}
Error
CommandObjectDisassemble::CommandOptions::SetOptionValue (uint32_t option_idx, const char *option_arg)
{
    Error error;

    const int short_option = m_getopt_table[option_idx].val;

    bool success;
    
    switch (short_option)
    {
    case 'm':
        show_mixed = true;
        break;

    case 'C':
        num_lines_context = StringConvert::ToUInt32(option_arg, 0, 0, &success);
        if (!success)
            error.SetErrorStringWithFormat ("invalid num context lines string: \"%s\"", option_arg);
        break;

    case 'c':
        num_instructions = StringConvert::ToUInt32(option_arg, 0, 0, &success);
        if (!success)
            error.SetErrorStringWithFormat ("invalid num of instructions string: \"%s\"", option_arg);
        break;

    case 'b':
        show_bytes = true;
        break;

    case 's':
        {
            ExecutionContext exe_ctx (m_interpreter.GetExecutionContext());
            start_addr = Args::StringToAddress(&exe_ctx, option_arg, LLDB_INVALID_ADDRESS, &error);
            if (start_addr != LLDB_INVALID_ADDRESS)
                some_location_specified = true;
        }
        break;
    case 'e':
        {
            ExecutionContext exe_ctx (m_interpreter.GetExecutionContext());
            end_addr = Args::StringToAddress(&exe_ctx, option_arg, LLDB_INVALID_ADDRESS, &error);
            if (end_addr != LLDB_INVALID_ADDRESS)
                some_location_specified = true;
        }
        break;
    case 'n':
        func_name.assign (option_arg);
        some_location_specified = true;
        break;

    case 'p':
        at_pc = true;
        some_location_specified = true;
        break;

    case 'l':
        frame_line = true;
        // Disassemble the current source line kind of implies showing mixed
        // source code context. 
        show_mixed = true;
        some_location_specified = true;
        break;

    case 'P':
        plugin_name.assign (option_arg);
        break;

    case 'F':
        {
            Target *target = m_interpreter.GetExecutionContext().GetTargetPtr();
            if (target->GetArchitecture().GetTriple().getArch() == llvm::Triple::x86
                || target->GetArchitecture().GetTriple().getArch() == llvm::Triple::x86_64)
            {
                flavor_string.assign (option_arg);
            }
            else
                error.SetErrorStringWithFormat("Disassembler flavors are currently only supported for x86 and x86_64 targets.");
            break;
        }
    case 'r':
        raw = true;
        break;

    case 'f':
        current_function = true;
        some_location_specified = true;
        break;

    case 'A':
        if (!arch.SetTriple (option_arg, m_interpreter.GetPlatform (true).get()))
            arch.SetTriple (option_arg);
        break;

    case 'a':
        {
            ExecutionContext exe_ctx (m_interpreter.GetExecutionContext());
            symbol_containing_addr = Args::StringToAddress(&exe_ctx, option_arg, LLDB_INVALID_ADDRESS, &error);
            if (symbol_containing_addr != LLDB_INVALID_ADDRESS)
            {
                some_location_specified = true;
            }
        }
        break;

    default:
        error.SetErrorStringWithFormat("unrecognized short option '%c'", short_option);
        break;
    }

    return error;
}
Example #23
0
void
MoonEGLContext::Project (MoonSurface  *src,
		     const double *matrix,
		     double       alpha,
		     double       x,
		     double       y)
{
	MoonEGLSurface *surface = (MoonEGLSurface *) src;
	Target     *target = Top ()->GetTarget ();
	Rect       r = target->GetData (NULL);
	Rect       clip = GetClip ();
	double     m[16];

	if (!target->GetInit () && !IS_TRANSLUCENT (alpha) && r == clip) {
		int x0, y0;

		GetMatrix (m);
		if (matrix)
			Matrix3D::Multiply (m, matrix, m);

		if (Matrix3D::IsIntegerTranslation (m, &x0, &y0)) {
			MoonEGLSurface *surface = (MoonEGLSurface *) src;
			Rect       r = Rect (x + x0,
						y + y0,
						surface->Width (),
						surface->Height ());

			// matching dimensions and no transformation allow us
			// to set source as initial state of target surface when
			// it is not already initialized.

			if (r == clip) {
				target->SetInit (src);
				return;
			}
		}
	}

	if (!HasDrawable () && !surface->HasTexture ()) {
		int x0, y0;

		GetMatrix (m);
		if (matrix)
			Matrix3D::Multiply (m, matrix, m);

		// avoid GL rendering to target without previously
		// allocated hardware drawable
		if (Matrix3D::IsIntegerTranslation (m, &x0, &y0)) {
			cairo_matrix_t m;

			cairo_matrix_init_translate (&m, x0, y0);

			Context::Push (Context::AbsoluteTransform (m));
			Context::Paint (src, alpha, x, y);
			Context::Pop ();
			return;
		}
	}

	GetDeviceMatrix (m);
	if (matrix)
		Matrix3D::Multiply (m, matrix, m);

	ForceCurrent ();

	GLContext::Paint (src, m, alpha, x, y);
}
Example #24
0
/// Locates the address of the rendezvous structure.  Returns the address on
/// success and LLDB_INVALID_ADDRESS on failure.
static addr_t
ResolveRendezvousAddress(Process *process)
{
    Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
    addr_t info_location;
    addr_t info_addr;
    Error error;

    if (!process)
    {
        if (log)
            log->Printf ("%s null process provided", __FUNCTION__);
        return LLDB_INVALID_ADDRESS;
    }

    // Try to get it from our process.  This might be a remote process and might
    // grab it via some remote-specific mechanism.
    info_location = process->GetImageInfoAddress();
    if (log)
        log->Printf ("%s info_location = 0x%" PRIx64, __FUNCTION__, info_location);

    // If the process fails to return an address, fall back to seeing if the local object file can help us find it.
    if (info_location == LLDB_INVALID_ADDRESS)
    {
        Target *target = &process->GetTarget();
        if (target)
        {
            ObjectFile *obj_file = target->GetExecutableModule()->GetObjectFile();
            Address addr = obj_file->GetImageInfoAddress(target);

            if (addr.IsValid())
            {
                info_location = addr.GetLoadAddress(target);
                if (log)
                    log->Printf ("%s resolved via direct object file approach to 0x%" PRIx64, __FUNCTION__, info_location);
            }
            else
            {
                if (log)
                    log->Printf ("%s FAILED - direct object file approach did not yield a valid address", __FUNCTION__);
            }
        }
    }

    if (info_location == LLDB_INVALID_ADDRESS)
    {
        if (log)
            log->Printf ("%s FAILED - invalid info address", __FUNCTION__);
        return LLDB_INVALID_ADDRESS;
    }

    if (log)
        log->Printf ("%s reading pointer (%" PRIu32 " bytes) from 0x%" PRIx64, __FUNCTION__, process->GetAddressByteSize(), info_location);

    info_addr = process->ReadPointerFromMemory(info_location, error);
    if (error.Fail())
    {
        if (log)
            log->Printf ("%s FAILED - could not read from the info location: %s", __FUNCTION__, error.AsCString ());
        return LLDB_INVALID_ADDRESS;
    }

    if (info_addr == 0)
    {
        if (log)
            log->Printf ("%s FAILED - the rendezvous address contained at 0x%" PRIx64 " returned a null value", __FUNCTION__, info_location);
        return LLDB_INVALID_ADDRESS;
    }

    return info_addr;
}
Example #25
0
Func demosaic(Func deinterleaved) {
    // These are the values we already know from the input
    // x_y = the value of channel x at a site in the input of channel y
    // gb refers to green sites in the blue rows
    // gr refers to green sites in the red rows

    // Give more convenient names to the four channels we know
    Func r_r, g_gr, g_gb, b_b;
    g_gr(x, y) = deinterleaved(x, y, 0);
    r_r(x, y)  = deinterleaved(x, y, 1);
    b_b(x, y)  = deinterleaved(x, y, 2);
    g_gb(x, y) = deinterleaved(x, y, 3);

    // These are the ones we need to interpolate
    Func b_r, g_r, b_gr, r_gr, b_gb, r_gb, r_b, g_b;

    // First calculate green at the red and blue sites

    // Try interpolating vertically and horizontally. Also compute
    // differences vertically and horizontally. Use interpolation in
    // whichever direction had the smallest difference.
    Expr gv_r  = avg(g_gb(x, y-1), g_gb(x, y));
    Expr gvd_r = absd(g_gb(x, y-1), g_gb(x, y));
    Expr gh_r  = avg(g_gr(x+1, y), g_gr(x, y));
    Expr ghd_r = absd(g_gr(x+1, y), g_gr(x, y));

    g_r(x, y)  = select(ghd_r < gvd_r, gh_r, gv_r);

    Expr gv_b  = avg(g_gr(x, y+1), g_gr(x, y));
    Expr gvd_b = absd(g_gr(x, y+1), g_gr(x, y));
    Expr gh_b  = avg(g_gb(x-1, y), g_gb(x, y));
    Expr ghd_b = absd(g_gb(x-1, y), g_gb(x, y));

    g_b(x, y)  = select(ghd_b < gvd_b, gh_b, gv_b);

    // Next interpolate red at gr by first interpolating, then
    // correcting using the error green would have had if we had
    // interpolated it in the same way (i.e. add the second derivative
    // of the green channel at the same place).
    Expr correction;
    correction = g_gr(x, y) - avg(g_r(x, y), g_r(x-1, y));
    r_gr(x, y) = correction + avg(r_r(x-1, y), r_r(x, y));

    // Do the same for other reds and blues at green sites
    correction = g_gr(x, y) - avg(g_b(x, y), g_b(x, y-1));
    b_gr(x, y) = correction + avg(b_b(x, y), b_b(x, y-1));

    correction = g_gb(x, y) - avg(g_r(x, y), g_r(x, y+1));
    r_gb(x, y) = correction + avg(r_r(x, y), r_r(x, y+1));

    correction = g_gb(x, y) - avg(g_b(x, y), g_b(x+1, y));
    b_gb(x, y) = correction + avg(b_b(x, y), b_b(x+1, y));

    // Now interpolate diagonally to get red at blue and blue at
    // red. Hold onto your hats; this gets really fancy. We do the
    // same thing as for interpolating green where we try both
    // directions (in this case the positive and negative diagonals),
    // and use the one with the lowest absolute difference. But we
    // also use the same trick as interpolating red and blue at green
    // sites - we correct our interpolations using the second
    // derivative of green at the same sites.

    correction = g_b(x, y)  - avg(g_r(x, y), g_r(x-1, y+1));
    Expr rp_b  = correction + avg(r_r(x, y), r_r(x-1, y+1));
    Expr rpd_b = absd(r_r(x, y), r_r(x-1, y+1));

    correction = g_b(x, y)  - avg(g_r(x-1, y), g_r(x, y+1));
    Expr rn_b  = correction + avg(r_r(x-1, y), r_r(x, y+1));
    Expr rnd_b = absd(r_r(x-1, y), r_r(x, y+1));

    r_b(x, y)  = select(rpd_b < rnd_b, rp_b, rn_b);


    // Same thing for blue at red
    correction = g_r(x, y)  - avg(g_b(x, y), g_b(x+1, y-1));
    Expr bp_r  = correction + avg(b_b(x, y), b_b(x+1, y-1));
    Expr bpd_r = absd(b_b(x, y), b_b(x+1, y-1));

    correction = g_r(x, y)  - avg(g_b(x+1, y), g_b(x, y-1));
    Expr bn_r  = correction + avg(b_b(x+1, y), b_b(x, y-1));
    Expr bnd_r = absd(b_b(x+1, y), b_b(x, y-1));

    b_r(x, y)  =  select(bpd_r < bnd_r, bp_r, bn_r);

    // Interleave the resulting channels
    Func r = interleave_y(interleave_x(r_gr, r_r),
                          interleave_x(r_b, r_gb));
    Func g = interleave_y(interleave_x(g_gr, g_r),
                          interleave_x(g_b, g_gb));
    Func b = interleave_y(interleave_x(b_gr, b_r),
                          interleave_x(b_b, b_gb));

    Func output;
    output(x, y, c) = select(c == 0, r(x, y),
                             c == 1, g(x, y),
                                     b(x, y));


    /* THE SCHEDULE */
    int vec = target.natural_vector_size(UInt(16));
    if (target.has_feature(Target::HVX_64)) {
        vec = 32;
    } else if (target.has_feature(Target::HVX_128)) {
        vec = 64;
    }
    g_r.compute_at(processed, yi)
        .store_at(processed, yo)
        .vectorize(x, vec, TailStrategy::RoundUp)
        .fold_storage(y, 2);
    g_b.compute_at(processed, yi)
        .store_at(processed, yo)
        .vectorize(x, vec, TailStrategy::RoundUp)
        .fold_storage(y, 2);
    output.compute_at(processed, x)
        .vectorize(x)
        .unroll(y)
        .reorder(c, x, y)
        .unroll(c);

    if (target.features_any_of({Target::HVX_64, Target::HVX_128})) {
        g_r.align_storage(x, vec);
        g_b.align_storage(x, vec);
    }

    return output;
}
Example #26
0
void Target::checkState() {
  if (_state == INITIALIZED) {
    _state = CHECKING_STATE;

    // Check output files
    bool needsRebuild = false;
    bool needsRebuildDeps = false;
    File * oldestOutput = NULL;
    for (FileList::const_iterator it = _outputs.begin(), itEnd = _outputs.end(); it != itEnd;
        ++it) {
      File * f = *it;
      if (!f->statusChecked()) {
        //console::out() << "    Checking status of " << f->name() << "\n";
        if (!f->updateFileStatus()) {
          continue;
        }
      }
      if (f->statusValid()) {
        if (!f->exists()) {
          if (!needsRebuild) {
            if (VERBOSE) {
              console::out() << "  Output " << f << " is missing.\n";
            }
          }
          needsRebuild = true;
          break;
        } else if (oldestOutput == NULL || f->lastModified() < oldestOutput->lastModified()) {
          oldestOutput = f;
        }
      }
    }

    if (_outputs.empty()) {
      needsRebuild = true;
    }

    // Check source files. Don't bother checking source file timestamps if we know we need
    // a rebuild, or if there are no declared outputs.
    for (FileList::const_iterator it = _sources.begin(), itEnd = _sources.end(); it != itEnd;
        ++it) {
      File * f = *it;
      if (!f->statusChecked()) {
        //console::out() << "    Checking status of " << f->name() << "\n";
        if (!f->updateFileStatus()) {
          continue;
        }
      }
      if (f->statusValid()) {
        // If this file is the output of another target, then unless that target is up
        // to date, then it doesn't matter what the timestamp of the output is in.
        if (!f->exists()) {
          needsRebuild = true;
        }
        if (!f->outputOf().empty() && !isSourceOnly()) {
          for (TargetList::const_iterator ti = f->outputOf().begin(), tiEnd = f->outputOf().end();
              ti != tiEnd; ++ti) {
            Target * dep = *ti;
            if (dep->state() == CHECKING_STATE) {
              diag::error(this->location()) << "Circular dependency between target: " << this;
              diag::info(dep->location()) << "and target: " << dep;
              continue;
            }
            dep->checkState();
            if (dep->state() == READY || dep->state() == WAITING || dep->state() == BUILDING) {
              needsRebuild = true;
              needsRebuildDeps = true;
            }
            // TODO: Do we want to add to implicit deps?
          }
        } else if (!f->exists()) {
          diag::error(this->location()) << "Target " << this << " depends on non-existent file "
              << f->name();
          break;
        } else if (oldestOutput != NULL && oldestOutput->lastModified() < f->lastModified()) {
          if (!needsRebuild) {
            if (VERBOSE) {
              console::out() << "  Output " << oldestOutput << " is older than source " << f << ".\n";
            }
          }
          needsRebuild = true;
        }
      }
    }

    for (TargetList::const_iterator ti = _depends.begin(), tiEnd = _depends.end(); ti != tiEnd;
        ++ti) {
      Target * dep = *ti;
      if (dep->state() == CHECKING_STATE) {
        diag::error(this->location()) << "Circular dependency between target: " << this;
        diag::info(dep->location()) << "and target: " << dep;
        continue;
      }
      dep->checkState();
      if (dep->state() == READY || dep->state() == WAITING || dep->state() == BUILDING) {
        needsRebuild = true;
        needsRebuildDeps = true;
      }
    }

    if (needsRebuild) {
      if (needsRebuildDeps) {
        _state = WAITING;
        if (VERBOSE) {
          console::out() << "Target " << this << " is waiting on other targets\n";
        }
      } else {
        _state = READY;
        if (VERBOSE) {
          console::out() << "Target " << this << " is ready to build\n";
        }
      }
    } else {
      _state = FINISHED;
      if (VERBOSE) {
        console::out() << "Target " << this << " is up to date\n";
        console::out() << "Target has " << _depends.size() << " dependencies, and " << _dependents.size() << " dependents.\n";
      }
    }
  } else {
    //console::out() << "Target " << this << " is in a weird state: " << _state << ".\n";
  }
}
Example #27
0
bool CardSelector::CheckUserInput(JButton key)
{
    if (!active)
    {
        for (vector<Target*>::iterator it = cards.begin(); it != cards.end(); ++it)
            if ((NULL == limitor) || (limitor->select(*it)))
            {
                active = *it;
                active->Entering();
                return true;
            }
        return true;
    }
    Target* oldactive = active;
    timer = 800;
    int x,y;
    JGE* jge = observer->getInput();
    if(!jge) return false;
    if(jge->GetLeftClickCoordinates(x, y))
    {
        active = closest<CardSelectorTrue> (cards, limitor, static_cast<float> (x), static_cast<float> (y));
    }

    switch (key)
    {
    case JGE_BTN_SEC:
        observer->cancelCurrentAction();
        goto switch_active;
        break;
    case JGE_BTN_OK:
        observer->ButtonPressed(active);
        goto switch_active;
        break;
    case JGE_BTN_LEFT:
        active = closest<CardSelectorLeft> (cards, limitor, active);
        break;
    case JGE_BTN_RIGHT:
        active = closest<CardSelectorRight> (cards, limitor, active);
        break;
    case JGE_BTN_UP:
        active = closest<CardSelectorUp> (cards, limitor, active);
        break;
    case JGE_BTN_DOWN:
        active = closest<CardSelectorDown> (cards, limitor, active);
        break;
    case JGE_BTN_CANCEL:
        mDrawMode = (mDrawMode + 1) % DrawMode::kNumDrawModes;
        if (mDrawMode == DrawMode::kText)
            options[Options::DISABLECARDS].number = 1;
        else
            options[Options::DISABLECARDS].number = 0;
        return true;
    default:
      {
        if(!jge->GetLeftClickCoordinates(x, y))
        {
          return false;
        }
      }
    }
    if(key != JGE_BTN_NONE)
    {
      if (active != oldactive)
      {
          CardView::SelectorZone oldowner, owner;
          if (CardView *q = dynamic_cast<CardView*>(oldactive))
              oldowner = q->owner;
          else
              oldowner = CardView::nullZone;
          if (CardView *q = dynamic_cast<CardView*>(active))
              owner = q->owner;
          else
              owner = CardView::nullZone;
          if (oldowner != owner)
          {
              if (CardView::nullZone != owner)
              {
                  if (PlayGuiObject* old = fetchMemory(lasts[owner]))
                      switch (key)
                      {
                      case JGE_BTN_LEFT:
                          if (old->x < oldactive->x)
                              active = old;
                          break;
                      case JGE_BTN_RIGHT:
                          if (old->x > oldactive->x)
                              active = old;
                          break;
                      case JGE_BTN_UP:
                          if (old->y < oldactive->y)
                              active = old;
                          break;
                      case JGE_BTN_DOWN:
                          if (old->y > oldactive->y)
                              active = old;
                          break;
                      default:
                          if (old)
                              active = old;
                          break;
                      }
              }
              lasts[oldowner] = SelectorMemory(oldactive);
          }
      }
      else
      {
          // active card hasn't changed - that means we're probably at an edge of the battlefield.
          // check if we're not already a selected avatar - if not, select one depending whether we're going up/down.
          GuiAvatar* avatar = dynamic_cast<GuiAvatar*> (active);
          if (!avatar)
          {
              if (key == JGE_BTN_DOWN)
              {
                  active = duel->GetAvatars()->GetSelf();
              }
              else if (key == JGE_BTN_UP)
              {
                  active = duel->GetAvatars()->GetOpponent();
              }
          }
      }
    }

switch_active:
    if (active != oldactive)
    {
        {
            PlayGuiObject* c = dynamic_cast<PlayGuiObject*> (oldactive);
            if (c)
                c->zoom = 1.0f;
        }
        {
            PlayGuiObject* c = dynamic_cast<PlayGuiObject*> (active);
            if (c)
                c->zoom = 1.4f;
        }
        if (oldactive)
            oldactive->Leaving(JGE_BTN_NONE);
        if (active)
            active->Entering();
    }
    else
    {
        timer = 800;
    }
    return true;
}
Example #28
0
//
// Performing accesses based on specifications to targets.
// The following function initiates I/O, recording performance information only when the
// grunt is in the TestRecording state.  The function needs to be as efficient as possible
// while still being readable and maintainable.
//
// "data" is the location of data to use for transfers.
//
void Grunt::Do_IOs()
{
	////////////////////////////////////////////////////////////////////////////
	// these are working variables for the IO loop - they aren't referenced
	// outside of it and their values don't span more than one burst of data.
	//
	int				remaining_transactions_in_burst=0;	// how's that for a name?
	int				access_percent = 0;		// Determines the access spec.
	int				target_id;			// Index into target array of target to access.
	DWORD			size;				// Size of transfer request to target.
	int				transfer_delay;		// Milliseconds to wait before accessing.
	ReturnVal		transfer_result;	// Success/failure result of read or write operation.
	Transaction*	transaction = NULL;		// Pointer to the transaction being processed.
	DWORD			user_alignment;
	DWORDLONG		user_align_mask;
	DWORD			reply;				// Size of reply, or 0 for no reply
	DWORDLONG		conn_time;			// Used to calculate average and max connection times.
	Target*			target;
	Raw_Result		*target_results;	// Pointer to results for selected target.
	Raw_Result		*prev_target_results;

	
	while ( grunt_state != TestIdle )
	{
#if defined(IOMTR_OSFAMILY_NETWARE)
		pthread_yield();	// NetWare is non-preemptive
#elif defined(IOMTR_OSFAMILY_UNIX) || defined(IOMTR_OSFAMILY_WINDOWS)
		// nop
#else
 #warning ===> WARNING: You have to do some coding here to get the port done!
#endif
		// If we can't queue another request, wait for a completion.
		// If we CAN queue another request, get only one completion and do 
		// so immediately (with a time out of 0).
		Complete_IO( ( available_head == available_tail || 
			target_count == targets_closing_count ) ? TIMEOUT_TIME : 0 );

		// Now check to see if there really are any completed requests.
		// Complete_IO may not have freed a slot in the available queue.
		if ( available_head == available_tail )
			continue;	// repeat the outermost while loop

		// Getting an index into the target array of the next target to access.
		target_id = trans_slots[available_trans_queue[available_head]].target_id;
		target = targets[target_id];

		// Checking the next target to access to see if it is closing.
		// This if statement is separated from the one below for performance.
		if ( target->spec.test_connection_rate && target->is_closing )
		{
			// Target is closing.  Move it to the tail of the available queue.
			available_trans_queue[available_tail++] = 
				available_trans_queue[available_head++];
			if ( available_head > cur_trans_slots ) {
				available_head = 0;
			}
			if ( available_tail > cur_trans_slots ) {
				available_tail = 0;
			}

			// Check to see if we can close the target.  Targets are not closed
			// until all outstanding I/Os have completed.
			if ( target->outstanding_ios == 0 )
			{
				#if _DEBUG 
					cout << "Testing connection rate: Closing " 
						 << targets[target_id]->spec.name << endl;
				#endif

				// Close target and record connection time.
				target->Close( &grunt_state );
				conn_time = rdtsc() - target->conn_start_time;

				// Since target is closed, it is no longer closing.
				target->is_closing = FALSE;

				// Record connection latencies.
				if ( ramp_up_ios_pending <= 0 && grunt_state == TestRecording )
				{
					target_results = &(worker_performance.target_results.result[target_id]);
					target_results->connection_count++;
					target_results->connection_latency_sum += conn_time;
					if ( conn_time > target_results->max_raw_connection_latency )
						target_results->max_raw_connection_latency = conn_time;

					prev_target_results = &(prev_worker_performance.target_results.result[target_id]);
					if ( conn_time > prev_target_results->max_raw_connection_latency )
						prev_target_results->max_raw_connection_latency = conn_time;
				}
			}
			continue;
		}

		// Check to see if we need to open the target.
		if ( target->spec.test_connection_rate && target->trans_left_in_conn <= 0 )
		{
			#if _DEBUG
				cout << "Testing connection rate: Opening " 
					<< target->spec.name << endl;
			#endif
			// Set the number of transactions to do before closing.
			target->trans_left_in_conn = target->spec.trans_per_conn;
			// Record the start time for the transaction.
			target->conn_start_time = rdtsc();
			// Open the target.
			target->Open( &grunt_state );

			// If not doing any transactions, set the target to close.
			if ((target->is_closing = !target->spec.trans_per_conn))
				continue;
		}

		// "transaction" will now point to the next available
		// transaction slot
		transaction = &( trans_slots[ available_trans_queue[available_head] ] );

		// See if this is the start of a new transaction
		if ( ! (transaction->remaining_requests || transaction->remaining_replies) )
		{
			// No requests or replies remain, start a new transaction.

			// Check to see if this transaction will be the last one
			// before closing the target.
			target->is_closing = ( target->spec.test_connection_rate && 
				--target->trans_left_in_conn <= 0 );

			// See if we need to get a new access spec line.  All transactions
			// for the current burst have been sent.
			if ( --remaining_transactions_in_burst <= 0 )
			{
				access_spec.GetNextBurst( access_percent = (unsigned int)Rand() % 100,
					&remaining_transactions_in_burst, &size, &transfer_delay,
					&user_alignment, &user_align_mask, &reply );
				// Possibly waiting some delay before sending next burst of transfers.
				if ( transfer_delay )
					Asynchronous_Delay( transfer_delay );
			}

			// Fill in the information for a new transaction

			// Set number and size of requests.  (Currently always one request; we can support 
			// any number, but this is not yet implemented in Iometer.)
			transaction->request_size = size;
			transaction->remaining_requests = 1;

			// Set number and size of replies.  (Currently reply size = 0 means no reply, 
			// reply size != 0 means one reply; we can support any number, but this is not
			// yet implemented in Iometer.)
			transaction->reply_size = reply;
			transaction->remaining_replies = ( reply ? 1 : 0 );

			// Determine if the first I/O will be a read or write.
			// (is_read will change when replies are sent)
			transaction->is_read = access_spec.Read( access_percent,
							(unsigned int)target->Rand() % 100 );

			// Set flag to record transaction start time when the transaction actually begins.
			transaction->start_transaction = 0;
		}

		// Prepare the next I/O of the transaction...

		// Set the transaction's size.
		if ( transaction->remaining_requests )
			transaction->size = transaction->request_size;
		else
			transaction->size = transaction->reply_size;

		if ( IsType( target->spec.type, GenericDiskType ) )
		{
			((TargetDisk *) targets[target_id])->Seek( access_spec.Random( access_percent,
				(unsigned int)targets[target_id]->Rand() % 100 ), size,
				user_alignment, user_align_mask );
		}

		transaction->start_IO = (grunt_state == TestRecording) ? rdtsc() : 0;

		// If the transaction start time hasn't been set,
		// this is the first I/O of this transaction.  Set the start time.
		if ( !transaction->start_transaction )
			transaction->start_transaction = transaction->start_IO;

		//
		// Finally doing the actual I/O request - whew!  Continue to try to do
		// the I/O while it should be retried.  A retry indicates that there
		// currently aren't enough reources to fulfill the request.
		//
		do
		{
#if defined(IOMTR_OSFAMILY_NETWARE)
			pthread_yield();	// NetWare is Non-preemptive
#elif defined(IOMTR_OSFAMILY_UNIX) || defined(IOMTR_OSFAMILY_WINDOWS)
			// nop
#else
 #warning ===> WARNING: You have to do some coding here to get the port done!
#endif
			if ( transaction->is_read )
			{
				transfer_result = target->Read( read_data, transaction );
			}
			else
			{
				transfer_result = target->Write( write_data, transaction );
			}

			// Continue to process completions.  This may free up the resource
			// that is needed.
			if ( transfer_result == ReturnRetry )
				Complete_IO( TIMEOUT_TIME );
		}
		while ( transfer_result == ReturnRetry && grunt_state != TestIdle );

		// The request finished.  See what the result was and process it
		// accordingly.
		switch ( transfer_result )
		{
		case ReturnPending:
			// An I/O was successfully started, and its completion will be
			// posted to the completion queue.

			// Increment the number of outstanding I/Os to the target.
			target->outstanding_ios++;

			// See if the I/O occurred during the ramp up period.
			if ( !transaction->start_IO )
				++ramp_up_ios_pending;
			break;
		case ReturnSuccess:
			// The request completed successfully, and its completion will not
			// go to the completion queue.
			// We need to treat its full completion as "pending" to ensure that 
			// Record_IO can properly handle it.

			// Increment the number of outstanding I/Os to the target.
			target->outstanding_ios++;

			// See if the I/O occurred during the ramp up period.
			if ( !transaction->start_IO )
				++ramp_up_ios_pending;

			// An I/O completed successfully and will not go to the completion 
			// queue.  Record the request as done.
			Record_IO( transaction, rdtsc() );
			break;
		default:
			// see whether it should record the error
			if ( grunt_state == TestRecording )
			{
				// ERROR: The I/O was not queued successfully.
				cout << "*** Error performing I/O to " << target->spec.name << endl;

				if ( transaction->is_read )
					worker_performance.target_results.result[target_id].read_errors++;
				else
					worker_performance.target_results.result[target_id].write_errors++;
			}

			// Move the failed transaction to the end of the available queue to
			// allow other requests, if any, to have a chance of going.
			available_trans_queue[available_tail++] = 
				available_trans_queue[available_head];
			if ( available_tail > cur_trans_slots ) {
				available_tail = 0;
			}
		}

		// Move the head of the available queue to reflect the last request.
		if ( (++available_head) > cur_trans_slots ) {
			available_head = 0;
		}
	} // while grunt_state is not TestIdle
}
Example #29
0
void
BreakpointLocation::GetDescription (Stream *s, lldb::DescriptionLevel level)
{
    SymbolContext sc;
    
    // If the description level is "initial" then the breakpoint is printing out our initial state,
    // and we should let it decide how it wants to print our label.
    if (level != eDescriptionLevelInitial)
    {
        s->Indent();
        BreakpointID::GetCanonicalReference(s, m_owner.GetID(), GetID());
    }
    
    if (level == lldb::eDescriptionLevelBrief)
        return;

    if (level != eDescriptionLevelInitial)
        s->PutCString(": ");

    if (level == lldb::eDescriptionLevelVerbose)
        s->IndentMore();

    if (m_address.IsSectionOffset())
    {
        m_address.CalculateSymbolContext(&sc);

        if (level == lldb::eDescriptionLevelFull || level == eDescriptionLevelInitial)
        {
            if (IsReExported())
                s->PutCString ("re-exported target = ");
            else
                s->PutCString("where = ");
            sc.DumpStopContext (s, m_owner.GetTarget().GetProcessSP().get(), m_address, false, true, false, true, true);
        }
        else
        {
            if (sc.module_sp)
            {
                s->EOL();
                s->Indent("module = ");
                sc.module_sp->GetFileSpec().Dump (s);
            }

            if (sc.comp_unit != NULL)
            {
                s->EOL();
                s->Indent("compile unit = ");
                static_cast<FileSpec*>(sc.comp_unit)->GetFilename().Dump (s);

                if (sc.function != NULL)
                {
                    s->EOL();
                    s->Indent("function = ");
                    s->PutCString (sc.function->GetName().AsCString("<unknown>"));
                }

                if (sc.line_entry.line > 0)
                {
                    s->EOL();
                    s->Indent("location = ");
                    sc.line_entry.DumpStopContext (s, true);
                }

            }
            else
            {
                // If we don't have a comp unit, see if we have a symbol we can print.
                if (sc.symbol)
                {
                    s->EOL();
                    if (IsReExported())
                        s->Indent ("re-exported target = ");
                    else
                        s->Indent("symbol = ");
                    s->PutCString(sc.symbol->GetName().AsCString("<unknown>"));
                }
            }
        }
    }

    if (level == lldb::eDescriptionLevelVerbose)
    {
        s->EOL();
        s->Indent();
    }
    
    if (m_address.IsSectionOffset() && (level == eDescriptionLevelFull || level == eDescriptionLevelInitial))
        s->Printf (", ");
    s->Printf ("address = ");
    
    ExecutionContextScope *exe_scope = NULL;
    Target *target = &m_owner.GetTarget();
    if (target)
        exe_scope = target->GetProcessSP().get();
    if (exe_scope == NULL)
        exe_scope = target;

    if (level == eDescriptionLevelInitial)
        m_address.Dump(s, exe_scope, Address::DumpStyleLoadAddress, Address::DumpStyleFileAddress);
    else
        m_address.Dump(s, exe_scope, Address::DumpStyleLoadAddress, Address::DumpStyleModuleWithFileAddress);
    
    if (IsIndirect() && m_bp_site_sp)
    {
        Address resolved_address;
        resolved_address.SetLoadAddress(m_bp_site_sp->GetLoadAddress(), target);
        Symbol *resolved_symbol = resolved_address.CalculateSymbolContextSymbol();
        if (resolved_symbol)
        {
            if (level == eDescriptionLevelFull || level == eDescriptionLevelInitial)
                s->Printf (", ");
            else if (level == lldb::eDescriptionLevelVerbose)
            {
                s->EOL();
                s->Indent();
            }
            s->Printf ("indirect target = %s", resolved_symbol->GetName().GetCString());
        }
    }

    if (level == lldb::eDescriptionLevelVerbose)
    {
        s->EOL();
        s->Indent();
        s->Printf("resolved = %s\n", IsResolved() ? "true" : "false");

        s->Indent();
        s->Printf ("hit count = %-4u\n", GetHitCount());

        if (m_options_ap.get())
        {
            s->Indent();
            m_options_ap->GetDescription (s, level);
            s->EOL();
        }
        s->IndentLess();
    }
    else if (level != eDescriptionLevelInitial)
    {
        s->Printf(", %sresolved, hit count = %u ",
                  (IsResolved() ? "" : "un"),
                  GetHitCount());
        if (m_options_ap.get())
        {
            m_options_ap->GetDescription (s, level);
        }
    }
}
Example #30
0
/// @brief Platform-level implementation called by getScom()
ReturnCode platGetScom(const Target<TARGET_TYPE_ALL>& i_target,
                       const uint64_t i_address,
                       buffer<uint64_t>& o_data)
{
    ReturnCode l_rc;
    errlHndl_t l_err = NULL;

    FAPI_DBG(ENTER_MRK "platGetScom");
    // Note: Trace is placed here in plat code because PPE doesn't support
    //       trace in common fapi2_hw_access.H
    bool l_traceit = platIsScanTraceEnabled();

    // Extract the component pointer
    TARGETING::Target* l_target =
              reinterpret_cast<TARGETING::Target*>(i_target.get());

    // Grab the name of the target
    TARGETING::ATTR_FAPI_NAME_type l_targName = {0};
    fapi2::toString(i_target, l_targName, sizeof(l_targName));

    // Perform SCOM read
    size_t l_size = sizeof(uint64_t);
    l_err = deviceRead(l_target,
                       &o_data(),
                       l_size,
                       DEVICE_SCOM_ADDRESS(i_address, opMode));

    //If an error occured durring the device read and a pib_err_mask is set,
    // then we will check if the err matches the mask, if it does we
    // ignore the error
    if(l_err && (pib_err_mask != 0x00))
    {
        checkPibMask(l_err);
    }

    if (l_err)
    {
        if(opMode & fapi2::IGNORE_HW_ERROR)
        {
            delete l_err;
            l_err = nullptr;
        }
        else
        {
            FAPI_ERR("platGetScom: deviceRead returns error!");
            FAPI_ERR("fapiGetScom failed - Target %s, Addr %.16llX",
                     l_targName, i_address);
            l_rc.setPlatDataPtr(reinterpret_cast<void *> (l_err));
        }
    }

    if (l_traceit)
    {
        uint64_t l_data = (uint64_t)o_data;
        FAPI_SCAN("TRACE : GETSCOM     :  %s : %.16llX %.16llX",
                  l_targName,
                  i_address,
                  l_data);
    }

    FAPI_DBG(EXIT_MRK "platGetScom");
    return l_rc;
}