remove trailing whitespace + remove some useless comments

llvm-svn: 212411
This commit is contained in:
Sylvestre Ledru 2014-07-06 17:54:58 +00:00
parent 3cc9d63031
commit ceab3ac375
13 changed files with 2038 additions and 2056 deletions

View File

@ -40,7 +40,7 @@ ASTResultSynthesizer::ASTResultSynthesizer(ASTConsumer *passthrough,
{
if (!m_passthrough)
return;
m_passthrough_sema = dyn_cast<SemaConsumer>(passthrough);
}
@ -49,10 +49,10 @@ ASTResultSynthesizer::~ASTResultSynthesizer()
}
void
ASTResultSynthesizer::Initialize(ASTContext &Context)
ASTResultSynthesizer::Initialize(ASTContext &Context)
{
m_ast_context = &Context;
if (m_passthrough)
m_passthrough->Initialize(Context);
}
@ -75,11 +75,11 @@ ASTResultSynthesizer::TransformTopLevelDecl(Decl* D)
}
}
if (LinkageSpecDecl *linkage_spec_decl = dyn_cast<LinkageSpecDecl>(D))
{
RecordDecl::decl_iterator decl_iterator;
for (decl_iterator = linkage_spec_decl->decls_begin();
decl_iterator != linkage_spec_decl->decls_end();
++decl_iterator)
@ -107,53 +107,53 @@ ASTResultSynthesizer::TransformTopLevelDecl(Decl* D)
}
}
bool
bool
ASTResultSynthesizer::HandleTopLevelDecl(DeclGroupRef D)
{
DeclGroupRef::iterator decl_iterator;
for (decl_iterator = D.begin();
decl_iterator != D.end();
++decl_iterator)
{
Decl *decl = *decl_iterator;
TransformTopLevelDecl(decl);
}
if (m_passthrough)
return m_passthrough->HandleTopLevelDecl(D);
return true;
}
bool
bool
ASTResultSynthesizer::SynthesizeFunctionResult (FunctionDecl *FunDecl)
{
Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
if (!m_sema)
return false;
FunctionDecl *function_decl = FunDecl;
if (!function_decl)
return false;
if (log && log->GetVerbose())
{
std::string s;
raw_string_ostream os(s);
function_decl->print(os);
os.flush();
log->Printf ("Untransformed function AST:\n%s", s.c_str());
}
Stmt *function_body = function_decl->getBody();
CompoundStmt *compound_stmt = dyn_cast<CompoundStmt>(function_body);
bool ret = SynthesizeBodyResult (compound_stmt,
function_decl);
@ -161,14 +161,14 @@ ASTResultSynthesizer::SynthesizeFunctionResult (FunctionDecl *FunDecl)
{
std::string s;
raw_string_ostream os(s);
function_decl->print(os);
os.flush();
log->Printf ("Transformed function AST:\n%s", s.c_str());
}
return ret;
}
@ -176,67 +176,67 @@ bool
ASTResultSynthesizer::SynthesizeObjCMethodResult (ObjCMethodDecl *MethodDecl)
{
Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
if (!m_sema)
return false;
if (!MethodDecl)
return false;
if (log && log->GetVerbose())
{
std::string s;
raw_string_ostream os(s);
MethodDecl->print(os);
os.flush();
log->Printf ("Untransformed method AST:\n%s", s.c_str());
}
Stmt *method_body = MethodDecl->getBody();
if (!method_body)
return false;
CompoundStmt *compound_stmt = dyn_cast<CompoundStmt>(method_body);
bool ret = SynthesizeBodyResult (compound_stmt,
MethodDecl);
if (log && log->GetVerbose())
{
std::string s;
raw_string_ostream os(s);
MethodDecl->print(os);
os.flush();
log->Printf("Transformed method AST:\n%s", s.c_str());
}
return ret;
}
bool
ASTResultSynthesizer::SynthesizeBodyResult (CompoundStmt *Body,
bool
ASTResultSynthesizer::SynthesizeBodyResult (CompoundStmt *Body,
DeclContext *DC)
{
Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
ASTContext &Ctx(*m_ast_context);
if (!Body)
return false;
if (Body->body_empty())
return false;
Stmt **last_stmt_ptr = Body->body_end() - 1;
Stmt *last_stmt = *last_stmt_ptr;
while (dyn_cast<NullStmt>(last_stmt))
{
if (last_stmt_ptr != Body->body_begin())
@ -249,28 +249,28 @@ ASTResultSynthesizer::SynthesizeBodyResult (CompoundStmt *Body,
return false;
}
}
Expr *last_expr = dyn_cast<Expr>(last_stmt);
if (!last_expr)
// No auxiliary variable necessary; expression returns void
return true;
// In C++11, last_expr can be a LValueToRvalue implicit cast. Strip that off if that's the
// case.
do {
ImplicitCastExpr *implicit_cast = dyn_cast<ImplicitCastExpr>(last_expr);
if (!implicit_cast)
break;
if (implicit_cast->getCastKind() != CK_LValueToRValue)
break;
last_expr = implicit_cast->getSubExpr();
} while (0);
// is_lvalue is used to record whether the expression returns an assignable Lvalue or an
// Rvalue. This is relevant because they are handled differently.
//
@ -302,7 +302,7 @@ ASTResultSynthesizer::SynthesizeBodyResult (CompoundStmt *Body,
//
// - In IR transformations, an instruction is inserted at the beginning of the function to
// dereference the pointer resident in the slot. Reads and writes to $__lldb_expr_result
// are redirected at that dereferenced version. Guard variables for the static variable
// are redirected at that dereferenced version. Guard variables for the static variable
// are excised.
//
// - During materialization, $0 (the result persistent variable) is populated with the location
@ -310,46 +310,46 @@ ASTResultSynthesizer::SynthesizeBodyResult (CompoundStmt *Body,
//
// - During dematerialization, $0 is ignored.
bool is_lvalue =
bool is_lvalue =
(last_expr->getValueKind() == VK_LValue || last_expr->getValueKind() == VK_XValue) &&
(last_expr->getObjectKind() == OK_Ordinary);
QualType expr_qual_type = last_expr->getType();
const clang::Type *expr_type = expr_qual_type.getTypePtr();
if (!expr_type)
return false;
if (expr_type->isVoidType())
return true;
if (log)
{
std::string s = expr_qual_type.getAsString();
log->Printf("Last statement is an %s with type: %s", (is_lvalue ? "lvalue" : "rvalue"), s.c_str());
}
clang::VarDecl *result_decl = NULL;
if (is_lvalue)
{
IdentifierInfo *result_ptr_id;
if (expr_type->isFunctionType())
result_ptr_id = &Ctx.Idents.get("$__lldb_expr_result"); // functions actually should be treated like function pointers
else
result_ptr_id = &Ctx.Idents.get("$__lldb_expr_result_ptr");
m_sema->RequireCompleteType(SourceLocation(), expr_qual_type, clang::diag::err_incomplete_type);
QualType ptr_qual_type;
if (expr_qual_type->getAs<ObjCObjectType>() != NULL)
ptr_qual_type = Ctx.getObjCObjectPointerType(expr_qual_type);
else
ptr_qual_type = Ctx.getPointerType(expr_qual_type);
result_decl = VarDecl::Create(Ctx,
DC,
SourceLocation(),
@ -358,61 +358,61 @@ ASTResultSynthesizer::SynthesizeBodyResult (CompoundStmt *Body,
ptr_qual_type,
NULL,
SC_Static);
if (!result_decl)
return false;
ExprResult address_of_expr = m_sema->CreateBuiltinUnaryOp(SourceLocation(), UO_AddrOf, last_expr);
m_sema->AddInitializerToDecl(result_decl, address_of_expr.get(), true, false);
}
else
{
IdentifierInfo &result_id = Ctx.Idents.get("$__lldb_expr_result");
result_decl = VarDecl::Create(Ctx,
DC,
result_decl = VarDecl::Create(Ctx,
DC,
SourceLocation(),
SourceLocation(),
&result_id,
expr_qual_type,
NULL,
&result_id,
expr_qual_type,
NULL,
SC_Static);
if (!result_decl)
return false;
m_sema->AddInitializerToDecl(result_decl, last_expr, true, false);
}
DC->addDecl(result_decl);
///////////////////////////////
// call AddInitializerToDecl
//
//m_sema->AddInitializerToDecl(result_decl, last_expr);
/////////////////////////////////
// call ConvertDeclToDeclGroup
//
Sema::DeclGroupPtrTy result_decl_group_ptr;
result_decl_group_ptr = m_sema->ConvertDeclToDeclGroup(result_decl);
////////////////////////
// call ActOnDeclStmt
//
StmtResult result_initialization_stmt_result(m_sema->ActOnDeclStmt(result_decl_group_ptr,
SourceLocation(),
SourceLocation()));
////////////////////////////////////////////////
// replace the old statement with the new one
//
*last_stmt_ptr = reinterpret_cast<Stmt*>(result_initialization_stmt_result.get());
return true;
@ -420,7 +420,7 @@ ASTResultSynthesizer::SynthesizeBodyResult (CompoundStmt *Body,
void
ASTResultSynthesizer::HandleTranslationUnit(ASTContext &Ctx)
{
{
if (m_passthrough)
m_passthrough->HandleTranslationUnit(Ctx);
}
@ -429,8 +429,8 @@ void
ASTResultSynthesizer::RecordPersistentTypes(DeclContext *FunDeclCtx)
{
typedef DeclContext::specific_decl_iterator<TypeDecl> TypeDeclIterator;
for (TypeDeclIterator i = TypeDeclIterator(FunDeclCtx->decls_begin()),
for (TypeDeclIterator i = TypeDeclIterator(FunDeclCtx->decls_begin()),
e = TypeDeclIterator(FunDeclCtx->decls_end());
i != e;
++i)
@ -439,35 +439,35 @@ ASTResultSynthesizer::RecordPersistentTypes(DeclContext *FunDeclCtx)
}
}
void
void
ASTResultSynthesizer::MaybeRecordPersistentType(TypeDecl *D)
{
if (!D->getIdentifier())
return;
StringRef name = D->getName();
if (name.size() == 0 || name[0] != '$')
return;
Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
ConstString name_cs(name.str().c_str());
if (log)
log->Printf ("Recording persistent type %s\n", name_cs.GetCString());
Decl *D_scratch = m_target.GetClangASTImporter()->DeportDecl(m_target.GetScratchClangASTContext()->getASTContext(),
Decl *D_scratch = m_target.GetClangASTImporter()->DeportDecl(m_target.GetScratchClangASTContext()->getASTContext(),
m_ast_context,
D);
if (TypeDecl *TypeDecl_scratch = dyn_cast<TypeDecl>(D_scratch))
m_target.GetPersistentVariables().RegisterPersistentType(name_cs, TypeDecl_scratch);
}
void
void
ASTResultSynthesizer::HandleTagDeclDefinition(TagDecl *D)
{
{
if (m_passthrough)
m_passthrough->HandleTagDeclDefinition(D);
}
@ -479,15 +479,15 @@ ASTResultSynthesizer::CompleteTentativeDefinition(VarDecl *D)
m_passthrough->CompleteTentativeDefinition(D);
}
void
ASTResultSynthesizer::HandleVTable(CXXRecordDecl *RD, bool DefinitionRequired)
void
ASTResultSynthesizer::HandleVTable(CXXRecordDecl *RD, bool DefinitionRequired)
{
if (m_passthrough)
m_passthrough->HandleVTable(RD, DefinitionRequired);
}
void
ASTResultSynthesizer::PrintStats()
ASTResultSynthesizer::PrintStats()
{
if (m_passthrough)
m_passthrough->PrintStats();
@ -497,16 +497,16 @@ void
ASTResultSynthesizer::InitializeSema(Sema &S)
{
m_sema = &S;
if (m_passthrough_sema)
m_passthrough_sema->InitializeSema(S);
}
void
ASTResultSynthesizer::ForgetSema()
void
ASTResultSynthesizer::ForgetSema()
{
m_sema = NULL;
if (m_passthrough_sema)
m_passthrough_sema->ForgetSema();
}

View File

@ -39,7 +39,7 @@ ASTStructExtractor::ASTStructExtractor(ASTConsumer *passthrough,
{
if (!m_passthrough)
return;
m_passthrough_sema = dyn_cast<SemaConsumer>(passthrough);
}
@ -48,10 +48,10 @@ ASTStructExtractor::~ASTStructExtractor()
}
void
ASTStructExtractor::Initialize(ASTContext &Context)
ASTStructExtractor::Initialize(ASTContext &Context)
{
m_ast_context = &Context;
if (m_passthrough)
m_passthrough->Initialize(Context);
}
@ -61,17 +61,17 @@ ASTStructExtractor::ExtractFromFunctionDecl(FunctionDecl *F)
{
if (!F->hasBody())
return;
Stmt *body_stmt = F->getBody();
CompoundStmt *body_compound_stmt = dyn_cast<CompoundStmt>(body_stmt);
if (!body_compound_stmt)
return; // do we have to handle this?
RecordDecl *struct_decl = NULL;
StringRef desired_name(m_struct_name.c_str());
for (CompoundStmt::const_body_iterator bi = body_compound_stmt->body_begin(), be = body_compound_stmt->body_end();
bi != be;
++bi)
@ -95,26 +95,26 @@ ASTStructExtractor::ExtractFromFunctionDecl(FunctionDecl *F)
if (struct_decl)
break;
}
if (!struct_decl)
return;
const ASTRecordLayout* struct_layout(&m_ast_context->getASTRecordLayout (struct_decl));
if (!struct_layout)
return;
m_function.m_struct_size = struct_layout->getSize().getQuantity(); // TODO Store m_struct_size as CharUnits
m_function.m_struct_size = struct_layout->getSize().getQuantity(); // TODO Store m_struct_size as CharUnits
m_function.m_return_offset = struct_layout->getFieldOffset(struct_layout->getFieldCount() - 1) / 8;
m_function.m_return_size = struct_layout->getDataSize().getQuantity() - m_function.m_return_offset;
for (unsigned field_index = 0, num_fields = struct_layout->getFieldCount();
field_index < num_fields;
++field_index)
{
m_function.m_member_offsets.push_back(struct_layout->getFieldOffset(field_index) / 8);
}
m_function.m_struct_valid = true;
}
@ -122,11 +122,11 @@ void
ASTStructExtractor::ExtractFromTopLevelDecl(Decl* D)
{
LinkageSpecDecl *linkage_spec_decl = dyn_cast<LinkageSpecDecl>(D);
if (linkage_spec_decl)
{
RecordDecl::decl_iterator decl_iterator;
for (decl_iterator = linkage_spec_decl->decls_begin();
decl_iterator != linkage_spec_decl->decls_end();
++decl_iterator)
@ -134,9 +134,9 @@ ASTStructExtractor::ExtractFromTopLevelDecl(Decl* D)
ExtractFromTopLevelDecl(*decl_iterator);
}
}
FunctionDecl *function_decl = dyn_cast<FunctionDecl>(D);
if (m_ast_context &&
function_decl &&
!m_function.m_wrapper_function_name.compare(function_decl->getNameAsString().c_str()))
@ -145,20 +145,20 @@ ASTStructExtractor::ExtractFromTopLevelDecl(Decl* D)
}
}
bool
bool
ASTStructExtractor::HandleTopLevelDecl(DeclGroupRef D)
{
DeclGroupRef::iterator decl_iterator;
for (decl_iterator = D.begin();
decl_iterator != D.end();
++decl_iterator)
{
Decl *decl = *decl_iterator;
ExtractFromTopLevelDecl(decl);
}
if (m_passthrough)
return m_passthrough->HandleTopLevelDecl(D);
return true;
@ -166,12 +166,12 @@ ASTStructExtractor::HandleTopLevelDecl(DeclGroupRef D)
void
ASTStructExtractor::HandleTranslationUnit(ASTContext &Ctx)
{
{
if (m_passthrough)
m_passthrough->HandleTranslationUnit(Ctx);
}
void
void
ASTStructExtractor::HandleTagDeclDefinition(TagDecl *D)
{
if (m_passthrough)
@ -185,15 +185,15 @@ ASTStructExtractor::CompleteTentativeDefinition(VarDecl *D)
m_passthrough->CompleteTentativeDefinition(D);
}
void
ASTStructExtractor::HandleVTable(CXXRecordDecl *RD, bool DefinitionRequired)
void
ASTStructExtractor::HandleVTable(CXXRecordDecl *RD, bool DefinitionRequired)
{
if (m_passthrough)
m_passthrough->HandleVTable(RD, DefinitionRequired);
}
void
ASTStructExtractor::PrintStats()
ASTStructExtractor::PrintStats()
{
if (m_passthrough)
m_passthrough->PrintStats();
@ -204,17 +204,17 @@ ASTStructExtractor::InitializeSema(Sema &S)
{
m_sema = &S;
m_action = reinterpret_cast<Action*>(m_sema);
if (m_passthrough_sema)
m_passthrough_sema->InitializeSema(S);
}
void
ASTStructExtractor::ForgetSema()
void
ASTStructExtractor::ForgetSema()
{
m_sema = NULL;
m_action = NULL;
if (m_passthrough_sema)
m_passthrough_sema->ForgetSema();
}

View File

@ -25,32 +25,32 @@
using namespace clang;
using namespace lldb_private;
ClangASTSource::~ClangASTSource()
ClangASTSource::~ClangASTSource()
{
m_ast_importer->ForgetDestination(m_ast_context);
// We are in the process of destruction, don't create clang ast context on demand
// by passing false to Target::GetScratchClangASTContext(create_on_demand).
ClangASTContext *scratch_clang_ast_context = m_target->GetScratchClangASTContext(false);
if (!scratch_clang_ast_context)
return;
clang::ASTContext *scratch_ast_context = scratch_clang_ast_context->getASTContext();
if (!scratch_ast_context)
return;
if (m_ast_context != scratch_ast_context)
m_ast_importer->ForgetSource(scratch_ast_context, m_ast_context);
}
void
ClangASTSource::StartTranslationUnit(ASTConsumer *Consumer)
ClangASTSource::StartTranslationUnit(ASTConsumer *Consumer)
{
if (!m_ast_context)
return;
m_ast_context->getTranslationUnitDecl()->setHasExternalVisibleStorage();
m_ast_context->getTranslationUnitDecl()->setHasExternalLexicalStorage();
}
@ -59,33 +59,33 @@ ClangASTSource::StartTranslationUnit(ASTConsumer *Consumer)
bool
ClangASTSource::FindExternalVisibleDeclsByName
(
const DeclContext *decl_ctx,
const DeclContext *decl_ctx,
DeclarationName clang_decl_name
)
)
{
if (!m_ast_context)
{
SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name);
return false;
}
if (GetImportInProgress())
{
SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name);
return false;
}
std::string decl_name (clang_decl_name.getAsString());
// if (m_decl_map.DoingASTImport ())
// return DeclContext::lookup_result();
//
//
switch (clang_decl_name.getNameKind()) {
// Normal identifiers.
case DeclarationName::Identifier:
{
clang::IdentifierInfo *identifier_info = clang_decl_name.getAsIdentifierInfo();
if (!identifier_info ||
identifier_info->getBuiltinID() != 0)
{
@ -94,27 +94,27 @@ ClangASTSource::FindExternalVisibleDeclsByName
}
}
break;
// Operator names. Not important for now.
case DeclarationName::CXXOperatorName:
case DeclarationName::CXXLiteralOperatorName:
SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name);
return false;
// Using directives found in this context.
// Tell Sema we didn't find any or we'll end up getting asked a *lot*.
case DeclarationName::CXXUsingDirective:
SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name);
return false;
case DeclarationName::ObjCZeroArgSelector:
case DeclarationName::ObjCOneArgSelector:
case DeclarationName::ObjCMultiArgSelector:
{
llvm::SmallVector<NamedDecl*, 1> method_decls;
llvm::SmallVector<NamedDecl*, 1> method_decls;
NameSearchContext method_search_context (*this, method_decls, clang_decl_name, decl_ctx);
FindObjCMethodDecls(method_search_context);
SetExternalVisibleDeclsForName (decl_ctx, clang_decl_name, method_decls);
@ -131,21 +131,21 @@ ClangASTSource::FindExternalVisibleDeclsByName
if (!GetLookupsEnabled())
{
// Wait until we see a '$' at the start of a name before we start doing
// Wait until we see a '$' at the start of a name before we start doing
// any lookups so we can avoid lookup up all of the builtin types.
if (!decl_name.empty() && decl_name[0] == '$')
{
SetLookupsEnabled (true);
}
else
{
{
SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name);
return false;
}
}
ConstString const_decl_name(decl_name.c_str());
const char *uniqued_const_decl_name = const_decl_name.GetCString();
if (m_active_lookups.find (uniqued_const_decl_name) != m_active_lookups.end())
{
@ -157,7 +157,7 @@ ClangASTSource::FindExternalVisibleDeclsByName
// static uint32_t g_depth = 0;
// ++g_depth;
// printf("[%5u] FindExternalVisibleDeclsByName() \"%s\"\n", g_depth, uniqued_const_decl_name);
llvm::SmallVector<NamedDecl*, 4> name_decls;
llvm::SmallVector<NamedDecl*, 4> name_decls;
NameSearchContext name_search_context(*this, name_decls, clang_decl_name, decl_ctx);
FindExternalVisibleDecls(name_search_context);
SetExternalVisibleDeclsForName (decl_ctx, clang_decl_name, name_decls);
@ -253,7 +253,7 @@ ClangASTSource::CompleteType (TagDecl *tag_decl)
}
}
}
else
else
{
TypeList types;
@ -313,7 +313,7 @@ ClangASTSource::CompleteType (clang::ObjCInterfaceDecl *interface_decl)
interface_decl->getName().str().c_str());
log->Printf(" [COID] Before:");
ASTDumper dumper((Decl*)interface_decl);
dumper.ToLog(log, " [COID] ");
dumper.ToLog(log, " [COID] ");
}
Decl *original_decl = NULL;
@ -342,7 +342,7 @@ ClangASTSource::CompleteType (clang::ObjCInterfaceDecl *interface_decl)
{
log->Printf(" [COID] After:");
ASTDumper dumper((Decl*)interface_decl);
dumper.ToLog(log, " [COID] ");
dumper.ToLog(log, " [COID] ");
}
}
@ -350,36 +350,36 @@ clang::ObjCInterfaceDecl *
ClangASTSource::GetCompleteObjCInterface (clang::ObjCInterfaceDecl *interface_decl)
{
lldb::ProcessSP process(m_target->GetProcessSP());
if (!process)
return NULL;
ObjCLanguageRuntime *language_runtime(process->GetObjCLanguageRuntime());
if (!language_runtime)
return NULL;
ConstString class_name(interface_decl->getNameAsString().c_str());
lldb::TypeSP complete_type_sp(language_runtime->LookupInCompleteClassCache(class_name));
if (!complete_type_sp)
return NULL;
TypeFromUser complete_type = TypeFromUser(complete_type_sp->GetClangFullType());
lldb::clang_type_t complete_opaque_type = complete_type.GetOpaqueQualType();
if (!complete_opaque_type)
return NULL;
const clang::Type *complete_clang_type = QualType::getFromOpaquePtr(complete_opaque_type).getTypePtr();
const ObjCInterfaceType *complete_interface_type = dyn_cast<ObjCInterfaceType>(complete_clang_type);
if (!complete_interface_type)
return NULL;
ObjCInterfaceDecl *complete_iface_decl(complete_interface_type->getDecl());
return complete_iface_decl;
}
@ -608,133 +608,133 @@ ClangASTSource::FindExternalVisibleDecls (NameSearchContext &context)
}
}
void
ClangASTSource::FindExternalVisibleDecls (NameSearchContext &context,
void
ClangASTSource::FindExternalVisibleDecls (NameSearchContext &context,
lldb::ModuleSP module_sp,
ClangNamespaceDecl &namespace_decl,
unsigned int current_id)
{
assert (m_ast_context);
Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
SymbolContextList sc_list;
const ConstString name(context.m_decl_name.getAsString().c_str());
const char *name_unique_cstr = name.GetCString();
static ConstString id_name("id");
static ConstString Class_name("Class");
if (name == id_name || name == Class_name)
return;
if (name_unique_cstr == NULL)
return;
// The ClangASTSource is not responsible for finding $-names.
if (name_unique_cstr[0] == '$')
return;
if (module_sp && namespace_decl)
{
ClangNamespaceDecl found_namespace_decl;
SymbolVendor *symbol_vendor = module_sp->GetSymbolVendor();
if (symbol_vendor)
{
SymbolContext null_sc;
found_namespace_decl = symbol_vendor->FindNamespace(null_sc, name, &namespace_decl);
if (found_namespace_decl)
{
context.m_namespace_map->push_back(std::pair<lldb::ModuleSP, ClangNamespaceDecl>(module_sp, found_namespace_decl));
if (log)
log->Printf(" CAS::FEVD[%u] Found namespace %s in module %s",
current_id,
name.GetCString(),
name.GetCString(),
module_sp->GetFileSpec().GetFilename().GetCString());
}
}
}
else
else
{
const ModuleList &target_images = m_target->GetImages();
Mutex::Locker modules_locker (target_images.GetMutex());
for (size_t i = 0, e = target_images.GetSize(); i < e; ++i)
{
lldb::ModuleSP image = target_images.GetModuleAtIndexUnlocked(i);
if (!image)
continue;
ClangNamespaceDecl found_namespace_decl;
SymbolVendor *symbol_vendor = image->GetSymbolVendor();
if (!symbol_vendor)
continue;
SymbolContext null_sc;
found_namespace_decl = symbol_vendor->FindNamespace(null_sc, name, &namespace_decl);
if (found_namespace_decl)
{
context.m_namespace_map->push_back(std::pair<lldb::ModuleSP, ClangNamespaceDecl>(image, found_namespace_decl));
if (log)
log->Printf(" CAS::FEVD[%u] Found namespace %s in module %s",
current_id,
name.GetCString(),
name.GetCString(),
image->GetFileSpec().GetFilename().GetCString());
}
}
}
do
do
{
TypeList types;
SymbolContext null_sc;
const bool exact_match = false;
if (module_sp && namespace_decl)
module_sp->FindTypesInNamespace(null_sc, name, &namespace_decl, 1, types);
else
else
m_target->GetImages().FindTypes(null_sc, name, exact_match, 1, types);
if (types.GetSize())
{
lldb::TypeSP type_sp = types.GetTypeAtIndex(0);
if (log)
{
const char *name_string = type_sp->GetName().GetCString();
log->Printf(" CAS::FEVD[%u] Matching type found for \"%s\": %s",
current_id,
name.GetCString(),
log->Printf(" CAS::FEVD[%u] Matching type found for \"%s\": %s",
current_id,
name.GetCString(),
(name_string ? name_string : "<anonymous>"));
}
ClangASTType full_type = type_sp->GetClangFullType();
ClangASTType copied_clang_type (GuardedCopyType(full_type));
if (!copied_clang_type)
{
{
if (log)
log->Printf(" CAS::FEVD[%u] - Couldn't export a type",
current_id);
break;
}
context.AddTypeDecl(copied_clang_type);
}
else
@ -742,55 +742,55 @@ ClangASTSource::FindExternalVisibleDecls (NameSearchContext &context,
do
{
// Couldn't find any types elsewhere. Try the Objective-C runtime if one exists.
lldb::ProcessSP process(m_target->GetProcessSP());
if (!process)
break;
ObjCLanguageRuntime *language_runtime(process->GetObjCLanguageRuntime());
if (!language_runtime)
break;
TypeVendor *type_vendor = language_runtime->GetTypeVendor();
if (!type_vendor)
break;
bool append = false;
uint32_t max_matches = 1;
std::vector <ClangASTType> types;
if (!type_vendor->FindTypes(name,
append,
max_matches,
types))
break;
if (log)
{
{
log->Printf(" CAS::FEVD[%u] Matching type found for \"%s\" in the runtime",
current_id,
name.GetCString());
}
ClangASTType copied_clang_type (GuardedCopyType(types[0]));
if (!copied_clang_type)
{
if (log)
log->Printf(" CAS::FEVD[%u] - Couldn't export a type from the runtime",
current_id);
break;
}
context.AddTypeDecl(copied_clang_type);
}
while(0);
}
} while(0);
}
@ -804,7 +804,7 @@ public:
D *decl;
};
template <class D2, template <class D> class TD, class D1>
template <class D2, template <class D> class TD, class D1>
TD<D2>
DynCast(TD<D1> source)
{
@ -814,19 +814,19 @@ DynCast(TD<D1> source)
template <class D = Decl> class DeclFromParser;
template <class D = Decl> class DeclFromUser;
template <class D> class DeclFromParser : public TaggedASTDecl<D> {
template <class D> class DeclFromParser : public TaggedASTDecl<D> {
public:
DeclFromParser() : TaggedASTDecl<D>() { }
DeclFromParser(D *_decl) : TaggedASTDecl<D>(_decl) { }
DeclFromUser<D> GetOrigin(ClangASTImporter *importer);
};
template <class D> class DeclFromUser : public TaggedASTDecl<D> {
template <class D> class DeclFromUser : public TaggedASTDecl<D> {
public:
DeclFromUser() : TaggedASTDecl<D>() { }
DeclFromUser(D *_decl) : TaggedASTDecl<D>(_decl) { }
DeclFromParser<D> Import(ClangASTImporter *importer, ASTContext &dest_ctx);
};
@ -863,7 +863,7 @@ FindObjCMethodDeclsWithOrigin (unsigned int current_id,
clang::ASTContext *original_ctx = &original_interface_decl->getASTContext();
Selector original_selector;
if (decl_name.isObjCZeroArgSelector())
{
IdentifierInfo *ident = &original_ctx->Idents.get(decl_name.getAsString());
@ -879,59 +879,59 @@ FindObjCMethodDeclsWithOrigin (unsigned int current_id,
else
{
SmallVector<IdentifierInfo *, 4> idents;
clang::Selector sel = decl_name.getObjCSelector();
unsigned num_args = sel.getNumArgs();
for (unsigned i = 0;
i != num_args;
++i)
{
idents.push_back(&original_ctx->Idents.get(sel.getNameForSlot(i)));
}
original_selector = original_ctx->Selectors.getSelector(num_args, idents.data());
}
DeclarationName original_decl_name(original_selector);
ObjCInterfaceDecl::lookup_result result = original_interface_decl->lookup(original_decl_name);
if (result.empty())
return false;
if (!result[0])
return false;
for (NamedDecl *named_decl : result)
{
ObjCMethodDecl *result_method = dyn_cast<ObjCMethodDecl>(named_decl);
if (!result_method)
return false;
Decl *copied_decl = ast_importer->CopyDecl(ast_context, &result_method->getASTContext(), result_method);
if (!copied_decl)
return false;
ObjCMethodDecl *copied_method_decl = dyn_cast<ObjCMethodDecl>(copied_decl);
if (!copied_method_decl)
return false;
Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
if (log)
{
ASTDumper dumper((Decl*)copied_method_decl);
log->Printf(" CAS::FOMD[%d] found (%s) %s", current_id, log_info, dumper.GetCString());
}
context.AddNamedDecl(copied_method_decl);
}
return true;
}
@ -991,7 +991,7 @@ ClangASTSource::FindObjCMethodDecls (NameSearchContext &context)
++i)
{
llvm::StringRef r = sel.getNameForSlot(i);
ss.Printf("%s:", r.str().c_str());
ss.Printf("%s:", r.str().c_str());
}
}
ss.Flush();
@ -1004,7 +1004,7 @@ ClangASTSource::FindObjCMethodDecls (NameSearchContext &context)
if (log)
log->Printf("ClangASTSource::FindObjCMethodDecls[%d] on (ASTContext*)%p for selector [%s %s]",
current_id, static_cast<void*>(m_ast_context),
interface_decl->getNameAsString().c_str(),
interface_decl->getNameAsString().c_str(),
selector_name.AsCString());
SymbolContextList sc_list;
@ -1220,7 +1220,7 @@ ClangASTSource::FindObjCMethodDecls (NameSearchContext &context)
}
static bool
FindObjCPropertyAndIvarDeclsWithOrigin (unsigned int current_id,
FindObjCPropertyAndIvarDeclsWithOrigin (unsigned int current_id,
NameSearchContext &context,
clang::ASTContext &ast_context,
ClangASTImporter *ast_importer,
@ -1230,15 +1230,15 @@ FindObjCPropertyAndIvarDeclsWithOrigin (unsigned int current_id,
if (origin_iface_decl.IsInvalid())
return false;
std::string name_str = context.m_decl_name.getAsString();
StringRef name(name_str.c_str());
IdentifierInfo &name_identifier(origin_iface_decl->getASTContext().Idents.get(name));
DeclFromUser<ObjCPropertyDecl> origin_property_decl(origin_iface_decl->FindPropertyDeclaration(&name_identifier));
bool found = false;
if (origin_property_decl.IsValid())
{
DeclFromParser<ObjCPropertyDecl> parser_property_decl(origin_property_decl.Import(ast_importer, ast_context));
@ -1249,14 +1249,14 @@ FindObjCPropertyAndIvarDeclsWithOrigin (unsigned int current_id,
ASTDumper dumper((Decl*)parser_property_decl.decl);
log->Printf(" CAS::FOPD[%d] found %s", current_id, dumper.GetCString());
}
context.AddNamedDecl(parser_property_decl.decl);
found = true;
}
}
DeclFromUser<ObjCIvarDecl> origin_ivar_decl(origin_iface_decl->getIvarDecl(&name_identifier));
if (origin_ivar_decl.IsValid())
{
DeclFromParser<ObjCIvarDecl> parser_ivar_decl(origin_ivar_decl.Import(ast_importer, ast_context));
@ -1267,12 +1267,12 @@ FindObjCPropertyAndIvarDeclsWithOrigin (unsigned int current_id,
ASTDumper dumper((Decl*)parser_ivar_decl.decl);
log->Printf(" CAS::FOPD[%d] found %s", current_id, dumper.GetCString());
}
context.AddNamedDecl(parser_ivar_decl.decl);
found = true;
}
}
return found;
}
@ -1292,13 +1292,13 @@ ClangASTSource::FindObjCPropertyAndIvarDecls (NameSearchContext &context)
if (log)
log->Printf("ClangASTSource::FindObjCPropertyAndIvarDecls[%d] on (ASTContext*)%p for '%s.%s'",
current_id, static_cast<void*>(m_ast_context),
parser_iface_decl->getNameAsString().c_str(),
parser_iface_decl->getNameAsString().c_str(),
context.m_decl_name.getAsString().c_str());
if (FindObjCPropertyAndIvarDeclsWithOrigin(current_id,
context,
*m_ast_context,
m_ast_importer,
if (FindObjCPropertyAndIvarDeclsWithOrigin(current_id,
context,
*m_ast_context,
m_ast_importer,
origin_iface_decl))
return;
@ -1330,10 +1330,10 @@ ClangASTSource::FindObjCPropertyAndIvarDecls (NameSearchContext &context)
static_cast<const void*>(complete_iface_decl.decl),
static_cast<void*>(&complete_iface_decl->getASTContext()));
FindObjCPropertyAndIvarDeclsWithOrigin(current_id,
context,
*m_ast_context,
m_ast_importer,
FindObjCPropertyAndIvarDeclsWithOrigin(current_id,
context,
*m_ast_context,
m_ast_importer,
complete_iface_decl);
return;
@ -1399,13 +1399,13 @@ typedef llvm::DenseMap <const CXXRecordDecl *, CharUnits> BaseOffsetMap;
template <class D, class O>
static bool
ImportOffsetMap (llvm::DenseMap <const D*, O> &destination_map,
ImportOffsetMap (llvm::DenseMap <const D*, O> &destination_map,
llvm::DenseMap <const D*, O> &source_map,
ClangASTImporter *importer,
ASTContext &dest_ctx)
{
typedef llvm::DenseMap <const D*, O> MapType;
for (typename MapType::iterator fi = source_map.begin(), fe = source_map.end();
fi != fe;
++fi)
@ -1416,7 +1416,7 @@ ImportOffsetMap (llvm::DenseMap <const D*, O> &destination_map,
return false;
destination_map.insert(std::pair<const D *, O>(parser_decl.decl, fi->second));
}
return true;
}
@ -1424,47 +1424,47 @@ template <bool IsVirtual> bool ExtractBaseOffsets (const ASTRecordLayout &record
DeclFromUser<const CXXRecordDecl> &record,
BaseOffsetMap &base_offsets)
{
for (CXXRecordDecl::base_class_const_iterator
bi = (IsVirtual ? record->vbases_begin() : record->bases_begin()),
for (CXXRecordDecl::base_class_const_iterator
bi = (IsVirtual ? record->vbases_begin() : record->bases_begin()),
be = (IsVirtual ? record->vbases_end() : record->bases_end());
bi != be;
++bi)
{
if (!IsVirtual && bi->isVirtual())
continue;
const clang::Type *origin_base_type = bi->getType().getTypePtr();
const clang::RecordType *origin_base_record_type = origin_base_type->getAs<RecordType>();
if (!origin_base_record_type)
return false;
DeclFromUser <RecordDecl> origin_base_record(origin_base_record_type->getDecl());
if (origin_base_record.IsInvalid())
return false;
DeclFromUser <CXXRecordDecl> origin_base_cxx_record(DynCast<CXXRecordDecl>(origin_base_record));
if (origin_base_cxx_record.IsInvalid())
return false;
CharUnits base_offset;
if (IsVirtual)
base_offset = record_layout.getVBaseClassOffset(origin_base_cxx_record.decl);
else
base_offset = record_layout.getBaseClassOffset(origin_base_cxx_record.decl);
base_offsets.insert(std::pair<const CXXRecordDecl *, CharUnits>(origin_base_cxx_record.decl, base_offset));
}
return true;
}
bool
bool
ClangASTSource::layoutRecordType(const RecordDecl *record,
uint64_t &size,
uint64_t &size,
uint64_t &alignment,
FieldOffsetMap &field_offsets,
BaseOffsetMap &base_offsets,
@ -1584,7 +1584,7 @@ ClangASTSource::layoutRecordType(const RecordDecl *record,
return true;
}
void
void
ClangASTSource::CompleteNamespaceMap (ClangASTImporter::NamespaceMapSP &namespace_map,
const ConstString &name,
ClangASTImporter::NamespaceMapSP &parent_map) const
@ -1635,7 +1635,7 @@ ClangASTSource::CompleteNamespaceMap (ClangASTImporter::NamespaceMapSP &namespac
if (log)
log->Printf(" CMN[%u] Found namespace %s in module %s",
current_id,
name.GetCString(),
name.GetCString(),
module_sp->GetFileSpec().GetFilename().GetCString());
}
}
@ -1672,7 +1672,7 @@ ClangASTSource::CompleteNamespaceMap (ClangASTImporter::NamespaceMapSP &namespac
if (log)
log->Printf(" CMN[%u] Found namespace %s in module %s",
current_id,
name.GetCString(),
name.GetCString(),
image->GetFileSpec().GetFilename().GetCString());
}
}
@ -1683,23 +1683,23 @@ ClangASTSource::AddNamespace (NameSearchContext &context, ClangASTImporter::Name
{
if (!namespace_decls)
return NULL;
const ClangNamespaceDecl &namespace_decl = namespace_decls->begin()->second;
Decl *copied_decl = m_ast_importer->CopyDecl(m_ast_context, namespace_decl.GetASTContext(), namespace_decl.GetNamespaceDecl());
if (!copied_decl)
return NULL;
NamespaceDecl *copied_namespace_decl = dyn_cast<NamespaceDecl>(copied_decl);
if (!copied_namespace_decl)
return NULL;
context.m_decls.push_back(copied_namespace_decl);
m_ast_importer->RegisterNamespaceMap(copied_namespace_decl, namespace_decls);
return dyn_cast<NamespaceDecl>(copied_decl);
}
@ -1707,18 +1707,18 @@ ClangASTType
ClangASTSource::GuardedCopyType (const ClangASTType &src_type)
{
ClangASTMetrics::RegisterLLDBImport();
SetImportInProgress(true);
QualType copied_qual_type = m_ast_importer->CopyType (m_ast_context, src_type.GetASTContext(), src_type.GetQualType());
SetImportInProgress(false);
if (copied_qual_type.getAsOpaquePtr() && copied_qual_type->getCanonicalTypeInternal().isNull())
// this shouldn't happen, but we're hardening because the AST importer seems to be generating bad types
// on occasion.
return ClangASTType();
return ClangASTType(m_ast_context, copied_qual_type);
}
@ -1729,39 +1729,39 @@ NameSearchContext::AddVarDecl(const ClangASTType &type)
if (!type.IsValid())
return NULL;
IdentifierInfo *ii = m_decl_name.getAsIdentifierInfo();
clang::ASTContext *ast = type.GetASTContext();
clang::NamedDecl *Decl = VarDecl::Create(*ast,
const_cast<DeclContext*>(m_decl_context),
SourceLocation(),
const_cast<DeclContext*>(m_decl_context),
SourceLocation(),
ii,
SourceLocation(),
ii,
type.GetQualType(),
0,
0,
SC_Static);
m_decls.push_back(Decl);
return Decl;
}
clang::NamedDecl *
NameSearchContext::AddFunDecl (const ClangASTType &type)
NameSearchContext::AddFunDecl (const ClangASTType &type)
{
assert (type && "Type for variable must be valid!");
if (!type.IsValid())
return NULL;
if (m_function_types.count(type))
return NULL;
m_function_types.insert(type);
QualType qual_type (type.GetQualType());
clang::ASTContext *ast = type.GetASTContext();
const bool isInlineSpecified = false;
@ -1783,20 +1783,20 @@ NameSearchContext::AddFunDecl (const ClangASTType &type)
// We have to do more than just synthesize the FunctionDecl. We have to
// synthesize ParmVarDecls for all of the FunctionDecl's arguments. To do
// this, we raid the function's FunctionProtoType for types.
const FunctionProtoType *func_proto_type = qual_type.getTypePtr()->getAs<FunctionProtoType>();
if (func_proto_type)
{
{
unsigned NumArgs = func_proto_type->getNumParams();
unsigned ArgIndex;
SmallVector<ParmVarDecl *, 5> parm_var_decls;
for (ArgIndex = 0; ArgIndex < NumArgs; ++ArgIndex)
{
QualType arg_qual_type (func_proto_type->getParamType(ArgIndex));
parm_var_decls.push_back(ParmVarDecl::Create (*ast,
const_cast<DeclContext*>(m_decl_context),
SourceLocation(),
@ -1807,7 +1807,7 @@ NameSearchContext::AddFunDecl (const ClangASTType &type)
SC_Static,
NULL));
}
func_decl->setParams(ArrayRef<ParmVarDecl*>(parm_var_decls));
}
else
@ -1817,9 +1817,9 @@ NameSearchContext::AddFunDecl (const ClangASTType &type)
if (log)
log->Printf("Function type wasn't a FunctionProtoType");
}
m_decls.push_back(func_decl);
return func_decl;
}
@ -1827,13 +1827,13 @@ clang::NamedDecl *
NameSearchContext::AddGenericFunDecl()
{
FunctionProtoType::ExtProtoInfo proto_info;
proto_info.Variadic = true;
QualType generic_function_type(m_ast_source.m_ast_context->getFunctionType (m_ast_source.m_ast_context->UnknownAnyTy, // result
ArrayRef<QualType>(), // argument types
proto_info));
return AddFunDecl(ClangASTType (m_ast_source.m_ast_context, generic_function_type));
}
@ -1847,32 +1847,32 @@ NameSearchContext::AddTypeDecl(const ClangASTType &clang_type)
if (const TypedefType *typedef_type = llvm::dyn_cast<TypedefType>(qual_type))
{
TypedefNameDecl *typedef_name_decl = typedef_type->getDecl();
m_decls.push_back(typedef_name_decl);
return (NamedDecl*)typedef_name_decl;
}
else if (const TagType *tag_type = qual_type->getAs<TagType>())
{
TagDecl *tag_decl = tag_type->getDecl();
m_decls.push_back(tag_decl);
return tag_decl;
}
else if (const ObjCObjectType *objc_object_type = qual_type->getAs<ObjCObjectType>())
{
ObjCInterfaceDecl *interface_decl = objc_object_type->getInterface();
m_decls.push_back((NamedDecl*)interface_decl);
return (NamedDecl*)interface_decl;
}
}
return NULL;
}
void
void
NameSearchContext::AddLookupResult (clang::DeclContextLookupConstResult result)
{
for (clang::NamedDecl *decl : result)

File diff suppressed because it is too large Load Diff

View File

@ -87,7 +87,7 @@ std::string GetBuiltinIncludePath(const char *Argv0) {
llvm::sys::path::append(P, "lib", "clang", CLANG_VERSION_STRING,
"include");
}
return P.str();
}
@ -111,16 +111,16 @@ ClangExpressionParser::ClangExpressionParser (ExecutionContextScope *exe_scope,
llvm::InitializeAllDisassemblers();
}
} InitializeLLVM;
// 1. Create a new compiler instance.
m_compiler.reset(new CompilerInstance());
m_compiler.reset(new CompilerInstance());
// 2. Install the target.
lldb::TargetSP target_sp;
if (exe_scope)
target_sp = exe_scope->CalculateTarget();
// TODO: figure out what to really do when we don't have a valid target.
// Sometimes this will be ok to just use the host target triple (when we
// evaluate say "2+3", but other expressions like breakpoint conditions
@ -135,14 +135,14 @@ ClangExpressionParser::ClangExpressionParser (ExecutionContextScope *exe_scope,
{
m_compiler->getTargetOpts().Triple = llvm::sys::getDefaultTargetTriple();
}
if (target_sp->GetArchitecture().GetMachine() == llvm::Triple::x86 ||
target_sp->GetArchitecture().GetMachine() == llvm::Triple::x86_64)
{
m_compiler->getTargetOpts().Features.push_back("+sse");
m_compiler->getTargetOpts().Features.push_back("+sse2");
}
// Any arm32 iOS environment, but not on arm64
if (m_compiler->getTargetOpts().Triple.find("arm64") == std::string::npos &&
m_compiler->getTargetOpts().Triple.find("arm") != std::string::npos &&
@ -158,11 +158,11 @@ ClangExpressionParser::ClangExpressionParser (ExecutionContextScope *exe_scope,
m_compiler->getDiagnostics(), m_compiler->getInvocation().TargetOpts));
assert (m_compiler->hasTarget());
// 3. Set options.
lldb::LanguageType language = expr.Language();
switch (language)
{
case lldb::eLanguageTypeC:
@ -183,20 +183,20 @@ ClangExpressionParser::ClangExpressionParser (ExecutionContextScope *exe_scope,
m_compiler->getLangOpts().CPlusPlus11 = true;
break;
}
m_compiler->getLangOpts().Bool = true;
m_compiler->getLangOpts().WChar = true;
m_compiler->getLangOpts().Blocks = true;
m_compiler->getLangOpts().DebuggerSupport = true; // Features specifically for debugger clients
if (expr.DesiredResultType() == ClangExpression::eResultTypeId)
m_compiler->getLangOpts().DebuggerCastResultToId = true;
// Spell checking is a nice feature, but it ends up completing a
// lot of types that we didn't strictly speaking need to complete.
// As a result, we spend a long time parsing and importing debug
// information.
m_compiler->getLangOpts().SpellChecking = false;
m_compiler->getLangOpts().SpellChecking = false;
lldb::ProcessSP process_sp;
if (exe_scope)
process_sp = exe_scope->CalculateProcess();
@ -209,7 +209,7 @@ ClangExpressionParser::ClangExpressionParser (ExecutionContextScope *exe_scope,
m_compiler->getLangOpts().ObjCRuntime.set(ObjCRuntime::MacOSX, VersionTuple(10, 7));
else
m_compiler->getLangOpts().ObjCRuntime.set(ObjCRuntime::FragileMacOSX, VersionTuple(10, 7));
if (process_sp->GetObjCLanguageRuntime()->HasNewLiteralsAndIndexing())
m_compiler->getLangOpts().DebuggerObjCLiteral = true;
}
@ -218,7 +218,7 @@ ClangExpressionParser::ClangExpressionParser (ExecutionContextScope *exe_scope,
m_compiler->getLangOpts().ThreadsafeStatics = false;
m_compiler->getLangOpts().AccessControl = false; // Debuggers get universal access
m_compiler->getLangOpts().DollarIdents = true; // $ indicates a persistent variable name
// Set CodeGen options
m_compiler->getCodeGenOpts().EmitDeclMetadata = true;
m_compiler->getCodeGenOpts().InstrumentFunctions = false;
@ -228,7 +228,7 @@ ClangExpressionParser::ClangExpressionParser (ExecutionContextScope *exe_scope,
m_compiler->getCodeGenOpts().setDebugInfo(CodeGenOptions::FullDebugInfo);
else
m_compiler->getCodeGenOpts().setDebugInfo(CodeGenOptions::NoDebugInfo);
// Disable some warnings.
m_compiler->getDiagnostics().setSeverityForGroup(
"unused-value", clang::diag::Severity::Ignored, SourceLocation());
@ -240,45 +240,45 @@ ClangExpressionParser::ClangExpressionParser (ExecutionContextScope *exe_scope,
// FIXME: We shouldn't need to do this, the target should be immutable once
// created. This complexity should be lifted elsewhere.
m_compiler->getTarget().adjust(m_compiler->getLangOpts());
// 4. Set up the diagnostic buffer for reporting errors
m_compiler->getDiagnostics().setClient(new clang::TextDiagnosticBuffer);
// 5. Set up the source management objects inside the compiler
clang::FileSystemOptions file_system_options;
m_file_manager.reset(new clang::FileManager(file_system_options));
if (!m_compiler->hasSourceManager())
m_compiler->createSourceManager(*m_file_manager.get());
m_compiler->createFileManager();
m_compiler->createPreprocessor(TU_Complete);
// 6. Most of this we get from the CompilerInstance, but we
// 6. Most of this we get from the CompilerInstance, but we
// also want to give the context an ExternalASTSource.
m_selector_table.reset(new SelectorTable());
m_builtin_context.reset(new Builtin::Context());
std::unique_ptr<clang::ASTContext> ast_context(new ASTContext(m_compiler->getLangOpts(),
m_compiler->getSourceManager(),
m_compiler->getPreprocessor().getIdentifierTable(),
*m_selector_table.get(),
*m_builtin_context.get()));
ast_context->InitBuiltinTypes(m_compiler->getTarget());
ClangExpressionDeclMap *decl_map = m_expr.DeclMap();
if (decl_map)
{
llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> ast_source(decl_map->CreateProxy());
decl_map->InstallASTContext(ast_context.get());
ast_context->setExternalSource(ast_source);
}
m_compiler->setASTContext(ast_context.release());
std::string module_name("$__lldb_module");
m_llvm_context.reset(new LLVMContext());
@ -297,9 +297,9 @@ unsigned
ClangExpressionParser::Parse (Stream &stream)
{
TextDiagnosticBuffer *diag_buf = static_cast<TextDiagnosticBuffer*>(m_compiler->getDiagnostics().getClient());
diag_buf->FlushDiagnostics (m_compiler->getDiagnostics());
const char *expr_text = m_expr.Text();
clang::SourceManager &SourceMgr = m_compiler->getSourceManager();
@ -307,7 +307,7 @@ ClangExpressionParser::Parse (Stream &stream)
if (m_compiler->getCodeGenOpts().getDebugInfo() == CodeGenOptions::FullDebugInfo)
{
std::string temp_source_path;
FileSpec tmpdir_file_spec;
if (Host::GetLLDBPath (ePathTypeLLDBTempSystemDir, tmpdir_file_spec))
{
@ -318,7 +318,7 @@ ClangExpressionParser::Parse (Stream &stream)
{
temp_source_path = "/tmp/expr.XXXXXX";
}
if (mktemp(&temp_source_path[0]))
{
lldb_private::File file (temp_source_path.c_str(),
@ -339,35 +339,35 @@ ClangExpressionParser::Parse (Stream &stream)
}
}
}
if (!created_main_file)
{
MemoryBuffer *memory_buffer = MemoryBuffer::getMemBufferCopy(expr_text, __FUNCTION__);
SourceMgr.setMainFileID(SourceMgr.createFileID(memory_buffer));
}
diag_buf->BeginSourceFile(m_compiler->getLangOpts(), &m_compiler->getPreprocessor());
ASTConsumer *ast_transformer = m_expr.ASTTransformer(m_code_generator.get());
if (ast_transformer)
ParseAST(m_compiler->getPreprocessor(), ast_transformer, m_compiler->getASTContext());
else
ParseAST(m_compiler->getPreprocessor(), m_code_generator.get(), m_compiler->getASTContext());
else
ParseAST(m_compiler->getPreprocessor(), m_code_generator.get(), m_compiler->getASTContext());
diag_buf->EndSourceFile();
TextDiagnosticBuffer::const_iterator diag_iterator;
int num_errors = 0;
for (diag_iterator = diag_buf->warn_begin();
diag_iterator != diag_buf->warn_end();
++diag_iterator)
stream.Printf("warning: %s\n", (*diag_iterator).second.c_str());
num_errors = 0;
for (diag_iterator = diag_buf->err_begin();
diag_iterator != diag_buf->err_end();
++diag_iterator)
@ -375,12 +375,12 @@ ClangExpressionParser::Parse (Stream &stream)
num_errors++;
stream.Printf("error: %s\n", (*diag_iterator).second.c_str());
}
for (diag_iterator = diag_buf->note_begin();
diag_iterator != diag_buf->note_end();
++diag_iterator)
stream.Printf("note: %s\n", (*diag_iterator).second.c_str());
if (!num_errors)
{
if (m_expr.DeclMap() && !m_expr.DeclMap()->ResolveUnknownTypes())
@ -389,7 +389,7 @@ ClangExpressionParser::Parse (Stream &stream)
num_errors++;
}
}
return num_errors;
}
@ -400,19 +400,19 @@ static bool FindFunctionInModule (ConstString &mangled_name,
for (llvm::Module::iterator fi = module->getFunctionList().begin(), fe = module->getFunctionList().end();
fi != fe;
++fi)
{
{
if (fi->getName().str().find(orig_name) != std::string::npos)
{
mangled_name.SetCString(fi->getName().str().c_str());
return true;
}
}
return false;
}
Error
ClangExpressionParser::PrepareForExecution (lldb::addr_t &func_addr,
ClangExpressionParser::PrepareForExecution (lldb::addr_t &func_addr,
lldb::addr_t &func_end,
std::shared_ptr<IRExecutionUnit> &execution_unit_sp,
ExecutionContext &exe_ctx,
@ -424,7 +424,7 @@ ClangExpressionParser::PrepareForExecution (lldb::addr_t &func_addr,
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())
@ -433,11 +433,11 @@ ClangExpressionParser::PrepareForExecution (lldb::addr_t &func_addr,
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();
@ -449,54 +449,54 @@ ClangExpressionParser::PrepareForExecution (lldb::addr_t &func_addr,
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)
@ -504,27 +504,27 @@ ClangExpressionParser::PrepareForExecution (lldb::addr_t &func_addr,
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();
@ -532,7 +532,7 @@ ClangExpressionParser::PrepareForExecution (lldb::addr_t &func_addr,
return err;
}
}
execution_unit_sp->GetRunnableInfo(err, func_addr, func_end);
}
}
@ -540,7 +540,7 @@ ClangExpressionParser::PrepareForExecution (lldb::addr_t &func_addr,
{
execution_unit_sp->GetRunnableInfo(err, func_addr, func_end);
}
return err;
}

View File

@ -8,11 +8,6 @@
//===----------------------------------------------------------------------===//
#include "lldb/Expression/ClangExpressionVariable.h"
// C Includes
// C++ Includes
// Other libraries and framework includes
// Project includes
#include "clang/AST/ASTContext.h"
#include "lldb/Core/ConstString.h"
#include "lldb/Core/DataExtractor.h"
@ -44,17 +39,17 @@ ClangExpressionVariable::ClangExpressionVariable (const lldb::ValueObjectSP &val
//----------------------------------------------------------------------
/// Return the variable's size in bytes
//----------------------------------------------------------------------
size_t
size_t
ClangExpressionVariable::GetByteSize ()
{
return m_frozen_sp->GetByteSize();
}
}
const ConstString &
ClangExpressionVariable::GetName ()
{
return m_frozen_sp->GetName();
}
}
lldb::ValueObjectSP
ClangExpressionVariable::GetValueObject()
@ -78,13 +73,13 @@ ClangASTType
ClangExpressionVariable::GetClangType()
{
return m_frozen_sp->GetClangType();
}
}
void
ClangExpressionVariable::SetClangType(const ClangASTType &clang_type)
{
m_frozen_sp->GetValue().SetClangType(clang_type);
}
}
TypeFromUser
@ -92,7 +87,7 @@ ClangExpressionVariable::GetTypeFromUser()
{
TypeFromUser tfu (m_frozen_sp->GetClangType());
return tfu;
}
}
uint8_t *
ClangExpressionVariable::GetValueBytes()
@ -130,7 +125,7 @@ ClangExpressionVariable::TransferAddress (bool force)
if (m_frozen_sp.get() == NULL)
return;
if (force || (m_frozen_sp->GetLiveAddress() == LLDB_INVALID_ADDRESS))
m_frozen_sp->SetLiveAddress(m_live_sp->GetLiveAddress());
}

View File

@ -7,13 +7,11 @@
//
//===----------------------------------------------------------------------===//
// C Includes
#include <stdio.h>
#if HAVE_SYS_TYPES_H
# include <sys/types.h>
#endif
// C++ Includes
#include <cstdlib>
#include <string>
#include <map>
@ -112,7 +110,7 @@ ClangUserExpression::ASTTransformer (clang::ASTConsumer *passthrough)
{
m_result_synthesizer.reset(new ASTResultSynthesizer(passthrough,
*m_target));
return m_result_synthesizer.get();
}
@ -123,16 +121,16 @@ ClangUserExpression::ScanContext(ExecutionContext &exe_ctx, Error &err)
if (log)
log->Printf("ClangUserExpression::ScanContext()");
m_target = exe_ctx.GetTargetPtr();
if (!(m_allow_cxx || m_allow_objc))
{
if (log)
log->Printf(" [CUE::SC] Settings inhibit C++ and Objective-C");
return;
}
StackFrame *frame = exe_ctx.GetFramePtr();
if (frame == NULL)
{
@ -140,19 +138,19 @@ ClangUserExpression::ScanContext(ExecutionContext &exe_ctx, Error &err)
log->Printf(" [CUE::SC] Null stack frame");
return;
}
SymbolContext sym_ctx = frame->GetSymbolContext(lldb::eSymbolContextFunction | lldb::eSymbolContextBlock);
if (!sym_ctx.function)
{
if (log)
log->Printf(" [CUE::SC] Null function");
return;
}
// Find the block that defines the function represented by "sym_ctx"
Block *function_block = sym_ctx.GetFunctionBlock();
if (!function_block)
{
if (log)
@ -168,7 +166,7 @@ ClangUserExpression::ScanContext(ExecutionContext &exe_ctx, Error &err)
log->Printf(" [CUE::SC] Null decl context");
return;
}
if (clang::CXXMethodDecl *method_decl = llvm::dyn_cast<clang::CXXMethodDecl>(decl_context))
{
if (m_allow_cxx && method_decl->isInstance())
@ -176,60 +174,60 @@ ClangUserExpression::ScanContext(ExecutionContext &exe_ctx, Error &err)
if (m_enforce_valid_object)
{
lldb::VariableListSP variable_list_sp (function_block->GetBlockVariableList (true));
const char *thisErrorString = "Stopped in a C++ method, but 'this' isn't available; pretending we are in a generic context";
if (!variable_list_sp)
{
err.SetErrorString(thisErrorString);
return;
}
lldb::VariableSP this_var_sp (variable_list_sp->FindVariable(ConstString("this")));
if (!this_var_sp ||
!this_var_sp->IsInScope(frame) ||
!this_var_sp->IsInScope(frame) ||
!this_var_sp->LocationIsValidForFrame (frame))
{
err.SetErrorString(thisErrorString);
return;
}
}
m_cplusplus = true;
m_needs_object_ptr = true;
}
}
else if (clang::ObjCMethodDecl *method_decl = llvm::dyn_cast<clang::ObjCMethodDecl>(decl_context))
{
{
if (m_allow_objc)
{
if (m_enforce_valid_object)
{
lldb::VariableListSP variable_list_sp (function_block->GetBlockVariableList (true));
const char *selfErrorString = "Stopped in an Objective-C method, but 'self' isn't available; pretending we are in a generic context";
if (!variable_list_sp)
{
err.SetErrorString(selfErrorString);
return;
}
lldb::VariableSP self_variable_sp = variable_list_sp->FindVariable(ConstString("self"));
if (!self_variable_sp ||
!self_variable_sp->IsInScope(frame) ||
if (!self_variable_sp ||
!self_variable_sp->IsInScope(frame) ||
!self_variable_sp->LocationIsValidForFrame (frame))
{
err.SetErrorString(selfErrorString);
return;
}
}
m_objectivec = true;
m_needs_object_ptr = true;
if (!method_decl->isInstanceMethod())
m_static_method = true;
}
@ -240,7 +238,7 @@ ClangUserExpression::ScanContext(ExecutionContext &exe_ctx, Error &err)
// object pointer. The best way to deal with getting to the ivars at present it by pretending
// that this is a method of a class in whatever runtime the debug info says the object pointer
// belongs to. Do that here.
ClangASTMetadata *metadata = ClangASTContext::GetMetadata (&decl_context->getParentASTContext(), function_decl);
if (metadata && metadata->HasObjectPtr())
{
@ -250,17 +248,17 @@ ClangUserExpression::ScanContext(ExecutionContext &exe_ctx, Error &err)
if (m_enforce_valid_object)
{
lldb::VariableListSP variable_list_sp (function_block->GetBlockVariableList (true));
const char *thisErrorString = "Stopped in a context claiming to capture a C++ object pointer, but 'this' isn't available; pretending we are in a generic context";
if (!variable_list_sp)
{
err.SetErrorString(thisErrorString);
return;
}
lldb::VariableSP this_var_sp (variable_list_sp->FindVariable(ConstString("this")));
if (!this_var_sp ||
!this_var_sp->IsInScope(frame) ||
!this_var_sp->LocationIsValidForFrame (frame))
@ -269,7 +267,7 @@ ClangUserExpression::ScanContext(ExecutionContext &exe_ctx, Error &err)
return;
}
}
m_cplusplus = true;
m_needs_object_ptr = true;
}
@ -278,17 +276,17 @@ ClangUserExpression::ScanContext(ExecutionContext &exe_ctx, Error &err)
if (m_enforce_valid_object)
{
lldb::VariableListSP variable_list_sp (function_block->GetBlockVariableList (true));
const char *selfErrorString = "Stopped in a context claiming to capture an Objective-C object pointer, but 'self' isn't available; pretending we are in a generic context";
if (!variable_list_sp)
{
err.SetErrorString(selfErrorString);
return;
}
lldb::VariableSP self_variable_sp = variable_list_sp->FindVariable(ConstString("self"));
if (!self_variable_sp ||
!self_variable_sp->IsInScope(frame) ||
!self_variable_sp->LocationIsValidForFrame (frame))
@ -296,23 +294,23 @@ ClangUserExpression::ScanContext(ExecutionContext &exe_ctx, Error &err)
err.SetErrorString(selfErrorString);
return;
}
Type *self_type = self_variable_sp->GetType();
if (!self_type)
{
err.SetErrorString(selfErrorString);
return;
}
ClangASTType self_clang_type = self_type->GetClangForwardType();
if (!self_clang_type)
{
err.SetErrorString(selfErrorString);
return;
}
if (self_clang_type.IsObjCClassType())
{
return;
@ -342,9 +340,9 @@ void
ClangUserExpression::InstallContext (ExecutionContext &exe_ctx)
{
m_process_wp = exe_ctx.GetProcessSP();
lldb::StackFrameSP frame_sp = exe_ctx.GetFrameSP();
if (frame_sp)
m_address = frame_sp->GetFrameCodeAddress();
}
@ -360,11 +358,11 @@ ClangUserExpression::LockAndCheckContext (ExecutionContext &exe_ctx,
if (process_sp != expected_process_sp)
return false;
process_sp = exe_ctx.GetProcessSP();
target_sp = exe_ctx.GetTargetSP();
frame_sp = exe_ctx.GetFrameSP();
if (m_address.IsValid())
{
if (!frame_sp)
@ -372,7 +370,7 @@ ClangUserExpression::LockAndCheckContext (ExecutionContext &exe_ctx,
else
return (0 == Address::CompareLoadAddress(m_address, frame_sp->GetFrameCodeAddress(), target_sp.get()));
}
return true;
}
@ -382,7 +380,7 @@ ClangUserExpression::MatchesContext (ExecutionContext &exe_ctx)
lldb::TargetSP target_sp;
lldb::ProcessSP process_sp;
lldb::StackFrameSP frame_sp;
return LockAndCheckContext(exe_ctx, target_sp, process_sp, frame_sp);
}
@ -397,7 +395,7 @@ ApplyObjcCastHack(std::string &expr)
#define OBJC_CAST_HACK_TO "(int)(long long)["
size_t from_offset;
while ((from_offset = expr.find(OBJC_CAST_HACK_FROM)) != expr.npos)
expr.replace(from_offset, sizeof(OBJC_CAST_HACK_FROM) - 1, OBJC_CAST_HACK_TO);
@ -426,84 +424,84 @@ ApplyObjcCastHack(std::string &expr)
//}
bool
ClangUserExpression::Parse (Stream &error_stream,
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);
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::unique_ptr<ExpressionSourceCode> source_code (ExpressionSourceCode::CreateWrapped(m_expr_prefix.c_str(), m_expr_text.c_str()));
lldb::LanguageType lang_type;
if (m_cplusplus)
lang_type = lldb::eLanguageTypeC_plus_plus;
else if(m_objectivec)
lang_type = lldb::eLanguageTypeObjC;
else
lang_type = lldb::eLanguageTypeC;
if (!source_code->GetText(m_transformed_text, lang_type, m_const_object, m_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());
m_expr_decl_map.reset(new ClangExpressionDeclMap(keep_result_in_memory, exe_ctx));
class OnExit
{
public:
typedef std::function <void (void)> Callback;
OnExit (Callback const &callback) :
m_callback(callback)
{
}
~OnExit ()
{
m_callback();
@ -511,52 +509,52 @@ ClangUserExpression::Parse (Stream &error_stream,
private:
Callback m_callback;
};
OnExit on_exit([this]() { m_expr_decl_map.reset(); });
if (!m_expr_decl_map->WillParse(exe_ctx, m_materializer_ap.get()))
{
error_stream.PutCString ("error: current process state is unsuitable for expression parsing\n");
m_expr_decl_map.reset(); // 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);
m_expr_decl_map.reset(); // 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());
@ -583,9 +581,9 @@ ClangUserExpression::Parse (Stream &error_stream,
// jit_sym_vendor->Dump(&strm);
// }
}
m_expr_decl_map.reset(); // 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)
@ -609,16 +607,16 @@ GetObjectPointer (lldb::StackFrameSP frame_sp,
Error &err)
{
err.Clear();
if (!frame_sp)
{
err.SetErrorStringWithFormat("Couldn't load '%s' because the context is incomplete", object_name.AsCString());
return LLDB_INVALID_ADDRESS;
}
lldb::VariableSP var_sp;
lldb::ValueObjectSP valobj_sp;
valobj_sp = frame_sp->GetValueForVariableExpressionPath(object_name.AsCString(),
lldb::eNoDynamicValues,
StackFrame::eExpressionPathOptionCheckPtrVsMember ||
@ -628,18 +626,18 @@ GetObjectPointer (lldb::StackFrameSP frame_sp,
StackFrame::eExpressionPathOptionsNoSyntheticArrayRange,
var_sp,
err);
if (!err.Success())
return LLDB_INVALID_ADDRESS;
lldb::addr_t ret = valobj_sp->GetValueAsUnsigned(LLDB_INVALID_ADDRESS);
if (ret == LLDB_INVALID_ADDRESS)
{
err.SetErrorStringWithFormat("Couldn't load '%s' because its value couldn't be evaluated", object_name.AsCString());
return LLDB_INVALID_ADDRESS;
}
return ret;
}
@ -653,22 +651,22 @@ ClangUserExpression::PrepareToExecuteJITExpression (Stream &error_stream,
lldb::TargetSP target;
lldb::ProcessSP process;
lldb::StackFrameSP frame;
if (!LockAndCheckContext(exe_ctx,
target,
process,
process,
frame))
{
error_stream.Printf("The context has changed before we could JIT the expression!\n");
return false;
}
if (m_jit_start_addr != LLDB_INVALID_ADDRESS || m_can_interpret)
{
{
if (m_needs_object_ptr)
{
ConstString object_name;
if (m_cplusplus)
{
object_name.SetCString("this");
@ -682,23 +680,23 @@ ClangUserExpression::PrepareToExecuteJITExpression (Stream &error_stream,
error_stream.Printf("Need object pointer but don't know the language\n");
return false;
}
Error object_ptr_error;
object_ptr = GetObjectPointer(frame, object_name, object_ptr_error);
if (!object_ptr_error.Success())
{
error_stream.Printf("warning: couldn't get required object pointer (substituting NULL): %s\n", object_ptr_error.AsCString());
object_ptr = 0;
}
if (m_objectivec)
{
ConstString cmd_name("_cmd");
cmd_ptr = GetObjectPointer(frame, cmd_name, object_ptr_error);
if (!object_ptr_error.Success())
{
error_stream.Printf("warning: couldn't get cmd pointer (substituting NULL): %s\n", object_ptr_error.AsCString());
@ -706,53 +704,53 @@ ClangUserExpression::PrepareToExecuteJITExpression (Stream &error_stream,
}
}
}
if (m_materialized_address == LLDB_INVALID_ADDRESS)
{
Error alloc_error;
IRMemoryMap::AllocationPolicy policy = m_can_interpret ? IRMemoryMap::eAllocationPolicyHostOnly : IRMemoryMap::eAllocationPolicyMirror;
m_materialized_address = m_execution_unit_sp->Malloc(m_materializer_ap->GetStructByteSize(),
m_materializer_ap->GetStructAlignment(),
lldb::ePermissionsReadable | lldb::ePermissionsWritable,
policy,
alloc_error);
if (!alloc_error.Success())
{
error_stream.Printf("Couldn't allocate space for materialized struct: %s\n", alloc_error.AsCString());
return false;
}
}
struct_address = m_materialized_address;
if (m_can_interpret && m_stack_frame_bottom == LLDB_INVALID_ADDRESS)
{
Error alloc_error;
const size_t stack_frame_size = 512 * 1024;
m_stack_frame_bottom = m_execution_unit_sp->Malloc(stack_frame_size,
8,
lldb::ePermissionsReadable | lldb::ePermissionsWritable,
IRMemoryMap::eAllocationPolicyHostOnly,
alloc_error);
m_stack_frame_top = m_stack_frame_bottom + stack_frame_size;
if (!alloc_error.Success())
{
error_stream.Printf("Couldn't allocate space for the stack frame: %s\n", alloc_error.AsCString());
return false;
}
}
Error materialize_error;
m_dematerializer_sp = m_materializer_ap->Materialize(frame, *m_execution_unit_sp, struct_address, materialize_error);
if (!materialize_error.Success())
{
error_stream.Printf("Couldn't materialize: %s\n", materialize_error.AsCString());
@ -770,18 +768,18 @@ ClangUserExpression::FinalizeJITExecution (Stream &error_stream,
lldb::addr_t function_stack_top)
{
Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
if (log)
log->Printf("-- [ClangUserExpression::FinalizeJITExecution] Dematerializing after execution --");
if (!m_dematerializer_sp)
{
error_stream.Printf ("Couldn't apply expression side effects : no dematerializer is present");
return false;
}
Error dematerialize_error;
m_dematerializer_sp->Dematerialize(dematerialize_error, result, function_stack_bottom, function_stack_top);
if (!dematerialize_error.Success())
@ -789,14 +787,14 @@ ClangUserExpression::FinalizeJITExecution (Stream &error_stream,
error_stream.Printf ("Couldn't apply expression side effects : %s\n", dematerialize_error.AsCString("unknown error"));
return false;
}
if (result)
result->TransferAddress();
m_dematerializer_sp.reset();
return true;
}
}
lldb::ExpressionResults
ClangUserExpression::Execute (Stream &error_stream,
@ -812,24 +810,24 @@ ClangUserExpression::Execute (Stream &error_stream,
if (m_jit_start_addr != LLDB_INVALID_ADDRESS || m_can_interpret)
{
lldb::addr_t struct_address = LLDB_INVALID_ADDRESS;
lldb::addr_t object_ptr = 0;
lldb::addr_t cmd_ptr = 0;
if (!PrepareToExecuteJITExpression (error_stream, exe_ctx, struct_address, object_ptr, cmd_ptr))
{
error_stream.Printf("Errored out in %s, couldn't PrepareToExecuteJITExpression", __FUNCTION__);
return lldb::eExpressionSetupError;
}
lldb::addr_t function_stack_bottom = LLDB_INVALID_ADDRESS;
lldb::addr_t function_stack_top = LLDB_INVALID_ADDRESS;
if (m_can_interpret)
{
{
llvm::Module *module = m_execution_unit_sp->GetModule();
llvm::Function *function = m_execution_unit_sp->GetFunction();
if (!module || !function)
{
error_stream.Printf("Supposed to interpret, but nothing is there");
@ -837,22 +835,22 @@ ClangUserExpression::Execute (Stream &error_stream,
}
Error interpreter_error;
llvm::SmallVector <lldb::addr_t, 3> args;
if (m_needs_object_ptr)
{
args.push_back(object_ptr);
if (m_objectivec)
args.push_back(cmd_ptr);
}
args.push_back(struct_address);
function_stack_bottom = m_stack_frame_bottom;
function_stack_top = m_stack_frame_top;
IRInterpreter::Interpret (*module,
*function,
args,
@ -860,7 +858,7 @@ ClangUserExpression::Execute (Stream &error_stream,
interpreter_error,
function_stack_bottom,
function_stack_top);
if (!interpreter_error.Success())
{
error_stream.Printf("Supposed to interpret, but failed: %s", interpreter_error.AsCString());
@ -874,54 +872,54 @@ ClangUserExpression::Execute (Stream &error_stream,
error_stream.Printf("ClangUserExpression::Execute called with no thread selected.");
return lldb::eExpressionSetupError;
}
Address wrapper_address (m_jit_start_addr);
llvm::SmallVector <lldb::addr_t, 3> args;
if (m_needs_object_ptr) {
args.push_back(object_ptr);
if (m_objectivec)
args.push_back(cmd_ptr);
}
args.push_back(struct_address);
lldb::ThreadPlanSP call_plan_sp(new ThreadPlanCallUserExpression (exe_ctx.GetThreadRef(),
wrapper_address,
lldb::ThreadPlanSP call_plan_sp(new ThreadPlanCallUserExpression (exe_ctx.GetThreadRef(),
wrapper_address,
args,
options,
shared_ptr_to_me));
if (!call_plan_sp || !call_plan_sp->ValidatePlan (&error_stream))
return lldb::eExpressionSetupError;
lldb::addr_t function_stack_pointer = static_cast<ThreadPlanCallFunction *>(call_plan_sp.get())->GetFunctionStackPointer();
function_stack_bottom = function_stack_pointer - Host::GetPageSize();
function_stack_top = function_stack_pointer;
if (log)
log->Printf("-- [ClangUserExpression::Execute] Execution of expression begins --");
if (exe_ctx.GetProcessPtr())
exe_ctx.GetProcessPtr()->SetRunningUserExpression(true);
lldb::ExpressionResults execution_result = exe_ctx.GetProcessRef().RunThreadPlan (exe_ctx,
call_plan_sp,
options,
error_stream);
if (exe_ctx.GetProcessPtr())
exe_ctx.GetProcessPtr()->SetRunningUserExpression(false);
if (log)
log->Printf("-- [ClangUserExpression::Execute] Execution of expression completed --");
if (execution_result == lldb::eExpressionInterrupted || execution_result == lldb::eExpressionHitBreakpoint)
{
const char *error_desc = NULL;
if (call_plan_sp)
{
lldb::StopInfoSP real_stop_info_sp = call_plan_sp->GetRealStopInfo();
@ -932,7 +930,7 @@ ClangUserExpression::Execute (Stream &error_stream,
error_stream.Printf ("Execution was interrupted, reason: %s.", error_desc);
else
error_stream.PutCString ("Execution was interrupted.");
if ((execution_result == lldb::eExpressionInterrupted && options.DoesUnwindOnError())
|| (execution_result == lldb::eExpressionHitBreakpoint && options.DoesIgnoreBreakpoints()))
error_stream.PutCString ("\nThe process has been returned to the state before expression evaluation.");
@ -955,7 +953,7 @@ ClangUserExpression::Execute (Stream &error_stream,
return execution_result;
}
}
if (FinalizeJITExecution (error_stream, exe_ctx, result, function_stack_bottom, function_stack_top))
{
return lldb::eExpressionCompleted;
@ -986,7 +984,7 @@ ClangUserExpression::Evaluate (ExecutionContext &exe_ctx,
const lldb::LanguageType language = options.GetLanguage();
const ResultType desired_type = options.DoesCoerceToId() ? ClangUserExpression::eResultTypeId : ClangUserExpression::eResultTypeAny;
lldb::ExpressionResults execution_results = lldb::eExpressionSetupError;
Process *process = exe_ctx.GetProcessPtr();
if (process == NULL || process->GetState() != lldb::eStateStopped)
@ -995,33 +993,33 @@ ClangUserExpression::Evaluate (ExecutionContext &exe_ctx,
{
if (log)
log->Printf("== [ClangUserExpression::Evaluate] Expression may not run, but is not constant ==");
error.SetErrorString ("expression needed to run but couldn't");
return execution_results;
}
}
if (process == NULL || !process->CanJIT())
execution_policy = eExecutionPolicyNever;
ClangUserExpressionSP user_expression_sp (new ClangUserExpression (expr_cstr, expr_prefix, language, desired_type));
StreamString error_stream;
if (log)
log->Printf("== [ClangUserExpression::Evaluate] Parsing expression %s ==", expr_cstr);
const bool keep_expression_in_memory = true;
const bool generate_debug_info = options.GetGenerateDebugInfo();
if (options.InvokeCancelCallback (lldb::eExpressionEvaluationParse))
{
error.SetErrorString ("expression interrupted by callback before parse");
result_valobj_sp = ValueObjectConstResult::Create (exe_ctx.GetBestExecutionContextScope(), error);
return lldb::eExpressionInterrupted;
}
if (!user_expression_sp->Parse (error_stream,
exe_ctx,
execution_policy,
@ -1042,7 +1040,7 @@ ClangUserExpression::Evaluate (ExecutionContext &exe_ctx,
{
if (log)
log->Printf("== [ClangUserExpression::Evaluate] Expression may not run, but is not constant ==");
if (error_stream.GetString().empty())
error.SetExpressionError (lldb::eExpressionSetupError, "expression needed to run but couldn't");
}
@ -1054,34 +1052,34 @@ ClangUserExpression::Evaluate (ExecutionContext &exe_ctx,
result_valobj_sp = ValueObjectConstResult::Create (exe_ctx.GetBestExecutionContextScope(), error);
return lldb::eExpressionInterrupted;
}
error_stream.GetString().clear();
if (log)
log->Printf("== [ClangUserExpression::Evaluate] Executing expression ==");
execution_results = user_expression_sp->Execute (error_stream,
execution_results = user_expression_sp->Execute (error_stream,
exe_ctx,
options,
user_expression_sp,
expr_result);
if (execution_results != lldb::eExpressionCompleted)
{
if (log)
log->Printf("== [ClangUserExpression::Evaluate] Execution completed abnormally ==");
if (error_stream.GetString().empty())
error.SetExpressionError (execution_results, "expression failed to execute, unknown error");
else
error.SetExpressionError (execution_results, error_stream.GetString().c_str());
}
else
else
{
if (expr_result)
{
result_valobj_sp = expr_result->GetValueObject();
if (log)
log->Printf("== [ClangUserExpression::Evaluate] Execution completed normally with result %s ==",
result_valobj_sp->GetValueAsCString());
@ -1090,19 +1088,19 @@ ClangUserExpression::Evaluate (ExecutionContext &exe_ctx,
{
if (log)
log->Printf("== [ClangUserExpression::Evaluate] Execution completed normally with no result ==");
error.SetError(ClangUserExpression::kNoResult, lldb::eErrorTypeGeneric);
}
}
}
}
if (options.InvokeCancelCallback(lldb::eExpressionEvaluationComplete))
{
error.SetExpressionError (lldb::eExpressionInterrupted, "expression interrupted by callback after complete");
return lldb::eExpressionInterrupted;
}
if (result_valobj_sp.get() == NULL)
{
result_valobj_sp = ValueObjectConstResult::Create (exe_ctx.GetBestExecutionContextScope(), error);

View File

@ -33,7 +33,7 @@ static char ID;
#define VALID_POINTER_CHECK_NAME "$__lldb_valid_pointer_check"
#define VALID_OBJC_OBJECT_CHECK_NAME "$__lldb_objc_object_check"
static const char g_valid_pointer_check_text[] =
static const char g_valid_pointer_check_text[] =
"extern \"C\" void\n"
"$__lldb_valid_pointer_check (unsigned char *$__lldb_arg_ptr)\n"
"{\n"
@ -56,22 +56,22 @@ DynamicCheckerFunctions::Install(Stream &error_stream,
VALID_POINTER_CHECK_NAME));
if (!m_valid_pointer_check->Install(error_stream, exe_ctx))
return false;
Process *process = exe_ctx.GetProcessPtr();
if (process)
{
ObjCLanguageRuntime *objc_language_runtime = process->GetObjCLanguageRuntime();
if (objc_language_runtime)
{
m_objc_object_check.reset(objc_language_runtime->CreateObjectChecker(VALID_OBJC_OBJECT_CHECK_NAME));
if (!m_objc_object_check->Install(error_stream, exe_ctx))
return false;
}
}
return true;
}
@ -94,7 +94,7 @@ DynamicCheckerFunctions::DoCheckersExplainStop (lldb::addr_t addr, Stream &messa
}
static std::string
static std::string
PrintValue(llvm::Value *V, bool truncate = false)
{
std::string s;
@ -128,10 +128,10 @@ PrintValue(llvm::Value *V, bool truncate = false)
///
/// - InspectInstruction [default: does nothing]
///
/// - InspectBasicBlock [default: iterates through the instructions in a
/// - InspectBasicBlock [default: iterates through the instructions in a
/// basic block calling InspectInstruction]
///
/// - InspectFunction [default: iterates through the basic blocks in a
/// - InspectFunction [default: iterates through the basic blocks in a
/// function calling InspectBasicBlock]
//----------------------------------------------------------------------
class Instrumenter {
@ -150,7 +150,7 @@ public:
m_intptr_ty(NULL)
{
}
virtual~Instrumenter ()
{
}
@ -168,7 +168,7 @@ public:
{
return InspectFunction(function);
}
//------------------------------------------------------------------
/// Instrument all the instructions found by Inspect()
///
@ -184,7 +184,7 @@ public:
if (!InstrumentInstruction(*ii))
return false;
}
return true;
}
protected:
@ -192,13 +192,13 @@ protected:
/// Add instrumentation to a single instruction
///
/// @param[in] inst
/// The instruction to be instrumented.
/// The instruction to be instrumented.
///
/// @return
/// True on success; false otherwise.
//------------------------------------------------------------------
virtual bool InstrumentInstruction(llvm::Instruction *inst) = 0;
//------------------------------------------------------------------
/// Register a single instruction to be instrumented
///
@ -209,7 +209,7 @@ protected:
{
m_to_instrument.push_back(&i);
}
//------------------------------------------------------------------
/// Determine whether a single instruction is interesting to
/// instrument, and, if so, call RegisterInstruction
@ -224,7 +224,7 @@ protected:
{
return true;
}
//------------------------------------------------------------------
/// Scan a basic block to see if any instructions are interesting
///
@ -243,15 +243,15 @@ protected:
if (!InspectInstruction(*ii))
return false;
}
return true;
}
//------------------------------------------------------------------
/// Scan a function to see if any instructions are interesting
///
/// @param[in] f
/// The function to be inspected.
/// The function to be inspected.
///
/// @return
/// False if there was an error scanning; true otherwise.
@ -265,12 +265,12 @@ protected:
if (!InspectBasicBlock(*bbi))
return false;
}
return true;
}
//------------------------------------------------------------------
/// Build a function pointer for a function with signature
/// Build a function pointer for a function with signature
/// void (*)(uint8_t*) with a given address
///
/// @param[in] start_address
@ -282,19 +282,19 @@ protected:
llvm::Value *BuildPointerValidatorFunc(lldb::addr_t start_address)
{
llvm::Type *param_array[1];
param_array[0] = const_cast<llvm::PointerType*>(GetI8PtrTy());
ArrayRef<llvm::Type*> params(param_array, 1);
FunctionType *fun_ty = FunctionType::get(llvm::Type::getVoidTy(m_module.getContext()), params, true);
PointerType *fun_ptr_ty = PointerType::getUnqual(fun_ty);
Constant *fun_addr_int = ConstantInt::get(GetIntptrTy(), start_address, false);
return ConstantExpr::getIntToPtr(fun_addr_int, fun_ptr_ty);
}
//------------------------------------------------------------------
/// Build a function pointer for a function with signature
/// Build a function pointer for a function with signature
/// void (*)(uint8_t*, uint8_t*) with a given address
///
/// @param[in] start_address
@ -306,41 +306,41 @@ protected:
llvm::Value *BuildObjectCheckerFunc(lldb::addr_t start_address)
{
llvm::Type *param_array[2];
param_array[0] = const_cast<llvm::PointerType*>(GetI8PtrTy());
param_array[1] = const_cast<llvm::PointerType*>(GetI8PtrTy());
ArrayRef<llvm::Type*> params(param_array, 2);
FunctionType *fun_ty = FunctionType::get(llvm::Type::getVoidTy(m_module.getContext()), params, true);
PointerType *fun_ptr_ty = PointerType::getUnqual(fun_ty);
Constant *fun_addr_int = ConstantInt::get(GetIntptrTy(), start_address, false);
return ConstantExpr::getIntToPtr(fun_addr_int, fun_ptr_ty);
}
PointerType *GetI8PtrTy()
{
if (!m_i8ptr_ty)
m_i8ptr_ty = llvm::Type::getInt8PtrTy(m_module.getContext());
return m_i8ptr_ty;
}
IntegerType *GetIntptrTy()
{
if (!m_intptr_ty)
{
llvm::DataLayout data_layout(&m_module);
m_intptr_ty = llvm::Type::getIntNTy(m_module.getContext(), data_layout.getPointerSizeInBits());
}
return m_intptr_ty;
}
typedef std::vector <llvm::Instruction *> InstVector;
typedef InstVector::iterator InstIterator;
InstVector m_to_instrument; ///< List of instructions the inspector found
llvm::Module &m_module; ///< The module which is being instrumented
DynamicCheckerFunctions &m_checker_functions; ///< The dynamic checker functions for the process
@ -358,7 +358,7 @@ public:
m_valid_pointer_check_func(NULL)
{
}
virtual ~ValidPointerChecker ()
{
}
@ -368,53 +368,53 @@ private:
Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
if (log)
log->Printf("Instrumenting load/store instruction: %s\n",
log->Printf("Instrumenting load/store instruction: %s\n",
PrintValue(inst).c_str());
if (!m_valid_pointer_check_func)
m_valid_pointer_check_func = BuildPointerValidatorFunc(m_checker_functions.m_valid_pointer_check->StartAddress());
llvm::Value *dereferenced_ptr = NULL;
if (llvm::LoadInst *li = dyn_cast<llvm::LoadInst> (inst))
dereferenced_ptr = li->getPointerOperand();
else if (llvm::StoreInst *si = dyn_cast<llvm::StoreInst> (inst))
dereferenced_ptr = si->getPointerOperand();
else
return false;
// Insert an instruction to cast the loaded value to int8_t*
BitCastInst *bit_cast = new BitCastInst(dereferenced_ptr,
GetI8PtrTy(),
"",
inst);
// Insert an instruction to call the helper with the result
llvm::Value *arg_array[1];
arg_array[0] = bit_cast;
llvm::ArrayRef<llvm::Value *> args(arg_array, 1);
CallInst::Create(m_valid_pointer_check_func,
CallInst::Create(m_valid_pointer_check_func,
args,
"",
inst);
return true;
}
bool InspectInstruction(llvm::Instruction &i)
{
if (dyn_cast<llvm::LoadInst> (&i) ||
dyn_cast<llvm::StoreInst> (&i))
RegisterInstruction(i);
return true;
}
llvm::Value *m_valid_pointer_check_func;
};
@ -496,7 +496,7 @@ private:
ArrayRef<llvm::Value*> args(arg_array, 2);
CallInst::Create(m_objc_object_check_func,
CallInst::Create(m_objc_object_check_func,
args,
"",
inst);
@ -612,52 +612,52 @@ bool
IRDynamicChecks::runOnModule(llvm::Module &M)
{
Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
llvm::Function* function = M.getFunction(StringRef(m_func_name.c_str()));
if (!function)
{
if (log)
log->Printf("Couldn't find %s() in the module", m_func_name.c_str());
return false;
}
if (m_checker_functions.m_valid_pointer_check.get())
{
ValidPointerChecker vpc(M, m_checker_functions);
if (!vpc.Inspect(*function))
return false;
if (!vpc.Instrument())
return false;
}
if (m_checker_functions.m_objc_object_check.get())
{
ObjcObjectChecker ooc(M, m_checker_functions);
if (!ooc.Inspect(*function))
return false;
if (!ooc.Instrument())
return false;
}
if (log && log->GetVerbose())
{
std::string s;
raw_string_ostream oss(s);
M.print(oss, NULL);
oss.flush();
log->Printf ("Module after dynamic checks: \n%s", s.c_str());
}
return true;
return true;
}
void

View File

@ -7,14 +7,10 @@
//
//===----------------------------------------------------------------------===//
// C Includes
// C++ Includes
// Other libraries and framework includes
#include "llvm/ExecutionEngine/ExecutionEngine.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/SourceMgr.h"
// Project includes
#include "lldb/Core/DataBufferHeap.h"
#include "lldb/Core/DataExtractor.h"
#include "lldb/Core/Disassembler.h"
@ -48,39 +44,39 @@ lldb::addr_t
IRExecutionUnit::WriteNow (const uint8_t *bytes,
size_t size,
Error &error)
{
{
lldb::addr_t allocation_process_addr = Malloc (size,
8,
lldb::ePermissionsWritable | lldb::ePermissionsReadable,
eAllocationPolicyMirror,
error);
if (!error.Success())
return LLDB_INVALID_ADDRESS;
WriteMemory(allocation_process_addr, bytes, size, error);
if (!error.Success())
{
Error err;
Free (allocation_process_addr, err);
return LLDB_INVALID_ADDRESS;
}
if (Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS))
{
DataBufferHeap my_buffer(size, 0);
Error err;
ReadMemory(my_buffer.GetBytes(), allocation_process_addr, size, err);
if (err.Success())
{
DataExtractor my_extractor(my_buffer.GetBytes(), my_buffer.GetByteSize(), lldb::eByteOrderBig, 8);
my_extractor.PutToLog(log, 0, my_buffer.GetByteSize(), allocation_process_addr, 16, DataExtractor::TypeUInt8);
}
}
return allocation_process_addr;
}
@ -89,9 +85,9 @@ IRExecutionUnit::FreeNow (lldb::addr_t allocation)
{
if (allocation == LLDB_INVALID_ADDRESS)
return;
Error err;
Free(allocation, err);
}
@ -100,16 +96,16 @@ IRExecutionUnit::DisassembleFunction (Stream &stream,
lldb::ProcessSP &process_wp)
{
Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
ExecutionContext exe_ctx(process_wp);
Error ret;
ret.Clear();
lldb::addr_t func_local_addr = LLDB_INVALID_ADDRESS;
lldb::addr_t func_remote_addr = LLDB_INVALID_ADDRESS;
for (JittedFunction &function : m_jitted_functions)
{
if (strstr(function.m_name.c_str(), m_name.AsCString()))
@ -118,31 +114,31 @@ IRExecutionUnit::DisassembleFunction (Stream &stream,
func_remote_addr = function.m_remote_addr;
}
}
if (func_local_addr == LLDB_INVALID_ADDRESS)
{
ret.SetErrorToGenericError();
ret.SetErrorStringWithFormat("Couldn't find function %s for disassembly", m_name.AsCString());
return ret;
}
if (log)
log->Printf("Found function, has local address 0x%" PRIx64 " and remote address 0x%" PRIx64, (uint64_t)func_local_addr, (uint64_t)func_remote_addr);
std::pair <lldb::addr_t, lldb::addr_t> func_range;
func_range = GetRemoteRangeForLocal(func_local_addr);
if (func_range.first == 0 && func_range.second == 0)
{
ret.SetErrorToGenericError();
ret.SetErrorStringWithFormat("Couldn't find code range for function %s", m_name.AsCString());
return ret;
}
if (log)
log->Printf("Function's code range is [0x%" PRIx64 "+0x%" PRIx64 "]", func_range.first, func_range.second);
Target *target = exe_ctx.GetTargetPtr();
if (!target)
{
@ -150,44 +146,44 @@ IRExecutionUnit::DisassembleFunction (Stream &stream,
ret.SetErrorString("Couldn't find the target");
return ret;
}
lldb::DataBufferSP buffer_sp(new DataBufferHeap(func_range.second, 0));
Process *process = exe_ctx.GetProcessPtr();
Error err;
process->ReadMemory(func_remote_addr, buffer_sp->GetBytes(), buffer_sp->GetByteSize(), err);
if (!err.Success())
{
ret.SetErrorToGenericError();
ret.SetErrorStringWithFormat("Couldn't read from process: %s", err.AsCString("unknown error"));
return ret;
}
ArchSpec arch(target->GetArchitecture());
const char *plugin_name = NULL;
const char *flavor_string = NULL;
lldb::DisassemblerSP disassembler_sp = Disassembler::FindPlugin(arch, flavor_string, plugin_name);
if (!disassembler_sp)
{
ret.SetErrorToGenericError();
ret.SetErrorStringWithFormat("Unable to find disassembler plug-in for %s architecture.", arch.GetArchitectureName());
return ret;
}
if (!process)
{
ret.SetErrorToGenericError();
ret.SetErrorString("Couldn't find the process");
return ret;
}
DataExtractor extractor(buffer_sp,
process->GetByteOrder(),
target->GetArchitecture().GetAddressByteSize());
if (log)
{
log->Printf("Function data has contents:");
@ -198,12 +194,12 @@ IRExecutionUnit::DisassembleFunction (Stream &stream,
16,
DataExtractor::TypeUInt8);
}
disassembler_sp->DecodeInstructions (Address (func_remote_addr), extractor, 0, UINT32_MAX, false, false);
InstructionList &instruction_list = disassembler_sp->GetInstructionList();
const uint32_t max_opcode_byte_size = instruction_list.GetMaxOpcocdeByteSize();
for (size_t instruction_index = 0, num_instructions = instruction_list.GetSize();
instruction_index < num_instructions;
++instruction_index)
@ -225,7 +221,7 @@ IRExecutionUnit::DisassembleFunction (Stream &stream,
static void ReportInlineAsmError(const llvm::SMDiagnostic &diagnostic, void *Context, unsigned LocCookie)
{
Error *err = static_cast<Error*>(Context);
if (err && err->Success())
{
err->SetErrorToGenericError();
@ -239,52 +235,52 @@ IRExecutionUnit::GetRunnableInfo(Error &error,
lldb::addr_t &func_end)
{
lldb::ProcessSP process_sp(GetProcessWP().lock());
static Mutex s_runnable_info_mutex(Mutex::Type::eMutexTypeRecursive);
func_addr = LLDB_INVALID_ADDRESS;
func_end = LLDB_INVALID_ADDRESS;
if (!process_sp)
{
error.SetErrorToGenericError();
error.SetErrorString("Couldn't write the JIT compiled code into the process because the process is invalid");
return;
}
if (m_did_jit)
{
func_addr = m_function_load_addr;
func_end = m_function_end_load_addr;
return;
};
Mutex::Locker runnable_info_mutex_locker(s_runnable_info_mutex);
m_did_jit = true;
Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
std::string error_string;
if (log)
{
std::string s;
llvm::raw_string_ostream oss(s);
m_module->print(oss, NULL);
oss.flush();
log->Printf ("Module being sent to JIT: \n%s", s.c_str());
}
llvm::Triple triple(m_module->getTargetTriple());
llvm::Function *function = m_module->getFunction (m_name.AsCString());
llvm::Reloc::Model relocModel;
llvm::CodeModel::Model codeModel;
if (triple.isOSBinFormatELF())
{
relocModel = llvm::Reloc::Static;
@ -296,11 +292,11 @@ IRExecutionUnit::GetRunnableInfo(Error &error,
relocModel = llvm::Reloc::PIC_;
codeModel = llvm::CodeModel::Small;
}
m_module_ap->getContext().setInlineAsmDiagnosticHandler(ReportInlineAsmError, &error);
llvm::EngineBuilder builder(m_module_ap.get());
builder.setEngineKind(llvm::EngineKind::JIT)
.setErrorStr(&error_string)
.setRelocationModel(relocModel)
@ -309,21 +305,21 @@ IRExecutionUnit::GetRunnableInfo(Error &error,
.setAllocateGVsWithCode(true)
.setCodeModel(codeModel)
.setUseMCJIT(true);
llvm::StringRef mArch;
llvm::StringRef mCPU;
llvm::SmallVector<std::string, 0> mAttrs;
for (std::string &feature : m_cpu_features)
mAttrs.push_back(feature);
llvm::TargetMachine *target_machine = builder.selectTarget(triple,
mArch,
mCPU,
mAttrs);
m_execution_engine_ap.reset(builder.create(target_machine));
if (!m_execution_engine_ap.get())
{
error.SetErrorToGenericError();
@ -334,46 +330,46 @@ IRExecutionUnit::GetRunnableInfo(Error &error,
{
m_module_ap.release(); // ownership was transferred
}
// Make sure we see all sections, including ones that don't have relocations...
m_execution_engine_ap->setProcessAllSections(true);
m_execution_engine_ap->DisableLazyCompilation();
// We don't actually need the function pointer here, this just forces it to get resolved.
void *fun_ptr = m_execution_engine_ap->getPointerToFunction(function);
if (!error.Success())
{
// We got an error through our callback!
return;
}
if (!function)
{
error.SetErrorToGenericError();
error.SetErrorStringWithFormat("Couldn't find '%s' in the JITted module", m_name.AsCString());
return;
}
if (!fun_ptr)
{
error.SetErrorToGenericError();
error.SetErrorStringWithFormat("'%s' was in the JITted module but wasn't lowered", m_name.AsCString());
return;
}
m_jitted_functions.push_back (JittedFunction(m_name.AsCString(), (lldb::addr_t)fun_ptr));
CommitAllocations(process_sp);
ReportAllocations(*m_execution_engine_ap);
WriteData(process_sp);
for (JittedFunction &jitted_function : m_jitted_functions)
{
jitted_function.m_remote_addr = GetRemoteAddressForLocal (jitted_function.m_local_addr);
if (!jitted_function.m_name.compare(m_name.AsCString()))
{
AddrRange func_range = GetRemoteRangeForLocal(jitted_function.m_local_addr);
@ -381,15 +377,15 @@ IRExecutionUnit::GetRunnableInfo(Error &error,
m_function_load_addr = jitted_function.m_remote_addr;
}
}
if (log)
{
log->Printf("Code can be run in the target.");
StreamString disassembly_stream;
Error err = DisassembleFunction(disassembly_stream, process_sp);
if (!err.Success())
{
log->Printf("Couldn't disassemble function : %s", err.AsCString("unknown error"));
@ -398,18 +394,18 @@ IRExecutionUnit::GetRunnableInfo(Error &error,
{
log->Printf("Function disassembly:\n%s", disassembly_stream.GetData());
}
log->Printf("Sections: ");
for (AllocationRecord &record : m_records)
{
if (record.m_process_address != LLDB_INVALID_ADDRESS)
{
record.dump(log);
DataBufferHeap my_buffer(record.m_size, 0);
Error err;
ReadMemory(my_buffer.GetBytes(), record.m_process_address, record.m_size, err);
if (err.Success())
{
DataExtractor my_extractor(my_buffer.GetBytes(), my_buffer.GetByteSize(), lldb::eByteOrderBig, 8);
@ -418,10 +414,10 @@ IRExecutionUnit::GetRunnableInfo(Error &error,
}
}
}
func_addr = m_function_load_addr;
func_end = m_function_end_load_addr;
return;
}
@ -508,7 +504,7 @@ IRExecutionUnit::GetSectionTypeFromSectionName (const llvm::StringRef &name, IRE
case AllocationKind::Global:sect_type = lldb::eSectionTypeData; break;
case AllocationKind::Bytes: sect_type = lldb::eSectionTypeOther; break;
}
if (!name.empty())
{
if (name.equals("__text") || name.equals(".text"))
@ -527,46 +523,46 @@ IRExecutionUnit::GetSectionTypeFromSectionName (const llvm::StringRef &name, IRE
else if (dwarf_name.equals("aranges"))
sect_type = lldb::eSectionTypeDWARFDebugAranges;
break;
case 'f':
if (dwarf_name.equals("frame"))
sect_type = lldb::eSectionTypeDWARFDebugFrame;
break;
case 'i':
if (dwarf_name.equals("info"))
sect_type = lldb::eSectionTypeDWARFDebugInfo;
break;
case 'l':
if (dwarf_name.equals("line"))
sect_type = lldb::eSectionTypeDWARFDebugLine;
else if (dwarf_name.equals("loc"))
sect_type = lldb::eSectionTypeDWARFDebugLoc;
break;
case 'm':
if (dwarf_name.equals("macinfo"))
sect_type = lldb::eSectionTypeDWARFDebugMacInfo;
break;
case 'p':
if (dwarf_name.equals("pubnames"))
sect_type = lldb::eSectionTypeDWARFDebugPubNames;
else if (dwarf_name.equals("pubtypes"))
sect_type = lldb::eSectionTypeDWARFDebugPubTypes;
break;
case 's':
if (dwarf_name.equals("str"))
sect_type = lldb::eSectionTypeDWARFDebugStr;
break;
case 'r':
if (dwarf_name.equals("ranges"))
sect_type = lldb::eSectionTypeDWARFDebugRanges;
break;
default:
break;
}
@ -611,7 +607,7 @@ IRExecutionUnit::MemoryManager::allocateSpace(intptr_t Size, unsigned Alignment)
Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
uint8_t *return_value = m_default_mm_ap->allocateSpace(Size, Alignment);
m_parent.m_records.push_back(AllocationRecord((uintptr_t)return_value,
lldb::ePermissionsReadable | lldb::ePermissionsWritable,
GetSectionTypeFromSectionName (llvm::StringRef(), AllocationKind::Bytes),
@ -619,13 +615,13 @@ IRExecutionUnit::MemoryManager::allocateSpace(intptr_t Size, unsigned Alignment)
Alignment,
eSectionIDInvalid,
NULL));
if (log)
{
log->Printf("IRExecutionUnit::allocateSpace(Size=%" PRIu64 ", Alignment=%u) = %p",
(uint64_t)Size, Alignment, return_value);
}
return return_value;
}
@ -636,9 +632,9 @@ IRExecutionUnit::MemoryManager::allocateCodeSection(uintptr_t Size,
llvm::StringRef SectionName)
{
Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
uint8_t *return_value = m_default_mm_ap->allocateCodeSection(Size, Alignment, SectionID, SectionName);
m_parent.m_records.push_back(AllocationRecord((uintptr_t)return_value,
lldb::ePermissionsReadable | lldb::ePermissionsExecutable,
GetSectionTypeFromSectionName (SectionName, AllocationKind::Code),
@ -646,13 +642,13 @@ IRExecutionUnit::MemoryManager::allocateCodeSection(uintptr_t Size,
Alignment,
SectionID,
SectionName.str().c_str()));
if (log)
{
log->Printf("IRExecutionUnit::allocateCodeSection(Size=0x%" PRIx64 ", Alignment=%u, SectionID=%u) = %p",
(uint64_t)Size, Alignment, SectionID, return_value);
}
return return_value;
}
@ -666,7 +662,7 @@ IRExecutionUnit::MemoryManager::allocateDataSection(uintptr_t Size,
Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
uint8_t *return_value = m_default_mm_ap->allocateDataSection(Size, Alignment, SectionID, SectionName, IsReadOnly);
m_parent.m_records.push_back(AllocationRecord((uintptr_t)return_value,
lldb::ePermissionsReadable | (IsReadOnly ? 0 : lldb::ePermissionsWritable),
GetSectionTypeFromSectionName (SectionName, AllocationKind::Data),
@ -679,8 +675,8 @@ IRExecutionUnit::MemoryManager::allocateDataSection(uintptr_t Size,
log->Printf("IRExecutionUnit::allocateDataSection(Size=0x%" PRIx64 ", Alignment=%u, SectionID=%u) = %p",
(uint64_t)Size, Alignment, SectionID, return_value);
}
return return_value;
return return_value;
}
uint8_t *
@ -690,7 +686,7 @@ IRExecutionUnit::MemoryManager::allocateGlobal(uintptr_t Size,
Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
uint8_t *return_value = m_default_mm_ap->allocateGlobal(Size, Alignment);
m_parent.m_records.push_back(AllocationRecord((uintptr_t)return_value,
lldb::ePermissionsReadable | lldb::ePermissionsWritable,
GetSectionTypeFromSectionName (llvm::StringRef(), AllocationKind::Global),
@ -698,13 +694,13 @@ IRExecutionUnit::MemoryManager::allocateGlobal(uintptr_t Size,
Alignment,
eSectionIDInvalid,
NULL));
if (log)
{
log->Printf("IRExecutionUnit::allocateGlobal(Size=0x%" PRIx64 ", Alignment=%u) = %p",
(uint64_t)Size, Alignment, return_value);
}
return return_value;
}
@ -726,9 +722,9 @@ IRExecutionUnit::GetRemoteAddressForLocal (lldb::addr_t local_address)
{
if (record.m_process_address == LLDB_INVALID_ADDRESS)
return LLDB_INVALID_ADDRESS;
lldb::addr_t ret = record.m_process_address + (local_address - record.m_host_address);
if (log)
{
log->Printf("IRExecutionUnit::GetRemoteAddressForLocal() found 0x%" PRIx64 " in [0x%" PRIx64 "..0x%" PRIx64 "], and returned 0x%" PRIx64 " from [0x%" PRIx64 "..0x%" PRIx64 "].",
@ -739,7 +735,7 @@ IRExecutionUnit::GetRemoteAddressForLocal (lldb::addr_t local_address)
record.m_process_address,
record.m_process_address + record.m_size);
}
return ret;
}
}
@ -757,11 +753,11 @@ IRExecutionUnit::GetRemoteRangeForLocal (lldb::addr_t local_address)
{
if (record.m_process_address == LLDB_INVALID_ADDRESS)
return AddrRange(0, 0);
return AddrRange(record.m_process_address, record.m_size);
}
}
return AddrRange (0, 0);
}
@ -769,14 +765,14 @@ bool
IRExecutionUnit::CommitAllocations (lldb::ProcessSP &process_sp)
{
bool ret = true;
lldb_private::Error err;
for (AllocationRecord &record : m_records)
{
if (record.m_process_address != LLDB_INVALID_ADDRESS)
continue;
switch (record.m_sect_type)
{
case lldb::eSectionTypeInvalid:
@ -805,14 +801,14 @@ IRExecutionUnit::CommitAllocations (lldb::ProcessSP &process_sp)
err);
break;
}
if (!err.Success())
{
ret = false;
break;
}
}
if (!ret)
{
for (AllocationRecord &record : m_records)
@ -824,7 +820,7 @@ IRExecutionUnit::CommitAllocations (lldb::ProcessSP &process_sp)
}
}
}
return ret;
}
@ -835,13 +831,13 @@ IRExecutionUnit::ReportAllocations (llvm::ExecutionEngine &engine)
{
if (record.m_process_address == LLDB_INVALID_ADDRESS)
continue;
if (record.m_section_id == eSectionIDInvalid)
continue;
engine.mapSectionAddress((void*)record.m_host_address, record.m_process_address);
}
// Trigger re-application of relocations.
engine.finalizeObject();
}
@ -863,12 +859,12 @@ IRExecutionUnit::WriteData (lldb::ProcessSP &process_sp)
return wrote_something;
}
void
void
IRExecutionUnit::AllocationRecord::dump (Log *log)
{
if (!log)
return;
log->Printf("[0x%llx+0x%llx]->0x%llx (alignment %d, section ID %d)",
(unsigned long long)m_host_address,
(unsigned long long)m_size,

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -28,11 +28,11 @@ IRMemoryMap::IRMemoryMap (lldb::TargetSP target_sp) :
IRMemoryMap::~IRMemoryMap ()
{
lldb::ProcessSP process_sp = m_process_wp.lock();
if (process_sp)
{
AllocationMap::iterator iter;
Error err;
while ((iter = m_allocations.begin()) != m_allocations.end())
@ -51,25 +51,25 @@ IRMemoryMap::FindSpace (size_t size)
{
lldb::TargetSP target_sp = m_target_wp.lock();
lldb::ProcessSP process_sp = m_process_wp.lock();
lldb::addr_t ret = LLDB_INVALID_ADDRESS;
if (process_sp && process_sp->CanJIT() && process_sp->IsAlive())
{
Error alloc_error;
ret = process_sp->AllocateMemory(size, lldb::ePermissionsReadable | lldb::ePermissionsWritable, alloc_error);
if (!alloc_error.Success())
return LLDB_INVALID_ADDRESS;
else
return ret;
}
for (int iterations = 0; iterations < 16; ++iterations)
{
lldb::addr_t candidate = LLDB_INVALID_ADDRESS;
switch (target_sp->GetArchitecture().GetAddressByteSize())
{
case 4:
@ -90,15 +90,15 @@ IRMemoryMap::FindSpace (size_t size)
break;
}
}
if (IntersectsAllocation(candidate, size))
continue;
ret = candidate;
return ret;
}
return ret;
}
@ -107,9 +107,9 @@ IRMemoryMap::FindAllocation (lldb::addr_t addr, size_t size)
{
if (addr == LLDB_INVALID_ADDRESS)
return m_allocations.end();
AllocationMap::iterator iter = m_allocations.lower_bound (addr);
if (iter == m_allocations.end() ||
iter->first > addr)
{
@ -117,10 +117,10 @@ IRMemoryMap::FindAllocation (lldb::addr_t addr, size_t size)
return m_allocations.end();
iter--;
}
if (iter->first <= addr && iter->first + iter->second.m_size >= addr + size)
return iter;
return m_allocations.end();
}
@ -129,9 +129,9 @@ IRMemoryMap::IntersectsAllocation (lldb::addr_t addr, size_t size) const
{
if (addr == LLDB_INVALID_ADDRESS)
return false;
AllocationMap::const_iterator iter = m_allocations.lower_bound (addr);
// Since we only know that the returned interval begins at a location greater than or
// equal to where the given interval begins, it's possible that the given interval
// intersects either the returned interval or the previous interval. Thus, we need to
@ -171,15 +171,15 @@ lldb::ByteOrder
IRMemoryMap::GetByteOrder()
{
lldb::ProcessSP process_sp = m_process_wp.lock();
if (process_sp)
return process_sp->GetByteOrder();
lldb::TargetSP target_sp = m_target_wp.lock();
if (target_sp)
return target_sp->GetArchitecture().GetByteOrder();
return lldb::eByteOrderInvalid;
}
@ -187,15 +187,15 @@ uint32_t
IRMemoryMap::GetAddressByteSize()
{
lldb::ProcessSP process_sp = m_process_wp.lock();
if (process_sp)
return process_sp->GetAddressByteSize();
lldb::TargetSP target_sp = m_target_wp.lock();
if (target_sp)
return target_sp->GetArchitecture().GetAddressByteSize();
return UINT32_MAX;
}
@ -203,15 +203,15 @@ ExecutionContextScope *
IRMemoryMap::GetBestExecutionContextScope() const
{
lldb::ProcessSP process_sp = m_process_wp.lock();
if (process_sp)
return process_sp.get();
lldb::TargetSP target_sp = m_target_wp.lock();
if (target_sp)
return target_sp.get();
return NULL;
}
@ -251,7 +251,7 @@ IRMemoryMap::Malloc (size_t size, uint8_t alignment, uint32_t permissions, Alloc
{
lldb_private::Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
error.Clear();
lldb::ProcessSP process_sp;
lldb::addr_t allocation_address = LLDB_INVALID_ADDRESS;
lldb::addr_t aligned_address = LLDB_INVALID_ADDRESS;
@ -263,7 +263,7 @@ IRMemoryMap::Malloc (size_t size, uint8_t alignment, uint32_t permissions, Alloc
allocation_size = alignment;
else
allocation_size = (size & alignment_mask) ? ((size + alignment) & (~alignment_mask)) : size;
switch (policy)
{
default:
@ -328,8 +328,8 @@ IRMemoryMap::Malloc (size_t size, uint8_t alignment, uint32_t permissions, Alloc
}
break;
}
lldb::addr_t mask = alignment - 1;
aligned_address = (allocation_address + mask) & (~mask);
@ -339,11 +339,11 @@ IRMemoryMap::Malloc (size_t size, uint8_t alignment, uint32_t permissions, Alloc
permissions,
alignment,
policy);
if (log)
{
const char * policy_string;
switch (policy)
{
default:
@ -359,7 +359,7 @@ IRMemoryMap::Malloc (size_t size, uint8_t alignment, uint32_t permissions, Alloc
policy_string = "eAllocationPolicyMirror";
break;
}
log->Printf("IRMemoryMap::Malloc (%" PRIu64 ", 0x%" PRIx64 ", 0x%" PRIx64 ", %s) -> 0x%" PRIx64,
(uint64_t)allocation_size,
(uint64_t)alignment,
@ -367,7 +367,7 @@ IRMemoryMap::Malloc (size_t size, uint8_t alignment, uint32_t permissions, Alloc
policy_string,
aligned_address);
}
return aligned_address;
}
@ -375,16 +375,16 @@ void
IRMemoryMap::Leak (lldb::addr_t process_address, Error &error)
{
error.Clear();
AllocationMap::iterator iter = m_allocations.find(process_address);
if (iter == m_allocations.end())
{
error.SetErrorToGenericError();
error.SetErrorString("Couldn't leak: allocation doesn't exist");
return;
}
Allocation &allocation = iter->second;
allocation.m_leak = true;
@ -394,18 +394,18 @@ void
IRMemoryMap::Free (lldb::addr_t process_address, Error &error)
{
error.Clear();
AllocationMap::iterator iter = m_allocations.find(process_address);
if (iter == m_allocations.end())
{
error.SetErrorToGenericError();
error.SetErrorString("Couldn't free: allocation doesn't exist");
return;
}
Allocation &allocation = iter->second;
switch (allocation.m_policy)
{
default:
@ -417,7 +417,7 @@ IRMemoryMap::Free (lldb::addr_t process_address, Error &error)
if (process_sp->CanJIT() && process_sp->IsAlive())
process_sp->DeallocateMemory(allocation.m_process_alloc); // FindSpace allocated this for real
}
break;
}
case eAllocationPolicyMirror:
@ -428,15 +428,15 @@ IRMemoryMap::Free (lldb::addr_t process_address, Error &error)
process_sp->DeallocateMemory(allocation.m_process_alloc);
}
}
if (lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS))
{
{
log->Printf("IRMemoryMap::Free (0x%" PRIx64 ") freed [0x%" PRIx64 "..0x%" PRIx64 ")",
(uint64_t)process_address,
iter->second.m_process_start,
iter->second.m_process_start + iter->second.m_size);
}
m_allocations.erase(iter);
}
@ -444,28 +444,28 @@ void
IRMemoryMap::WriteMemory (lldb::addr_t process_address, const uint8_t *bytes, size_t size, Error &error)
{
error.Clear();
AllocationMap::iterator iter = FindAllocation(process_address, size);
if (iter == m_allocations.end())
{
lldb::ProcessSP process_sp = m_process_wp.lock();
if (process_sp)
{
process_sp->WriteMemory(process_address, bytes, size, error);
return;
}
error.SetErrorToGenericError();
error.SetErrorString("Couldn't write: no allocation contains the target range and the process doesn't exist");
return;
}
Allocation &allocation = iter->second;
uint64_t offset = process_address - allocation.m_process_start;
lldb::ProcessSP process_sp;
switch (allocation.m_policy)
@ -509,9 +509,9 @@ IRMemoryMap::WriteMemory (lldb::addr_t process_address, const uint8_t *bytes, si
}
break;
}
if (lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS))
{
{
log->Printf("IRMemoryMap::WriteMemory (0x%" PRIx64 ", 0x%" PRIx64 ", 0x%" PRId64 ") went to [0x%" PRIx64 "..0x%" PRIx64 ")",
(uint64_t)process_address,
(uint64_t)bytes,
@ -525,10 +525,10 @@ void
IRMemoryMap::WriteScalarToMemory (lldb::addr_t process_address, Scalar &scalar, size_t size, Error &error)
{
error.Clear();
if (size == UINT32_MAX)
size = scalar.GetByteSize();
if (size > 0)
{
uint8_t buf[32];
@ -555,9 +555,9 @@ void
IRMemoryMap::WritePointerToMemory (lldb::addr_t process_address, lldb::addr_t address, Error &error)
{
error.Clear();
Scalar scalar(address);
WriteScalarToMemory(process_address, scalar, GetAddressByteSize(), error);
}
@ -565,46 +565,46 @@ void
IRMemoryMap::ReadMemory (uint8_t *bytes, lldb::addr_t process_address, size_t size, Error &error)
{
error.Clear();
AllocationMap::iterator iter = FindAllocation(process_address, size);
if (iter == m_allocations.end())
{
lldb::ProcessSP process_sp = m_process_wp.lock();
if (process_sp)
{
process_sp->ReadMemory(process_address, bytes, size, error);
return;
}
lldb::TargetSP target_sp = m_target_wp.lock();
if (target_sp)
{
Address absolute_address(process_address);
target_sp->ReadMemory(absolute_address, false, bytes, size, error);
return;
}
error.SetErrorToGenericError();
error.SetErrorString("Couldn't read: no allocation contains the target range, and neither the process nor the target exist");
return;
}
Allocation &allocation = iter->second;
uint64_t offset = process_address - allocation.m_process_start;
if (offset > allocation.m_size)
{
error.SetErrorToGenericError();
error.SetErrorString("Couldn't read: data is not in the allocation");
return;
}
lldb::ProcessSP process_sp;
switch (allocation.m_policy)
{
default:
@ -656,7 +656,7 @@ IRMemoryMap::ReadMemory (uint8_t *bytes, lldb::addr_t process_address, size_t si
}
break;
}
if (lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS))
{
log->Printf("IRMemoryMap::ReadMemory (0x%" PRIx64 ", 0x%" PRIx64 ", 0x%" PRId64 ") came from [0x%" PRIx64 "..0x%" PRIx64 ")",
@ -672,19 +672,19 @@ void
IRMemoryMap::ReadScalarFromMemory (Scalar &scalar, lldb::addr_t process_address, size_t size, Error &error)
{
error.Clear();
if (size > 0)
{
DataBufferHeap buf(size, 0);
ReadMemory(buf.GetBytes(), process_address, size, error);
if (!error.Success())
return;
DataExtractor extractor(buf.GetBytes(), buf.GetByteSize(), GetByteOrder(), GetAddressByteSize());
lldb::offset_t offset = 0;
switch (size)
{
default:
@ -709,15 +709,15 @@ void
IRMemoryMap::ReadPointerFromMemory (lldb::addr_t *address, lldb::addr_t process_address, Error &error)
{
error.Clear();
Scalar pointer_scalar;
ReadScalarFromMemory(pointer_scalar, process_address, GetAddressByteSize(), error);
if (!error.Success())
return;
*address = pointer_scalar.ULongLong();
return;
}
@ -725,20 +725,20 @@ void
IRMemoryMap::GetMemoryData (DataExtractor &extractor, lldb::addr_t process_address, size_t size, Error &error)
{
error.Clear();
if (size > 0)
{
AllocationMap::iterator iter = FindAllocation(process_address, size);
if (iter == m_allocations.end())
{
error.SetErrorToGenericError();
error.SetErrorStringWithFormat("Couldn't find an allocation containing [0x%" PRIx64 "..0x%" PRIx64 ")", process_address, process_address + size);
return;
}
Allocation &allocation = iter->second;
switch (allocation.m_policy)
{
default:
@ -788,5 +788,3 @@ IRMemoryMap::GetMemoryData (DataExtractor &extractor, lldb::addr_t process_addre
return;
}
}

View File

@ -1,10 +1,10 @@
##===- source/Expression/Makefile --------------------------*- Makefile -*-===##
#
#
# The LLVM Compiler Infrastructure
#
# This file is distributed under the University of Illinois Open Source
# License. See LICENSE.TXT for details.
#
#
##===----------------------------------------------------------------------===##
LLDB_LEVEL := ../..