Exemplo n.º 1
0
void UK2Node_Event::ExpandNode(class FKismetCompilerContext& CompilerContext, UEdGraph* SourceGraph)
{
	Super::ExpandNode(CompilerContext, SourceGraph);

	if (CompilerContext.bIsFullCompile)
	{
		UEdGraphPin* OrgDelegatePin = FindPin(UK2Node_Event::DelegateOutputName);
		if (OrgDelegatePin && OrgDelegatePin->LinkedTo.Num() > 0)
		{
			const UEdGraphSchema_K2* Schema = CompilerContext.GetSchema();

			const FName FunctionName = GetFunctionName();
			if(FunctionName == NAME_None)
			{
				CompilerContext.MessageLog.Error(*FString::Printf(*LOCTEXT("EventDelegateName_Error", "Event node @@ has no name of function.").ToString()), this);
			}

			UK2Node_Self* SelfNode = CompilerContext.SpawnIntermediateNode<UK2Node_Self>(this, SourceGraph);
			SelfNode->AllocateDefaultPins();

			UK2Node_CreateDelegate* CreateDelegateNode = CompilerContext.SpawnIntermediateNode<UK2Node_CreateDelegate>(this, SourceGraph);
			CreateDelegateNode->AllocateDefaultPins();
			CompilerContext.MovePinLinksToIntermediate(*OrgDelegatePin, *CreateDelegateNode->GetDelegateOutPin());
			Schema->TryCreateConnection(SelfNode->FindPinChecked(Schema->PN_Self), CreateDelegateNode->GetObjectInPin());
			// When called UFunction is defined in the same class, it wasn't created yet (previously the Skeletal class was checked). So no "CreateDelegateNode->HandleAnyChangeWithoutNotifying();" is called.
			CreateDelegateNode->SetFunction(FunctionName);
		}
	}
}
Exemplo n.º 2
0
int PythonIntegration::RunScript(ScriptId scriptId, EventId evt, PyObject* args) {

	ScriptRecord script;
	if (!LoadScript(scriptId, script)) {
		return 1;
	}

	auto dict = PyModule_GetDict(script.module);
	auto eventName = GetFunctionName(evt);
	auto callback = PyDict_GetItemString(dict, eventName);

	if (!callback || !PyCallable_Check(callback)) {
		logger->error("Script {} attached as {} is missing the corresponding function.",
			script.filename, eventName);
		return 1;
	}

	auto resultObj = PyObject_CallObject(callback, args);

	if (!resultObj) {
		logger->error("An error occurred while calling event {} for script {}.", eventName, script.filename);
		PyErr_Print();
		return 1;
	}

	auto result = -1;
	if (PyInt_Check(resultObj)) {
		result = PyInt_AsLong(resultObj);
	}
	Py_DECREF(resultObj);

	return result;
}
Exemplo n.º 3
0
bool ExcDialog(LPCWSTR ModuleName,LPCWSTR Exception,LPVOID Adress)
{
	string strAddr;
	strAddr.Format(L"0x%p",Adress);
	string strFunction=GetFunctionName(From);
#ifndef NO_WRAPPER
	if(Module && !Module->IsOemPlugin())
#endif // NO_WRAPPER
	{
		strFunction+=L"W";
	}

	FarDialogItem EditDlgData[]=
	{
		{DI_DOUBLEBOX,3,1,72,8,0,nullptr,nullptr,0,MSG(MExcTrappedException)},
		{DI_TEXT,     5,2, 17,2,0,nullptr,nullptr,0,MSG(MExcException)},
		{DI_TEXT,    18,2, 70,2,0,nullptr,nullptr,0,Exception},
		{DI_TEXT,     5,3, 17,3,0,nullptr,nullptr,0,MSG(MExcAddress)},
		{DI_TEXT,    18,3, 70,3,0,nullptr,nullptr,0,strAddr},
		{DI_TEXT,     5,4, 17,4,0,nullptr,nullptr,0,MSG(MExcFunction)},
		{DI_TEXT,    18,4, 70,4,0,nullptr,nullptr,0,strFunction},
		{DI_TEXT,     5,5, 17,5,0,nullptr,nullptr,0,MSG(MExcModule)},
		{DI_EDIT,    18,5, 70,5,0,nullptr,nullptr,DIF_READONLY|DIF_SELECTONENTRY,ModuleName},
		{DI_TEXT,    -1,6, 0,6,0,nullptr,nullptr,DIF_SEPARATOR,L""},
		{DI_BUTTON,   0,7, 0,7,0,nullptr,nullptr,DIF_DEFAULTBUTTON|DIF_FOCUS|DIF_CENTERGROUP,MSG((From == EXCEPT_KERNEL)?MExcTerminate:MExcUnload)},
		{DI_BUTTON,   0,7, 0,7,0,nullptr,nullptr,DIF_CENTERGROUP,MSG(MExcDebugger)},
	};
	MakeDialogItemsEx(EditDlgData,EditDlg);
	Dialog Dlg(EditDlg, ARRAYSIZE(EditDlg),ExcDlgProc);
	Dlg.SetDialogMode(DMODE_WARNINGSTYLE|DMODE_NOPLUGINS);
	Dlg.SetPosition(-1,-1,76,10);
	Dlg.Process();
	return Dlg.GetExitCode()==11;
}
Exemplo n.º 4
0
	extern pascal OSStatus MoreAToSCopySymbolNamesUsingDyld(ItemCount 		count, 
															MoreAToSAddr 	addresses[],
															MoreAToSSymInfo symbols[])
	{
		OSStatus 	err;
		ItemCount 	index;
		
		assert(addresses != NULL);
		assert(symbols != NULL);
		
		err = noErr;
		for (index = 0; index < count; index++) {
			const char * 		thisSymbol;
			const char * 		cleanSymbol;
			unsigned int 		thisSymbolOffset;
			Boolean      		thisSymbolPublic;
			CFStringRef	 		thisSymbolStr;
			MoreAToSSymbolType	thisSymbolType;
			
			thisSymbolStr = NULL;
			
			thisSymbol = NULL;
			if (addresses[index] != NULL) {		// NULL is never a useful symbol
				thisSymbol = GetFunctionName( (unsigned int) addresses[index], &thisSymbolOffset, &thisSymbolPublic);
			}
			if (thisSymbol != NULL) {
			
				// Mach-O symbols virtually always start with '_'.  If there's one there, 
				// let's strip it.
				
				if (thisSymbol[0] == '_') {
					cleanSymbol = &thisSymbol[1];
				} else {
					cleanSymbol = thisSymbol;
				}
				thisSymbolStr = CFStringCreateWithCString(NULL, cleanSymbol, kCFStringEncodingASCII);
				err = CFQError(thisSymbolStr);
				
				if (thisSymbolPublic) {
					thisSymbolType = kMoreAToSDyldPubliSymbol;
				} else {
					thisSymbolType = kMoreAToSDyldPrivateSymbol;
				}
				
				if (err == noErr) {	
					ReplaceSymbolIfBetter(&symbols[index], thisSymbolType, thisSymbolStr, (UInt32) thisSymbolOffset);
				}
			}
			
			CFQRelease(thisSymbolStr);
			free( (void *) thisSymbol);
			
			if (err != noErr) {
				break;
			}
		}
		
		return err;
	}
Exemplo n.º 5
0
bool UnwindCurrent::UnwindFromContext(size_t num_ignore_frames, bool resolve) {
  // The cursor structure is pretty large, do not put it on the stack.
  unw_cursor_t* cursor = new unw_cursor_t;
  int ret = unw_init_local(cursor, &context_);
  if (ret < 0) {
    BACK_LOGW("unw_init_local failed %d", ret);
    delete cursor;
    return false;
  }

  std::vector<backtrace_frame_data_t>* frames = GetFrames();
  frames->reserve(MAX_BACKTRACE_FRAMES);
  size_t num_frames = 0;
  do {
    unw_word_t pc;
    ret = unw_get_reg(cursor, UNW_REG_IP, &pc);
    if (ret < 0) {
      BACK_LOGW("Failed to read IP %d", ret);
      break;
    }
    unw_word_t sp;
    ret = unw_get_reg(cursor, UNW_REG_SP, &sp);
    if (ret < 0) {
      BACK_LOGW("Failed to read SP %d", ret);
      break;
    }

    if (num_ignore_frames == 0) {
      frames->resize(num_frames+1);
      backtrace_frame_data_t* frame = &frames->at(num_frames);
      frame->num = num_frames;
      frame->pc = static_cast<uintptr_t>(pc);
      frame->sp = static_cast<uintptr_t>(sp);
      frame->stack_size = 0;

      if (num_frames > 0) {
        // Set the stack size for the previous frame.
        backtrace_frame_data_t* prev = &frames->at(num_frames-1);
        prev->stack_size = frame->sp - prev->sp;
      }

      if (resolve) {
        frame->func_name = GetFunctionName(frame->pc, &frame->func_offset);
        frame->map = FindMap(frame->pc);
      } else {
        frame->map = NULL;
        frame->func_offset = 0;
      }
      num_frames++;
    } else {
      num_ignore_frames--;
    }
    ret = unw_step (cursor);
  } while (ret > 0 && num_frames < MAX_BACKTRACE_FRAMES);

  delete cursor;
  return true;
}
void BacktraceThread::FinishUnwind() {
  for (std::vector<backtrace_frame_data_t>::iterator it = frames_.begin();
       it != frames_.end(); ++it) {
    it->map = FindMap(it->pc);

    it->func_offset = 0;
    it->func_name = GetFunctionName(it->pc, &it->func_offset);
  }
}
bool BacktraceOffline::Unwind(size_t num_ignore_frames, ucontext_t* context) {
  if (context == nullptr) {
    BACK_LOGW("The context is needed for offline backtracing.");
    return false;
  }
  context_ = context;

  unw_addr_space_t addr_space = unw_create_addr_space(&accessors, 0);
  unw_cursor_t cursor;
  int ret = unw_init_remote(&cursor, addr_space, this);
  if (ret != 0) {
    BACK_LOGW("unw_init_remote failed %d", ret);
    unw_destroy_addr_space(addr_space);
    return false;
  }
  size_t num_frames = 0;
  do {
    unw_word_t pc;
    ret = unw_get_reg(&cursor, UNW_REG_IP, &pc);
    if (ret < 0) {
      BACK_LOGW("Failed to read IP %d", ret);
      break;
    }
    unw_word_t sp;
    ret = unw_get_reg(&cursor, UNW_REG_SP, &sp);
    if (ret < 0) {
      BACK_LOGW("Failed to read SP %d", ret);
      break;
    }

    if (num_ignore_frames == 0) {
      frames_.resize(num_frames + 1);
      backtrace_frame_data_t* frame = &frames_[num_frames];
      frame->num = num_frames;
      frame->pc = static_cast<uintptr_t>(pc);
      frame->sp = static_cast<uintptr_t>(sp);
      frame->stack_size = 0;

      if (num_frames > 0) {
        backtrace_frame_data_t* prev = &frames_[num_frames - 1];
        prev->stack_size = frame->sp - prev->sp;
      }
      frame->func_name = GetFunctionName(frame->pc, &frame->func_offset);
      FillInMap(frame->pc, &frame->map);
      num_frames++;
    } else {
      num_ignore_frames--;
    }
    ret = unw_step(&cursor);
  } while (ret > 0 && num_frames < MAX_BACKTRACE_FRAMES);

  unw_destroy_addr_space(addr_space);
  context_ = nullptr;
  return true;
}
Exemplo n.º 8
0
	void OnFunctionEnter( UINT functionId )
	{
		if (!seen_function[functionId])
		{
			char sz[1024];
			std::wstring ws = GetFunctionName( functionId );
			sprintf(sz, "0x%08x=%ws", functionId, ws.c_str());
			Log(sz);

			seen_function[functionId] = true;
		}
		writer.WriteEnterFunction( functionId, profiler );
	}
Exemplo n.º 9
0
void UK2Node_CastByteToEnum::ExpandNode(class FKismetCompilerContext& CompilerContext, UEdGraph* SourceGraph)
{
	Super::ExpandNode(CompilerContext, SourceGraph);

	if (bSafe && Enum)
	{
		const UEdGraphSchema_K2* Schema = CompilerContext.GetSchema();

		// FUNCTION NODE
		const FName FunctionName = GetFunctionName();
		const UFunction* Function = UKismetNodeHelperLibrary::StaticClass()->FindFunctionByName(FunctionName);
		check(NULL != Function);
		UK2Node_CallFunction* CallValidation = CompilerContext.SpawnIntermediateNode<UK2Node_CallFunction>(this, SourceGraph); 
		CallValidation->SetFromFunction(Function);
		CallValidation->AllocateDefaultPins();
		check(CallValidation->IsNodePure());

		// FUNCTION ENUM PIN
		UEdGraphPin* FunctionEnumPin = CallValidation->FindPinChecked(TEXT("Enum"));
		Schema->TrySetDefaultObject(*FunctionEnumPin, Enum);
		check(FunctionEnumPin->DefaultObject == Enum);

		// FUNCTION INPUT BYTE PIN
		UEdGraphPin* OrgInputPin = FindPinChecked(ByteInputPinName);
		UEdGraphPin* FunctionIndexPin = CallValidation->FindPinChecked(TEXT("EnumeratorIndex"));
		check(EGPD_Input == FunctionIndexPin->Direction && Schema->PC_Byte == FunctionIndexPin->PinType.PinCategory);
		CompilerContext.MovePinLinksToIntermediate(*OrgInputPin, *FunctionIndexPin);

		// UNSAFE CAST NODE
		UK2Node_CastByteToEnum* UsafeCast = CompilerContext.SpawnIntermediateNode<UK2Node_CastByteToEnum>(this, SourceGraph); 
		UsafeCast->Enum = Enum;
		UsafeCast->bSafe = false;
		UsafeCast->AllocateDefaultPins();

		// UNSAFE CAST INPUT
		UEdGraphPin* CastInputPin = UsafeCast->FindPinChecked(ByteInputPinName);
		UEdGraphPin* FunctionReturnPin = CallValidation->GetReturnValuePin();
		check(NULL != FunctionReturnPin);
		Schema->TryCreateConnection(CastInputPin, FunctionReturnPin);

		// OPUTPUT PIN
		UEdGraphPin* OrgReturnPin = FindPinChecked(Schema->PN_ReturnValue);
		UEdGraphPin* NewReturnPin = UsafeCast->FindPinChecked(Schema->PN_ReturnValue);
		CompilerContext.MovePinLinksToIntermediate(*OrgReturnPin, *NewReturnPin);

		BreakAllNodeLinks();
	}
}
Exemplo n.º 10
0
llvm::Function *ValuesRuntimeProxy::_OutputDate::GetFunction(CodeGen &codegen) {
  const std::string &fn_name = GetFunctionName();

  // Has the function already been registered?
  llvm::Function *llvm_fn = codegen.LookupFunction(fn_name);
  if (llvm_fn != nullptr) {
    return llvm_fn;
  }

  auto *value_type = ValueProxy::GetType(codegen);
  auto *fn_type = llvm::FunctionType::get(
      codegen.VoidType(),
      {value_type->getPointerTo(), codegen.Int64Type(), codegen.Int32Type()},
      false);
  return codegen.RegisterFunction(fn_name, fn_type);
}
Exemplo n.º 11
0
JBoolean
CBCClass::IsInherited
	(
	const JIndex		index,
	const InheritType	inherit,
	FnAccessLevel*		access
	)
	const
{
	const JString& fnName = GetFunctionName(index);
	*access               = GetFnAccessLevel(index);

	if (!IsPrivate(*access) &&					// private
		fnName.GetFirstCharacter() != '~' &&	// dtor
		fnName != GetName())					// ctor
		{
		if (inherit == kInheritPrivate)
			{
			if (*access == kPublicAccess ||
				*access == kProtectedAccess)
				{
				*access = kPrivateAccess;
				}
			else if (*access == kQtPublicSlotAccess ||
					 *access == kQtProtectedSlotAccess)
				{
				*access = kQtPrivateSlotAccess;
				}
			}
		else if (inherit == kInheritProtected &&
				 *access == kPublicAccess)
			{
			*access = kProtectedAccess;
			}
		else if (inherit == kInheritProtected &&
				 *access == kQtPublicSlotAccess)
			{
			*access = kQtProtectedSlotAccess;
			}
		return kJTrue;
		}
	else
		{
		return kJFalse;
		}
}
/**
 * Enqueues a compilation for a new shader of this type.
 * @param Platform - The platform to compile for.
 * @param Material - The material to link the shader with.
 * @param VertexFactoryType - The vertex factory to compile with.
 */
FShaderCompileJob* FMeshMaterialShaderType::BeginCompileShader(
	uint32 ShaderMapId,
	EShaderPlatform Platform,
	const FMaterial* Material,
	FShaderCompilerEnvironment* MaterialEnvironment,
	FVertexFactoryType* VertexFactoryType,
	const FShaderPipelineType* ShaderPipeline,
	TArray<FShaderCommonCompileJob*>& NewJobs
	)
{
	FShaderCompileJob* NewJob = new FShaderCompileJob(ShaderMapId, VertexFactoryType, this);

	NewJob->Input.SharedEnvironment = MaterialEnvironment;
	FShaderCompilerEnvironment& ShaderEnvironment = NewJob->Input.Environment;

	// apply the vertex factory changes to the compile environment
	check(VertexFactoryType);
	VertexFactoryType->ModifyCompilationEnvironment(Platform, Material, ShaderEnvironment);

	//update material shader stats
	UpdateMaterialShaderCompilingStats(Material);

	UE_LOG(LogShaders, Verbose, TEXT("			%s"), GetName());
	COOK_STAT(MaterialMeshCookStats::ShadersCompiled++);

	// Allow the shader type to modify the compile environment.
	SetupCompileEnvironment(Platform, Material, ShaderEnvironment);

	bool bAllowDevelopmentShaderCompile = Material->GetAllowDevelopmentShaderCompile();

	// Compile the shader environment passed in with the shader type's source code.
	::GlobalBeginCompileShader(
		Material->GetFriendlyName(),
		VertexFactoryType,
		this,
		ShaderPipeline,
		GetShaderFilename(),
		GetFunctionName(),
		FShaderTarget(GetFrequency(),Platform),
		NewJob,
		NewJobs,
		bAllowDevelopmentShaderCompile
		);
	return NewJob;
}
Exemplo n.º 13
0
llvm::Function *ValuesRuntimeProxy::_CompareStrings::GetFunction(
    CodeGen &codegen) {
  const std::string &fn_name = GetFunctionName();

  // Has the function already been registered?
  llvm::Function *llvm_fn = codegen.LookupFunction(fn_name);
  if (llvm_fn != nullptr) {
    return llvm_fn;
  }

  std::vector<llvm::Type *> arg_types = {codegen.CharPtrType(),  // str1
                                         codegen.Int32Type(),    // str1 length
                                         codegen.CharPtrType(),  // str2
                                         codegen.Int32Type()};   // str2 length
  auto *fn_type =
      llvm::FunctionType::get(codegen.Int32Type(), arg_types, false);
  return codegen.RegisterFunction(fn_name, fn_type);
}
void WrapClassMemberWithDoc::ShowHelp() 
{
  std::string mess; 
  std::string paramlist_str;
  int nb_param = parameters_comments.size();
  
  // We consider that, when the help is displayed, the argument failure flag is set to true
  Set_arg_failure(true);

  for(int n=0;n<nb_param;n++) {
    //if ()
    paramlist_str += (boost::format("%1% p%2%") % paramtypes[n] %n).str(); 
    
    if (n<nb_param-1) paramlist_str += ", ";
  }

  mess += "\n";
  if (return_comments!="") 
    mess += "Variable ";
  mess += (boost::format("%1%(%2%)\n")% GetFunctionName() % paramlist_str).str();
  mess += "\n"; 
  if (nb_param>0) {
    //mess +=  "\n  Parameters:\n"; 
    for(int n=0;n<nb_param;n++) {
      mess +=  (boost::format("    - p%1%: %2% \n") % n % parameters_comments[n]).str(); 
    }
  }
  mess += "\n"; 
  mess +=  (boost::format("    %s\n") % GetDescription()).str(); 

  if (return_comments!="") {
    mess += "\n";
    mess += "  Returns: ";
    mess += return_comments;
    mess += "\n";
  }

  // TODO: display help message
//   wxMessageDialog* msg = new wxMessageDialog(NULL,wxString(mess.c_str(),wxConvUTF8),
//       wxString::FromAscii("Info"),wxOK | wxICON_INFORMATION  );
//   msg->ShowModal();
//   msg->Destroy();
}
Exemplo n.º 15
0
void Value::FillImportTable(IMDLBinaryFile* pfile)
{
    if (m_pnsInfo) {
        if (pfile->AddImport(m_pnsInfo)) {
            return;
        }
    }

    ZString str = GetFunctionName();

    if (!str.IsEmpty()) {
        pfile->AddImport(str);
    }

    int count = m_pchildren.GetCount();
    for (int index = count - 1; index >= 0; index--) {
        m_pchildren[index]->FillImportTable(pfile);
    }
}
Exemplo n.º 16
0
ZString Value::GetString(int indent)
{
    // name ( args )

    ZString str = GetFunctionName() + "(\n";

    int count = m_pchildren.GetCount();
    for (int index = 0; index < count; index++) {
        str += Indent(indent + 1) + m_pchildren[index]->GetChildString(indent + 1);

        if (index != count - 1) {
            str += ",\n";
        } else {
            str += "\n";
        }
    }

    return str + Indent(indent) + ")";
}
Exemplo n.º 17
0
static std::wostream& PrintFowardDeclarations(std::wostream& os, Grammar& g, MMap& map)
{
    os << L"/*forward declarations*/ \n";
    int i = 0;
    int sub = 0;
    int currentRuleIndex = -1;

    for (auto it = map.begin(); it != map.end(); it++)
    {
        if (currentRuleIndex != it->m_pNotTerminal->GetIndex())
        {
            //mudou
            currentRuleIndex = it->m_pNotTerminal->GetIndex();
            os << L"Result " << GetFunctionName(g, it->m_pNotTerminal->GetName()) << L"( " << g.GetLanguageName() << L"_Context* ctx);\n";
            sub = 0;
        }

        sub++;
        i++;
    }

    os << L"\n\n";
    return os;
}
Exemplo n.º 18
0
void FGlobalShaderType::BeginCompileShader(EShaderPlatform Platform, TArray<FShaderCompileJob*>& NewJobs)
{
	FShaderCompileJob* NewJob = new FShaderCompileJob(GlobalShaderMapId, NULL, this);
	FShaderCompilerEnvironment& ShaderEnvironment = NewJob->Input.Environment;

	UE_LOG(LogShaders, Verbose, TEXT("	%s"), GetName());

	// Allow the shader type to modify the compile environment.
	SetupCompileEnvironment(Platform, ShaderEnvironment);

	static FString GlobalName(TEXT("Global"));

	// Compile the shader environment passed in with the shader type's source code.
	::GlobalBeginCompileShader(
		GlobalName,
		NULL,
		this,
		GetShaderFilename(),
		GetFunctionName(),
		FShaderTarget(GetFrequency(),Platform),
		NewJob,
		NewJobs
		);
}
bool UnwindCurrent::UnwindFromContext(size_t num_ignore_frames, ucontext_t* ucontext) {
  if (ucontext == nullptr) {
    int ret = unw_getcontext(&context_);
    if (ret < 0) {
      BACK_LOGW("unw_getcontext failed %d", ret);
      return false;
    }
  } else {
    GetUnwContextFromUcontext(ucontext);
  }

  // The cursor structure is pretty large, do not put it on the stack.
  std::unique_ptr<unw_cursor_t> cursor(new unw_cursor_t);
  int ret = unw_init_local(cursor.get(), &context_);
  if (ret < 0) {
    BACK_LOGW("unw_init_local failed %d", ret);
    return false;
  }

  size_t num_frames = 0;
  do {
    unw_word_t pc;
    ret = unw_get_reg(cursor.get(), UNW_REG_IP, &pc);
    if (ret < 0) {
      BACK_LOGW("Failed to read IP %d", ret);
      break;
    }
    unw_word_t sp;
    ret = unw_get_reg(cursor.get(), UNW_REG_SP, &sp);
    if (ret < 0) {
      BACK_LOGW("Failed to read SP %d", ret);
      break;
    }

    frames_.resize(num_frames+1);
    backtrace_frame_data_t* frame = &frames_.at(num_frames);
    frame->num = num_frames;
    frame->pc = static_cast<uintptr_t>(pc);
    frame->sp = static_cast<uintptr_t>(sp);
    frame->stack_size = 0;

    FillInMap(frame->pc, &frame->map);
    // Check to see if we should skip this frame because it's coming
    // from within the library, and we are doing a local unwind.
    if (ucontext != nullptr || num_frames != 0 || !DiscardFrame(*frame)) {
      if (num_ignore_frames == 0) {
        // GetFunctionName is an expensive call, only do it if we are
        // keeping the frame.
        frame->func_name = GetFunctionName(frame->pc, &frame->func_offset);
        if (num_frames > 0) {
          // Set the stack size for the previous frame.
          backtrace_frame_data_t* prev = &frames_.at(num_frames-1);
          prev->stack_size = frame->sp - prev->sp;
        }
        num_frames++;
      } else {
        num_ignore_frames--;
      }
    }
    ret = unw_step (cursor.get());
  } while (ret > 0 && num_frames < MAX_BACKTRACE_FRAMES);

  return true;
}
Exemplo n.º 20
0
//
// Get the functions for the given PID/TID/MODULE
// If PID is -1, get functions from all the PIDs
// If TID is -1 get functions from all the PIDS
//
bool GetFunctionInfoList(CpuProfileReader&        profileReader,
                         ProcessIdType            pid,
                         ThreadIdType             tid,
                         CpuProfileModule&        module,
                         const gtString&          moduleFilePath,
                         gtUInt64                 flags,        // ignore-system-modules, separate-by-core, etc
                         gtUInt64                 coreMask,
                         FunctionInfoList&        funcInfoList,
                         FunctionIdxMap&          funcIdxMap)
{
    GT_UNREFERENCED_PARAMETER(coreMask);
    GT_UNREFERENCED_PARAMETER(moduleFilePath);
    FunctionInfo funcInfo;
    gtVector<gtUInt64> totalDataVector;

    bool ignoreSysModule = ((flags & SAMPLE_IGNORE_SYSTEM_MODULES) == SAMPLE_IGNORE_SYSTEM_MODULES) ? true : false;
    bool sepByCore = ((flags & SAMPLE_SEPARATE_BY_CORE) == SAMPLE_SEPARATE_BY_CORE) ? true : false;

    bool groupByModule = ((flags & SAMPLE_GROUP_BY_MODULE) == SAMPLE_GROUP_BY_MODULE) ? true : false;
    // TODO: - group by thread
    bool groupByThread = ((flags & SAMPLE_GROUP_BY_THREAD) == SAMPLE_GROUP_BY_THREAD) ? true : false;

    gtUInt32 numCores = profileReader.getProfileInfo()->m_numCpus;
    gtUInt32 dataSize = (sepByCore) ? (numCores * profileReader.getProfileInfo()->m_numEvents)
                        : profileReader.getProfileInfo()->m_numEvents;

    if (!ignoreSysModule || !module.isSystemModule())
    {
        // For each function
        AddrFunctionMultMap::iterator fit = module.getBeginFunction();
        AddrFunctionMultMap::iterator fEnd = module.getEndFunction();

        for (; fit != fEnd; ++fit)
        {
            CpuProfileFunction& function = fit->second;

            // For each sample
            AptAggregatedSampleMap::const_iterator sit = function.getBeginSample();
            AptAggregatedSampleMap::const_iterator sEnd = function.getEndSample();

            gtString funcName;
            CpuProfileFunction* pFunc = &function;

            for (; sit != sEnd; ++sit)
            {
                const AptKey& aptKey = sit->first;
                gtVAddr sampAddr = aptKey.m_addr;
                bool rc = false;
                ProcessIdType sampPid = (groupByModule) ? static_cast<ProcessIdType>(-1) : aptKey.m_pid;
                ThreadIdType sampTid = (groupByThread) ? aptKey.m_tid : static_cast<ThreadIdType>(-1);

                if (sampPid != pid)
                {
                    continue;
                }

                if (sampTid != tid)
                {
                    continue;
                }

                funcName.makeEmpty();

                switch (module.m_modType)
                {
                    // Normal PE module:
                    case CpuProfileModule::UNMANAGEDPE:
                        if (module.isUnchartedFunction(function))
                        {
                            sampAddr += module.getBaseAddr();

                            // Find the name of the function
                            rc = GetFunctionName(&module, sampAddr, funcName, &pFunc);

                            if (rc)
                            {
                                sampAddr = pFunc->getBaseAddr();
                            }
                        }
                        else
                        {
                            funcName = pFunc->getFuncName(); // FIXME, if the func name is empty ?
                            sampAddr = pFunc->getBaseAddr();
                        }

                        break;

                    case CpuProfileModule::JAVAMODULE:
                    case CpuProfileModule::MANAGEDPE:
                        // For now, Putting this specific check for Java/CLR
                        // At some point, need to re-structure this function to properly handle all module type
                        // For Java/CLR, func name/addr info is already present and just need to set in outer loop (for each func)
                        // Probably the better is to define separate functions for each module type like in old GUI code
                        sampAddr = function.getBaseAddr();
                        funcName = function.getFuncName();
                        break;

                    case CpuProfileModule::UNKNOWNMODULE:
                    case CpuProfileModule::UNKNOWNKERNELSAMPLES:
                        // TODO: Handle Unknown Kernel Samples and Unknown Module here
                        // Convert the "No symbol" to a wide char:
                        break;

                    default:
                        break;
                }

                // Find the function in the unique
                FunctionInfo* pFuncInfo = &funcInfo;
                bool isNewFunc = false;

                // Check whether the new function is already there in the funcInfoList
                pFuncInfo = FindFunction(funcInfoList, funcIdxMap, sampAddr, pid, tid);

                if (nullptr == pFuncInfo)
                {
                    pFuncInfo = &funcInfo;

                    funcInfo.m_baseAddress = sampAddr;
                    funcInfo.m_functionName = funcName;
                    funcInfo.m_pModule = &module;
                    funcInfo.m_dataVector.clear();

                    funcInfo.m_pid = pid;
                    funcInfo.m_tid = tid;

                    funcInfo.m_dataVector.resize(dataSize);
                    isNewFunc = true;
                }

                totalDataVector.resize(dataSize);

                // Aggregate the samples..
                //   Get the EventToIndexMap - which is required to aggregate the samples
                EventToIndexMap evtToIdxMap;
                GetEventToIndexMap(profileReader, evtToIdxMap);

                AggregateSamples(profileReader,
                                 (*sit).second,
                                 pFuncInfo->m_dataVector,
                                 totalDataVector,
                                 evtToIdxMap,
                                 sepByCore);

                if (isNewFunc)
                {
                    funcInfoList.push_back(funcInfo);
                    funcIdxMap.insert({ sampAddr, funcInfoList.size() - 1 });
                }
            } // AptAggregatedSampleMap
        } // AddrFunctionMultMap
    }

    return true;
}
Exemplo n.º 21
0
bool UnwindPtrace::Unwind(size_t num_ignore_frames, ucontext_t* ucontext) {
  if (ucontext) {
    BACK_LOGW("Unwinding from a specified context not supported yet.");
    return false;
  }

  addr_space_ = unw_create_addr_space(&_UPT_accessors, 0);
  if (!addr_space_) {
    BACK_LOGW("unw_create_addr_space failed.");
    return false;
  }

  UnwindMap* map = static_cast<UnwindMap*>(GetMap());
  if (NULL == map) {
    BACK_LOGW("GetMap before unwinding failed.");
    return false;
  }
  unw_map_set(addr_space_, map->GetMapCursor());

  upt_info_ = reinterpret_cast<struct UPT_info*>(_UPT_create(Tid()));
  if (!upt_info_) {
    BACK_LOGW("Failed to create upt info.");
    return false;
  }

  unw_cursor_t cursor;
  if(num_ignore_frames==0xdeaddead)
  	{
  		cursor.opaque[0]=0xdeaddead; //add for tell libunwind to unwind for kernel unwind userspace backtrace,lhd
  		BACK_LOGW(" K2U_bt call into UnwindPtrace::Unwind.");
		num_ignore_frames=0;
  	}
  int ret = unw_init_remote(&cursor, addr_space_, upt_info_);
  if (ret < 0) {
    BACK_LOGW("unw_init_remote failed %d", ret);
    return false;
  }

  std::vector<backtrace_frame_data_t>* frames = GetFrames();
  frames->reserve(MAX_BACKTRACE_FRAMES);
  size_t num_frames = 0;
  do {
    unw_word_t pc;
    ret = unw_get_reg(&cursor, UNW_REG_IP, &pc);
    if (ret < 0) {
      BACK_LOGW("Failed to read IP %d", ret);
      break;
    }
    unw_word_t sp;
    ret = unw_get_reg(&cursor, UNW_REG_SP, &sp);
    if (ret < 0) {
      BACK_LOGW("Failed to read SP %d", ret);
      break;
    }

    if (num_ignore_frames == 0) {
      frames->resize(num_frames+1);
      backtrace_frame_data_t* frame = &frames->at(num_frames);
      frame->num = num_frames;
      frame->pc = static_cast<uintptr_t>(pc);
      frame->sp = static_cast<uintptr_t>(sp);
      frame->stack_size = 0;

      if (num_frames > 0) {
        backtrace_frame_data_t* prev = &frames->at(num_frames-1);
        prev->stack_size = frame->sp - prev->sp;
      }

      frame->func_name = GetFunctionName(frame->pc, &frame->func_offset);

      frame->map = FindMap(frame->pc);

      num_frames++;
    } else {
      num_ignore_frames--;
    }
    ret = unw_step (&cursor);
  } while (ret > 0 && num_frames < MAX_BACKTRACE_FRAMES);

  return true;
}
Exemplo n.º 22
0
/////////////////////////////////////////////////////
//                                                 //
// GetIrpTableHooksAndDetours()                    //
//                                                 //
/////////////////////////////////////////////////////
//Description:  Scans the IRP table for the passed-in
//				driver and attempts to determine if a
//				dispatch routine is hooked.
//
//Returns:      void
/////////////////////////////////////////////////////
BOOL GetIrpTableHooksAndDetours(PUNICODE_STRING puDriverName, 
								PUNICODE_STRING puDeviceName, 
								ULONG DriverBaseAddress, 
								ULONG DriverSize, 
								PHOOKED_DISPATCH_FUNCTIONS_TABLE pHookTable,
								PDETOURED_DISPATCH_FUNCTIONS_TABLE pDetourTable)
{
	NTSTATUS nt;
	PDRIVER_DISPATCH* pDriverIrpTable;
	PDRIVER_DISPATCH dispatchFunctionAddress;
	CHAR dispatchFunctionName[256];
	PFILE_OBJECT fileObj;
	PDRIVER_OBJECT driverObj;
	PDEVICE_OBJECT deviceObj;
	PSYSTEM_MODULE_INFORMATION pModInfo;
	PCHAR pUnknownBuf="[unknown]";
	CHAR ContainingModule[256];
	BOOL IsHooked=FALSE,IsDetoured=FALSE;
	PDETOURINFO d;
	int i,j;

	//prep work
	pModInfo=ExAllocatePoolWithTag(NonPagedPool,sizeof(SYSTEM_MODULE_INFORMATION),CW_TAG);
	d=ExAllocatePoolWithTag(NonPagedPool,sizeof(DETOURINFO),CW_TAG);

	if (pModInfo == NULL || d == NULL)
	{
		DbgPrint("GetIrpTableHooksAndDetours():  ERROR:  pModInfo or d was NULL.");
		return FALSE;
	}

	//get a pointer to the driver's device object structure that represents this exposed device name
	//note: ACCESS_MASK of FILE_READ_DATA is important because it ensures
	//the file system is mounted on the storage device (if dealing with fs device)
	nt=IoGetDeviceObjectPointer(puDeviceName,FILE_READ_DATA,&fileObj,&deviceObj);
	if (!NT_SUCCESS(nt))
	{
		DbgPrint("GetIrpTableHooksAndDetours():  Error:  failed to obtain device pointer:  0x%08x",nt);
		return FALSE;
	}

	//get a pointer to the device's DRIVER_OBJECT structure
	driverObj=deviceObj->DriverObject;

	//from the driver object structure, get a pointer to the IRP table
	pDriverIrpTable=driverObj->MajorFunction;

	DbgPrint("GetIrpTableHooksAndDetours():  IRP table pointer obtained.");

	//iterate over all pointers in the IRP function handler table for this driver
	//note there are 28 IRP major function codes, and all drivers must specify
	//a routine for each one; the I/O manager fills entires in the IRP table
	//that the driver chose not to handle with a generic routine.
	for (i=0;i<IRP_MJ_MAXIMUM_FUNCTION+1;i++)
	{
		dispatchFunctionAddress=pDriverIrpTable[i];

		//---------------------------------------------
		//GET CONTAINING MODULE NAME AND FUNCTION NAME
		//---------------------------------------------
		//get the containing module of this  function by its address in memory
		if(GetModInfoByAddress((ULONG)dispatchFunctionAddress,pModInfo))
		{
			RtlStringCbCopyExA(ContainingModule,256,pModInfo->ImageName,NULL,NULL,0);

			//get the name of the function from the containing module's export table
			//or if not exported, store [unknown]
			if (!GetFunctionName(pModInfo->Base,(ULONG)dispatchFunctionAddress,dispatchFunctionName))
				RtlStringCbCopyExA(dispatchFunctionName,256,pUnknownBuf,NULL,NULL,0);
		}
		//if we cant find the containing module, there's a problem:
		//	(1) ZwQuerySystemInformation() is hooked.  we're screwed.
		//	(2) the module was not in the system's module list, so it injected somehow
		//in either case, the user should suspect something's up from this fact alone.
		else
		{
			RtlStringCbCopyExA(ContainingModule,256,pUnknownBuf,NULL,NULL,0);
			RtlStringCbCopyExA(dispatchFunctionName,256,pUnknownBuf,NULL,NULL,0);
		}

		////////////////////////////////////////
		//				HOOKED
		////////////////////////////////////////
		if (pHookTable != NULL)
		{
			pHookTable->HookedEntries[i].DispatchFunctionAddress=(ULONG)dispatchFunctionAddress;			
			RtlStringCbCopyExA(pHookTable->HookedEntries[i].ContainingModule,256,ContainingModule,NULL,NULL,0);
			RtlStringCbCopyExA(pHookTable->HookedEntries[i].DispatchFunctionName,256,dispatchFunctionName,NULL,NULL,0);

			if (!IsAddressWithinModule((ULONG)dispatchFunctionAddress,DriverBaseAddress,DriverSize))
			{
				pHookTable->HookedEntries[i].IrpMajorFunctionHooked=i;
				pHookTable->isHooked=TRUE;
			}
			else
			{
				pHookTable->isHooked=FALSE;
			}

			pHookTable->NumHookedEntries++;
		}

		////////////////////////////////////////
		//				DETOURED
		////////////////////////////////////////
		if (pDetourTable != NULL)
		{
			pDetourTable->DetouredEntries[i].DispatchFunctionAddress=(ULONG)dispatchFunctionAddress;
			RtlStringCbCopyExA(pDetourTable->DetouredEntries[i].DetouringModule,256,ContainingModule,NULL,NULL,0);
			RtlStringCbCopyExA(pDetourTable->DetouredEntries[i].DispatchFunctionName,256,dispatchFunctionName,NULL,NULL,0);

			if (IsFunctionPrologueDetoured((ULONG)dispatchFunctionAddress,DriverBaseAddress,DriverSize,d))
			{
				pDetourTable->isDetoured=TRUE;

				if (d->detouringModule != NULL)
					RtlStringCbCopyExA(pDetourTable->DetouredEntries[i].DetouringModule,256,d->detouringModule,NULL,NULL,0);

				pDetourTable->DetouredEntries[i].TargetAddress=d->TargetAddress;

				//loop through possible decoded instructions
				for (j = 0;j<d->numDisassembled; j++) 
				{
					RtlStringCchPrintfA(
						pDetourTable->DetouredEntries[i].Disassembly[j],
						256,
						"%08I64x (%02d) %s %s %s\n", 
						d->decodedInstructions[j].offset,
						d->decodedInstructions[j].size,
						(char*)d->decodedInstructions[j].instructionHex.p,
						(char*)d->decodedInstructions[j].mnemonic.p,
						(char*)d->decodedInstructions[j].operands.p
						);
				}
			}
			else
			{
				pDetourTable->isDetoured=FALSE;
			}

			pDetourTable->NumDetours++;
		}
	}

	//decrease reference count
	ObDereferenceObject(&fileObj);

	if (pModInfo != NULL)
		ExFreePoolWithTag(pModInfo,CW_TAG);
	if (d != NULL)
		ExFreePoolWithTag(d,CW_TAG);

	return TRUE;
}
Exemplo n.º 23
0
bool ElfParser::ParseFileText( const QStringList &strs, const QStringList &sectionStrs, const QStringList &symbolStrs, ElfParser::File &file )
{
	quint32 cnt = strs.size();

	quint32 fOff = 0;
	quint32 fStart = 0;

	QString name;
	QString pattern;
	QList< SymRef > refs;

	//DBG << file.Name() << sectionStrs.size() << symbolStrs.size() << strs.size();
	QMap< QString, QByteArray >sections = ParseSectionText( sectionStrs );
	QList< SymAlias > aliases = ParseSymbolTable( symbolStrs );


	//DBG << file.Name() << sections.size() << aliases.size();

	for( quint32 i = 0; i < cnt; i++ )
	{
		const QString &str = strs.at( i );
		/*if( name == "WII_Initialize" )
  {
   qDebug() << str;
  }*/

		// start a new funciton
		if( IsFunctionStart( str, &fStart ) )
		{
			// add this function to the list
			if( !name.isEmpty() && fOff )
			{
				Function fun( name );
				fun.references = refs;
				fun.pattern = pattern;
				fun.file = &file;
				file.functions << fun;
				//qDebug() << "pattern:" << pattern;
			}
			//qDebug() << GetFunctionName( str );
			name = GetFunctionName( str );
			//DBG << name;
			if( fOff != (quint32)pattern.size() / 2 )
			{
				qDebug() << "size bad";
				exit( 0 );
			}
			fOff = 0;
			pattern.clear();
			refs.clear();

			sections.remove( name );// remove functions from the section list
			continue;
		}
		if( name.isEmpty() )
		{
			continue;
		}
		if( IsBlank( str ) )
		{
			//qDebug() << str << "is blank";
			continue;
		}
		if( IsSymbolLine( str ) )
		{
			//qDebug() << str << "IsSymbolLine";
			continue;
		}
		QString hex;
		QString oper;
		QString symbol;
		quint32 refOff = 0xdeadbeef;

		if( !ParseOpLine( str, hex, oper ) )
		{
			qDebug() << str << strs.at( i - 1 );
			return false;
		}
		/*if( name == "WII_Initialize" )
  {
   qDebug() << "hex" << hex;
  }*/

		if( ( i < cnt - 1 ) && IsSymbolLine( strs.at( i + 1 ) ) )
		{
			SymRef::Type refType;
			symbol = GetNonOperRef( strs.at( i + 1 ), &refOff, &refType );

			if( refOff < fStart )
			{
				WRN << "refOff < fStart" << str;
				return false;
			}
			SymRef ref;
			quint32 deRef;
			ref.name = DeReferenceSymbol( symbol, &deRef );
			ref.symOff = deRef;

			switch( refType )
			{
			case SymRef::R_PPC_ADDR16_HA:
			case SymRef::R_PPC_ADDR16_HI:
			case SymRef::R_PPC_ADDR16_LO:
			{
				hex[ 4 ] = '.';
				hex[ 5 ] = '.';
				hex[ 6 ] = '.';
				hex[ 7 ] = '.';
			}
			break;
			case SymRef::R_PPC_REL24:
			case SymRef::R_PPC_EMB_SDA21:
			{
				hex[ 1 ] = '.';
				hex[ 2 ] = '.';
				hex[ 3 ] = '.';
				hex[ 4 ] = '.';
				hex[ 5 ] = '.';
				hex[ 6 ] = '.';
				hex[ 7 ] = '.';
			}
			break;
			case SymRef::R_PPC_SDAREL16:
			{
				hex = "........";
			}
			break;
			default:
				WRN << "unhandled reference type";
				return false;
				break;
			}

			ref.type = refType;
			ref.off = refOff - fStart;
			refs << ref;
			if( ref.off & 0xff000000 )
			{
				qDebug() << "ref.off is busted 1" << name << str;

				qDebug() << ::hex << refOff << fStart;
				exit( 0 );
			}
		}

		else if( OpNeedsWildCard( oper ) )
		{
			//DBG << "bl called without symbol reference\n" << str;
			hex = "........";
			if( symbol.isEmpty() )
			{
				symbol = GetOpersymRef( str );
			}
			SymRef ref;
			ref.name = symbol;
			ref.off = (quint32)(pattern.size());
			ref.type = SymRef::R_PPC_REL24;
			refs << ref;

			if( ref.off & 0xff000000 )
			{
				DBG << "ref.off is busted 2" << name << str;
				exit( 0 );
			}

		}
		pattern += hex.toUpper();
		/*if( name == "WII_Initialize" )
  {
   qDebug() << "hex" << pattern;
  }*/
		fOff += 4;
	}
	if( !name.isEmpty() )
	{
		Function fun( name );
		fun.references = refs;
		fun.pattern = pattern;
		fun.file = &file;
		file.functions << fun;
	}
	file.sections = sections;
	file.aliases = aliases;
	return true;
}
Exemplo n.º 24
0
void Value::Write(IMDLBinaryFile* pfile)
{
    WriteChildren(pfile);
    pfile->WriteReference(GetFunctionName());
    pfile->WriteApply();
}
Exemplo n.º 25
0
void DumpChronoEntry(PTHDBLK pthdblk,
                     LPSTR lpstrBuff,
                     PCHRONOCELL * ppChronoCell,
                     BOOL fDumpAll)
{
    PCHRONOCELL    pChronoCell;
    LONGLONG	   liElapsed,
                   liRealTime;
    TCHAR          chElapsedSuffix,
                   chRealTimeSuffix;
    TCHAR          pIndentation [MAX_NESTING * 2];
    TCHAR          ptchSym [FILENAMELENGTH];
    int            i;
    int            iMinimumDepth;
//  TCHAR          ptchCallerSym [FILENAMELENGTH];
    ULONG          ulSymbolAddress;


    if (fDumpAll)
    {
        pChronoCell = pthdblk->pChronoHeadCell;
        cChars += sprintf(lpstrBuff + cChars,
                          "\n\n------------------------------------------------"
                          "------------------------------------------------"
                          "----------------------------------------\r\n\n"
                          " Complete Dump of Chronological Listings\n\n"
                          " Sym Address [+Callee]  [-Callee]   Nesting Depth"
                          "       <RepCnt> - Symbol Name\n"
                          " ___________ _________  _________   _____________"
                          "       ______________________\n\n");
    }
    else
    {
        pChronoCell = * ppChronoCell;
        cChars += sprintf(lpstrBuff + cChars,
                          "\n\n------------------------------------------------"
                          "------------------------------------------------"
                          "----------------------------------------\r\n\n"
                          " Dump Chrono listing for Entry:"
                          "  %-*.*s\n\n"
                          " Sym Address  [+Callee]  [-Callee]   Nesting Depth"
                          "       <RepCnt> - Symbol Name\n"
                          " ___________  _________  _________   _____________"
                          "       ______________________\n\n",
                          iNameLength,
                          iNameLength,
                          GetFunctionName(pChronoCell->ulSymbolAddr,
                                          ulLocProfBlkOff,
                                          NULL));
    }

    iMinimumDepth = pChronoCell->nNestedCalls;

    do
    {
        //
        // Get the symbol name using the function address
        //
        strcpy(ptchSym, GetFunctionName (pChronoCell->ulSymbolAddr,
                                         ulLocProfBlkOff,
                                         &ulSymbolAddress));

        // The following caller's symbol somehow could not currently be
        // correctly resolved.  More investigation to figure out how
        // BUGBUG
        // strcpy(ptchCallerSym, GetFunctionName (
        //                           pChronoCell->ulCallRetAddr,
        //                           MKPPROFBLK(ulLocProfBlkOff)));

        pIndentation[0] = '\0';
        for (i = 0 ; i < pChronoCell->nNestedCalls ; i++)
        {
            strcat(pIndentation, "  ");
        }

        liElapsed  = pChronoCell->liElapsed;
        if (liElapsed == 0L)
        {
            liRealTime = liElapsed;
        }
        else
        {
            liRealTime = liElapsed - pChronoCell->liCallees;
        }

        AdjustTime (&liRealTime, &chRealTimeSuffix);
        AdjustTime (&liElapsed, &chElapsedSuffix);

        // Setup our string
        cChars += sprintf (
                     lpstrBuff + cChars,
                     " <%8lx>  %9lu%1c %9lu%1c%s%3d                   "
                     "<%2d>  %-*.*s\n",
                     ulSymbolAddress,
                     (ULONG)liElapsed, chElapsedSuffix,
                     (ULONG)liRealTime, chRealTimeSuffix,
                     pIndentation,
                     pChronoCell->nNestedCalls,
                     pChronoCell->nRepetitions,
                     iNameLength,
                     iNameLength,
                     ptchSym);

        if (cChars > BUFFER_SIZE)
        {
            if ( !WriteFile(hOutFile, lpstrBuff, cChars, &cChars, NULL))
            {
                 CapDbgPrint ("CAP:  DumpChronoFuncs() - ChronoDump - "
                           "Error writing to %s - 0x%lx\n",
                           atchOutFileName, GetLastError());
            }

            cChars = 0;
        }

        pChronoCell++;
    }
    while ( (pChronoCell->ulSymbolAddr != 0L) &&              // End Of list?
            ((pChronoCell->nNestedCalls > iMinimumDepth) ||   // Nest ?
             (fDumpAll)) );                                   // Override

    if (cChars)          // if Count is not 0, we have to flush everything
    {
        if ( !WriteFile (hOutFile, lpstrBuff, cChars, &cChars, NULL) )
        {
            CapDbgPrint ("CAP:  DumpChronoFuncs() - "
                      "Error writing to %s - 0x%lx\n",
                      atchOutFileName, GetLastError());
        }

        cChars = 0;
    }

    *ppChronoCell = pChronoCell;

} /* DumpChronoEntry */
Exemplo n.º 26
0
void DumpFuncCalls(PTHDBLK pthdblk, LPSTR lpstrBuff)
{
    PCHRONOCELL    pChronoCell, pCurrentChronoCell;
    ULONG          ulTotalCalls;
    ULONG          ulCurrentSymbol;
    LONGLONG	   liTotalElapsed,
                   liTotalRealTime;
    DOUBLE         dblTotalPercentage,
                   dblSinglePercentage;
    TCHAR          chElapsedSuffix,
                   chRealTimeSuffix,
                   chTotalRuntimeSuffix;
    ULONG          ulTotalPercentage,
                   ulSinglePercentage;

    AdjustTime(&liTotalRunTime, &chTotalRuntimeSuffix);

    cChars += sprintf (lpstrBuff + cChars,
                       "\r\n\n_________________________________"
                       "________________________________________________"
                       "________________________________________________"
                       "________________________________________\r\n\n\n\n"
                       " SUMMARY OF CALLS PER FUNCTION\r\n"
                       " =============================\r\n\n\n\n"
                       "   Count     [+Callee]  [-Callee]   %%Total | %%Single "
                       "   Function Name\n"
                       " __________  _________  _________  __________________   "
                       "_______________\n\n");

    if ( !WriteFile (hOutFile, lpstrBuff, cChars, &cChars, NULL) )
    {
        CapDbgPrint ("CAP:  DumpFuncCalls() - "
                  "Error writing to %s - 0x%lx\n",
                  atchOutFileName, GetLastError());
    }

    cChars = 0;

    ulTotalCalls = 0L;
    pChronoCell = pthdblk->pChronoHeadCell;
    while (pChronoCell->ulSymbolAddr != 0L)
    {
        liTotalRealTime = 0L;
        liTotalElapsed = 0L;

        ulCurrentSymbol = pChronoCell->ulSymbolAddr;
        pCurrentChronoCell = pChronoCell;
        pChronoCell->nNestedCalls = pChronoCell->nRepetitions;
        liTotalRealTime += pChronoCell->liCallees;
        liTotalElapsed += pChronoCell->liElapsed;
        pCurrentChronoCell++;

        // Walk the list and accumulate the counts
        while (pCurrentChronoCell->ulSymbolAddr != 0L)
        {
            if (pCurrentChronoCell->ulSymbolAddr == ulCurrentSymbol)
            {
                pChronoCell->nNestedCalls += pCurrentChronoCell->nRepetitions;
                liTotalRealTime += pCurrentChronoCell->liCallees;
                liTotalElapsed += pCurrentChronoCell->liElapsed;

                // Set to 0xffffffff to indicate it has been processed
                pCurrentChronoCell->ulSymbolAddr = 0xffffffff;
            }

            pCurrentChronoCell++;
        }

        if (liTotalElapsed == 0 )
        {
            liTotalRealTime = liTotalElapsed;
        }
        else
        {
            liTotalRealTime = liTotalElapsed - liTotalRealTime;
        }

        AdjustTime (&liTotalElapsed, &chElapsedSuffix);
        AdjustTime (&liTotalRealTime, &chRealTimeSuffix);
        ulTotalCalls += pChronoCell->nNestedCalls;

        if (liTotalRunTime != 0L )
        {
            dblTotalPercentage  = (100.0 * liTotalRealTime) /
                                  liTotalRunTime;

            dblSinglePercentage = dblTotalPercentage /
                                  pChronoCell->nNestedCalls;

            // BUGBUG! This "sometimes" does not produce correct results
            //         for some reasons...
            //
            // dblSinglePercentage =
            //            (100.0 * liTotalRealTime.LowPart) /
            //            (liTotalRunTime.LowPart * pChronoCell->nNestedCalls);
        }
        else
        {
            dblTotalPercentage  = 0.0;
            dblSinglePercentage = 0.0;
        }

        ulTotalPercentage = (ULONG) (dblTotalPercentage * 1000.0);
        ulSinglePercentage = (ULONG) (dblSinglePercentage * 1000.0);

        cChars += sprintf(lpstrBuff + cChars,
//                          " <%8lu>  %9lu%1c %9lu%1c %7.3f|%7.3f     %-*.*s\n",
                          " <%8lu>  %9lu%1c %9lu%1c %3lu.%03lu | %3lu.%03lu     %-*.*s\n",
                          pChronoCell->nNestedCalls,
                          (ULONG)liTotalElapsed,
                          chElapsedSuffix,
                          (ULONG)liTotalRealTime,
                          chRealTimeSuffix,
                          ulTotalPercentage / 1000,
                          ulTotalPercentage % 1000,
                          ulSinglePercentage / 1000,
                          ulSinglePercentage % 1000,
                          iNameLength,
                          iNameLength,
                          GetFunctionName (pChronoCell->ulSymbolAddr,
                                           ulLocProfBlkOff,
                                           NULL));


        if (cChars > BUFFER_SIZE)
        {
            if ( !WriteFile(hOutFile, lpstrBuff, cChars, &cChars, NULL))
            {
                 CapDbgPrint ("CAP:  DumpFuncCalls() - ChronoDump - "
                           "Error writing to %s - 0x%lx\n",
                           atchOutFileName, GetLastError());
            }

            cChars = 0;
        }

        pChronoCell++;
        while (pChronoCell->ulSymbolAddr == 0xffffffff)
        {
            pChronoCell++;
        }
    }

    cChars += sprintf(lpstrBuff + cChars,
                      "\n\n ________________________________ \n\n "
                      "<%8lu>             %9lu%1c\n\n"
                       "\r\n\n================================="
                       "================================================"
                       "================================================"
                       "========================================\r\n\n\n",
                       ulTotalCalls,
                       (ULONG)liTotalRunTime,
                       chTotalRuntimeSuffix);

    if ( !WriteFile (hOutFile, lpstrBuff, cChars, &cChars, NULL) )
    {
        CapDbgPrint ("CAP:  DumpFuncCalls() - "
                  "Error writing to %s - 0x%lx\n",
                  atchOutFileName, GetLastError());
    }

    cChars = 0;

} /* DumpFuncCalls */
Exemplo n.º 27
0
    HRESULT StackFrame::GetInfo( 
       FRAMEINFO_FLAGS dwFieldSpec,
       UINT            nRadix,
       FRAMEINFO*      pFrameInfo )
    {
        if ( pFrameInfo == NULL )
            return E_INVALIDARG;

        HRESULT hr = S_OK;

        pFrameInfo->m_dwValidFields = 0;

        if ( (dwFieldSpec & FIF_FRAME) != 0 )
        {
            hr = QueryInterface( __uuidof( IDebugStackFrame2 ), (void**) &pFrameInfo->m_pFrame );
            _ASSERT( hr == S_OK );
            pFrameInfo->m_dwValidFields |= FIF_FRAME;
        }

        if ( (dwFieldSpec & FIF_DEBUG_MODULEP) != 0 )
        {
            if ( mModule.Get() != NULL )
            {
                hr = mModule->QueryInterface( __uuidof( IDebugModule2 ), (void**) &pFrameInfo->m_pModule );
                _ASSERT( hr == S_OK );
                pFrameInfo->m_dwValidFields |= FIF_DEBUG_MODULEP;
            }
        }

        if ( (dwFieldSpec & FIF_STACKRANGE) != 0 )
        {
#if 0
            if ( mDiaStackFrame != NULL )
            {
                // TODO: review all this
                UINT64  base = 0;
                DWORD   size = 0;

                mDiaStackFrame->get_base( &base );
                mDiaStackFrame->get_size( &size );

                pFrameInfo->m_addrMax = base;
                pFrameInfo->m_addrMin = base - size;
                pFrameInfo->m_dwValidFields |= FIF_STACKRANGE;
            }
#endif
        }

        if ( (dwFieldSpec & FIF_DEBUGINFO) != 0 )
        {
            if ( mModule.Get() != NULL )
            {
                RefPtr<MagoST::ISession>    session;

                pFrameInfo->m_fHasDebugInfo = mModule->GetSymbolSession( session );
            }
            else
                pFrameInfo->m_fHasDebugInfo = FALSE;

            pFrameInfo->m_dwValidFields |= FIF_DEBUGINFO;
        }

        if ( (dwFieldSpec & FIF_FUNCNAME) != 0 )
        {
            hr = GetFunctionName( dwFieldSpec, nRadix, &pFrameInfo->m_bstrFuncName );
            if ( SUCCEEDED( hr ) )
                pFrameInfo->m_dwValidFields |= FIF_FUNCNAME;
        }

        if ( (dwFieldSpec & FIF_RETURNTYPE) != 0 )
        {
            //pFrameInfo->m_bstrReturnType;
            //pFrameInfo->m_dwValidFields |= FIF_RETURNTYPE;
        }

        if ( (dwFieldSpec & FIF_ARGS) != 0 )
        {
            //pFrameInfo->m_bstrArgs;
            //pFrameInfo->m_dwValidFields |= FIF_ARGS;
        }

        if ( (dwFieldSpec & FIF_LANGUAGE) != 0 )
        {
            hr = GetLanguageName( &pFrameInfo->m_bstrLanguage );
            if ( SUCCEEDED( hr ) )
                pFrameInfo->m_dwValidFields |= FIF_LANGUAGE;
        }

        if ( (dwFieldSpec & FIF_MODULE) != 0 )
        {
            if ( mModule != NULL )
            {
                CComBSTR modName;
                mModule->GetName( modName );
                pFrameInfo->m_bstrModule = modName.Detach();
                if ( pFrameInfo->m_bstrModule != NULL )
                    pFrameInfo->m_dwValidFields |= FIF_MODULE;
            }
        }

        //FIF_STALECODE m_fStaleCode
        //FIF_ANNOTATEDFRAME m_fAnnotatedFrame

        return S_OK;
    }
Exemplo n.º 28
0
bool UnwindPtrace::Unwind(size_t num_ignore_frames, ucontext_t* ucontext) {
  if (GetMap() == nullptr) {
    // Without a map object, we can't do anything.
    error_ = BACKTRACE_UNWIND_ERROR_MAP_MISSING;
    return false;
  }

  error_ = BACKTRACE_UNWIND_NO_ERROR;

  if (ucontext) {
    BACK_LOGW("Unwinding from a specified context not supported yet.");
    error_ = BACKTRACE_UNWIND_ERROR_UNSUPPORTED_OPERATION;
    return false;
  }

  if (!Init()) {
    return false;
  }

  unw_cursor_t cursor;
  int ret = unw_init_remote(&cursor, addr_space_, upt_info_);
  if (ret < 0) {
    BACK_LOGW("unw_init_remote failed %d", ret);
    error_ = BACKTRACE_UNWIND_ERROR_SETUP_FAILED;
    return false;
  }

  size_t num_frames = 0;
  do {
    unw_word_t pc;
    ret = unw_get_reg(&cursor, UNW_REG_IP, &pc);
    if (ret < 0) {
      BACK_LOGW("Failed to read IP %d", ret);
      break;
    }
    unw_word_t sp;
    ret = unw_get_reg(&cursor, UNW_REG_SP, &sp);
    if (ret < 0) {
      BACK_LOGW("Failed to read SP %d", ret);
      break;
    }

    if (num_ignore_frames == 0) {
      frames_.resize(num_frames+1);
      backtrace_frame_data_t* frame = &frames_.at(num_frames);
      frame->num = num_frames;
      frame->pc = static_cast<uintptr_t>(pc);
      frame->sp = static_cast<uintptr_t>(sp);
      frame->stack_size = 0;

      if (num_frames > 0) {
        backtrace_frame_data_t* prev = &frames_.at(num_frames-1);
        prev->stack_size = frame->sp - prev->sp;
      }

      FillInMap(frame->pc, &frame->map);
      if (BacktraceMap::IsValid(frame->map)) {
        frame->rel_pc = frame->pc - frame->map.start + frame->map.load_bias;
      } else {
        frame->rel_pc = frame->pc;
      }

      frame->func_name = GetFunctionName(frame->pc, &frame->func_offset, &frame->map);

      num_frames++;
      // If the pc is in a device map, then don't try to step.
      if (frame->map.flags & PROT_DEVICE_MAP) {
        break;
      }
    } else {
      // If the pc is in a device map, then don't try to step.
      backtrace_map_t map;
      FillInMap(pc, &map);
      if (map.flags & PROT_DEVICE_MAP) {
        break;
      }
      num_ignore_frames--;
    }
    // Verify the sp is not in a device map.
    backtrace_map_t map;
    FillInMap(sp, &map);
    if (map.flags & PROT_DEVICE_MAP) {
      break;
    }
    ret = unw_step (&cursor);
  } while (ret > 0 && num_frames < MAX_BACKTRACE_FRAMES);

  return true;
}
Exemplo n.º 29
0
void UK2Node_Event::GetNodeAttributes( TArray<TKeyValuePair<FString, FString>>& OutNodeAttributes ) const
{
	OutNodeAttributes.Add( TKeyValuePair<FString, FString>( TEXT( "Type" ), TEXT( "Event" ) ));
	OutNodeAttributes.Add( TKeyValuePair<FString, FString>( TEXT( "Class" ), GetClass()->GetName() ));
	OutNodeAttributes.Add( TKeyValuePair<FString, FString>( TEXT( "Name" ), GetFunctionName().ToString() ));
}
Exemplo n.º 30
0
void DumpChronoFuncs(PTHDBLK pthdblk, LPSTR lpstrBuff)
{
    PCHRONOCELL    pChronoCell;
    TCHAR          ptchSym [FILENAMELENGTH];
    PTCHAR         ptchFuncName;
    PTCHAR         ptchModule;
    ULONG          ulTotalCalls;
    int            iNest;
    PTCHAR         ptchChronoModule;
    PTCHAR         ptchChronoFuncName;
    PTCHAR         ptchMatch;
    LONGLONG	   liTime;
    TCHAR          chRuntimeSuffix;


    if (cChars)          // if Count is not 0, we have to flush everything
    {
        if ( !WriteFile (hOutFile, lpstrBuff, cChars, &cChars, NULL) )
        {
            CapDbgPrint ("CAP:  DumpChronoFuncs() - "
                      "Error writing to %s - 0x%lx\n",
                      atchOutFileName, GetLastError());
        }

        cChars = 0;
    }

    //CalcIncompleteChronoCalls(pthdblk);
    GetTotalRuntime(pthdblk);

    cChars = sprintf (lpstrBuff,
                      "\r\n\n_________________________________"
                      "________________________________________________"
                      "________________________________________________"
                      "________________________________________\r\n\n\n\n"
                      "CHRONOLOGICAL FUNCTION LISTINGS\r\n"
                      "===============================\r\n");

    if (fChronoDump)
    {
        pChronoCell = pthdblk->pChronoHeadCell;

        while (pChronoCell->ulSymbolAddr != 0L)
        {
            //
            // Get the symbol name using the function address
            //
            strcpy(ptchSym, GetFunctionName (pChronoCell->ulSymbolAddr,
                                             ulLocProfBlkOff,
                                             NULL));

            _strupr(ptchSym);
            _strupr(ptchChronoFuncs);
            ptchFuncName        = strchr(ptchSym, ':') + 1;
            ptchModule          = ptchSym;
            // ???? Check ptchFuncName
            *(ptchFuncName - 1) = '\0';

            if (ptchChronoFuncs[0] != EMPTY_STRING)  // Empty list ?
            {
                ptchChronoModule = (PTCHAR) ptchChronoFuncs;

                while (*ptchChronoModule != '\0')
                {
                    ptchChronoFuncName = strchr(ptchChronoModule, INI_DELIM) + 1;
                    *(ptchChronoFuncName - 1) = '\0';

                    // Look for the Module name
                    ptchMatch = strstr(ptchModule, ptchChronoModule);
                    if (ptchMatch && (*(ptchMatch - 1) != COMMENT_CHAR))
                    {
                        // We have found the module, now check the func name
                        if (strstr(ptchFuncName, ptchChronoFuncName))
                        {
                            *(ptchChronoFuncName - 1) = INI_DELIM;

                            // Dump everything call from this cell only
                            // until the nesting depth is < or == to this cell
                            //
                            DumpChronoEntry(pthdblk,
                                            lpstrBuff,
                                            &pChronoCell,
                                            FALSE);

                            // if found then break out of the
                            // while (ptchChronoModule) loop
                            break;
                        }
                    }

                    // If we get here that means we fail to match a module
                    // name and the func name in the [CHRONO FUNCS] section.
                    // Just bump to next entry
                    //
                    *(ptchChronoFuncName - 1) = INI_DELIM;
                    ptchChronoModule += strlen(ptchChronoModule) + 1;
                }

                if (*ptchChronoModule == '\0')   // If we did not match
                {                                // anything then bump to
                    pChronoCell++;               // next cell
                }
            }
            else
            {
                // Dump everything
                DumpChronoEntry(pthdblk, lpstrBuff, &pChronoCell, TRUE);
            }

            // At this point, pChronoCell has been incremented correctly
            // by DumpChronoEntry or inside the searching loop for
            // " while (* ptchChronoListItem != EMPTY_STRING) ".
            // We just need to loop back.
        }
    }
    else
    {
        cChars += sprintf (
                     lpstrBuff + cChars,
                     "\n\n <<< CHRONO INFO COLLECTED BUT NOT DUMPED >>>\n\n"
                     "================================="
                     "================================================"
                     "================================================"
                     "========================================\r\n\n\n");

    }

    cChars += sprintf(lpstrBuff + cChars,
                      "\n\n______________________________________\n\n\n"
                      " Summary Statistics\n"
                      " ==================\n\n\n");

    ulTotalCalls = 0L;  // Reset our total count for each thread
    for (iNest = 0 ;
         ( (iNest < MAX_NESTING) &&
           (pthdblk->aulDepth[iNest] != 0) ) ;
         iNest++)
    {
        ulTotalCalls += pthdblk->aulDepth[iNest];
        cChars += sprintf(lpstrBuff + cChars,
                          " Total calls Depth [%3d] = [%8lu]\n",
                          iNest,
                          pthdblk->aulDepth[iNest]);
    }

    liTime = liTotalRunTime;
    AdjustTime(&liTime, &chRuntimeSuffix);

    cChars += sprintf(lpstrBuff + cChars,
                      "\n\n______________________________________\n\n"
                      " Total Calls             = [ %8lu]\n"
                      " Total Time-Callees      = [%9lu]%1c\n\n",
                      ulTotalCalls,
                      (ULONG)liTime,
                      chRuntimeSuffix);

}   /* DumpChronoFuncs */