From johnny.chen at apple.com Mon Nov 15 11:42:22 2010 From: johnny.chen at apple.com (Johnny Chen) Date: Mon, 15 Nov 2010 17:42:22 -0000 Subject: [Lldb-commits] [lldb] r119160 - /lldb/trunk/test/namespace/TestNamespace.py Message-ID: <20101115174222.473892A6C12C@llvm.org> Author: johnny Date: Mon Nov 15 11:42:22 2010 New Revision: 119160 URL: http://llvm.org/viewvc/llvm-project?rev=119160&view=rev Log: Remove the @expectedFailure decorator and uncomment 'expression -- i + j" test, as both rdar://problem/8659840 and rdar://problem/8660275 have been fixed. Modified: lldb/trunk/test/namespace/TestNamespace.py Modified: lldb/trunk/test/namespace/TestNamespace.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/namespace/TestNamespace.py?rev=119160&r1=119159&r2=119160&view=diff ============================================================================== --- lldb/trunk/test/namespace/TestNamespace.py (original) +++ lldb/trunk/test/namespace/TestNamespace.py Mon Nov 15 11:42:22 2010 @@ -17,7 +17,6 @@ self.buildDsym() self.namespace_variable_commands() - @unittest2.expectedFailure # rdar://problem/8659840 # runCmd: frame variable -c -G i # runCmd failed! @@ -65,8 +64,8 @@ # rdar://problem/8660275 # test/namespace: 'expression -- i+j' not working - #self.expect("expression -- i + j", - # startstr = "(int) $0 = 7") + self.expect("expression -- i + j", + startstr = "(int) $0 = 7") # (int) $0 = 7 if __name__ == '__main__': From johnny.chen at apple.com Mon Nov 15 12:04:54 2010 From: johnny.chen at apple.com (Johnny Chen) Date: Mon, 15 Nov 2010 18:04:54 -0000 Subject: [Lldb-commits] [lldb] r119162 - /lldb/trunk/test/class_types/TestClassTypes.py Message-ID: <20101115180454.DD8392A6C12C@llvm.org> Author: johnny Date: Mon Nov 15 12:04:54 2010 New Revision: 119162 URL: http://llvm.org/viewvc/llvm-project?rev=119162&view=rev Log: Add test sequence for 'frame variable this' and 'expression this' when stopped inside a ctor. Modified: lldb/trunk/test/class_types/TestClassTypes.py Modified: lldb/trunk/test/class_types/TestClassTypes.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/class_types/TestClassTypes.py?rev=119162&r1=119161&r2=119162&view=diff ============================================================================== --- lldb/trunk/test/class_types/TestClassTypes.py (original) +++ lldb/trunk/test/class_types/TestClassTypes.py Mon Nov 15 12:04:54 2010 @@ -176,10 +176,18 @@ # Continue on inside the ctor() body... self.runCmd("thread step-over") + # Verify that 'frame variable this' gets the data type correct. + self.expect("frame variable this",VARIABLES_DISPLAYED_CORRECTLY, + substrs = ['class C *']) + # Verify that frame variable -t this->m_c_int behaves correctly. self.expect("frame variable -t this->m_c_int", VARIABLES_DISPLAYED_CORRECTLY, startstr = '(int) this->m_c_int = 66') + # Verify that 'expression this' gets the data type correct. + self.expect("expression this", VARIABLES_DISPLAYED_CORRECTLY, + substrs = ['class C *']) + # rdar://problem/8430916 # expr this->m_c_int returns an incorrect value # From johnny.chen at apple.com Mon Nov 15 12:27:57 2010 From: johnny.chen at apple.com (Johnny Chen) Date: Mon, 15 Nov 2010 18:27:57 -0000 Subject: [Lldb-commits] [lldb] r119165 - in /lldb/trunk/test: global_variables/TestGlobalVariables.py namespace/TestNamespace.py Message-ID: <20101115182757.4A3F12A6C12C@llvm.org> Author: johnny Date: Mon Nov 15 12:27:57 2010 New Revision: 119165 URL: http://llvm.org/viewvc/llvm-project?rev=119165&view=rev Log: Add test sequences for 'frame variable' address-of operator and 'frame variable' fully-qualified name variable. Also add some comments. Modified: lldb/trunk/test/global_variables/TestGlobalVariables.py lldb/trunk/test/namespace/TestNamespace.py Modified: lldb/trunk/test/global_variables/TestGlobalVariables.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/global_variables/TestGlobalVariables.py?rev=119165&r1=119164&r2=119165&view=diff ============================================================================== --- lldb/trunk/test/global_variables/TestGlobalVariables.py (original) +++ lldb/trunk/test/global_variables/TestGlobalVariables.py Mon Nov 15 12:27:57 2010 @@ -56,6 +56,9 @@ 'GLOBAL: (const char *) g_file_static_cstr', '"g_file_static_cstr"']) + # 'frame variable' should support address-of operator. + self.runCmd("frame variable &g_file_global_int") + if __name__ == '__main__': import atexit Modified: lldb/trunk/test/namespace/TestNamespace.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/namespace/TestNamespace.py?rev=119165&r1=119164&r2=119165&view=diff ============================================================================== --- lldb/trunk/test/namespace/TestNamespace.py (original) +++ lldb/trunk/test/namespace/TestNamespace.py Mon Nov 15 12:27:57 2010 @@ -54,14 +54,23 @@ substrs = ['state is stopped', 'stop reason = breakpoint']) + # 'frame variable' with basename 'i' should work. self.expect("frame variable -c -G i", startstr = "main.cpp:%d: (int) (anonymous namespace)::i = 3" % self.line_var_i) # main.cpp:12: (int) (anonymous namespace)::i = 3 + # 'frame variable' with basename 'j' should work, too. self.expect("frame variable -c -G j", startstr = "main.cpp:%d: (int) A::B::j = 4" % self.line_var_j) # main.cpp:19: (int) A::B::j = 4 + # 'frame variable' should support address-of operator. + self.runCmd("frame variable &i") + + # 'frame variable' with fully qualified name 'A::B::j' should work. + self.expect("frame variable 'A::B::j", VARIABLES_DISPLAYED_CORRECTLY, + startstr = '(int) A::B::j = 4') + # rdar://problem/8660275 # test/namespace: 'expression -- i+j' not working self.expect("expression -- i + j", From johnny.chen at apple.com Mon Nov 15 12:40:06 2010 From: johnny.chen at apple.com (Johnny Chen) Date: Mon, 15 Nov 2010 18:40:06 -0000 Subject: [Lldb-commits] [lldb] r119168 - /lldb/trunk/test/namespace/TestNamespace.py Message-ID: <20101115184006.757852A6C12C@llvm.org> Author: johnny Date: Mon Nov 15 12:40:06 2010 New Revision: 119168 URL: http://llvm.org/viewvc/llvm-project?rev=119168&view=rev Log: Also add a test for "frame variable '(anonymous namespace)::i'", plus expression command using fully qualified names. Modified: lldb/trunk/test/namespace/TestNamespace.py Modified: lldb/trunk/test/namespace/TestNamespace.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/namespace/TestNamespace.py?rev=119168&r1=119167&r2=119168&view=diff ============================================================================== --- lldb/trunk/test/namespace/TestNamespace.py (original) +++ lldb/trunk/test/namespace/TestNamespace.py Mon Nov 15 12:40:06 2010 @@ -71,12 +71,21 @@ self.expect("frame variable 'A::B::j", VARIABLES_DISPLAYED_CORRECTLY, startstr = '(int) A::B::j = 4') + # So should the anonymous namespace case. + self.expect("frame variable '(anonymous namespace)::i", VARIABLES_DISPLAYED_CORRECTLY, + startstr = '(int) (anonymous namespace)::i = 3') + # rdar://problem/8660275 # test/namespace: 'expression -- i+j' not working self.expect("expression -- i + j", startstr = "(int) $0 = 7") # (int) $0 = 7 + self.runCmd("expression -- '(anonymous namespace)::i'") + + self.runCmd("expression -- 'A::B::j'") + + if __name__ == '__main__': import atexit lldb.SBDebugger.Initialize() From johnny.chen at apple.com Mon Nov 15 12:49:03 2010 From: johnny.chen at apple.com (Johnny Chen) Date: Mon, 15 Nov 2010 18:49:03 -0000 Subject: [Lldb-commits] [lldb] r119171 - /lldb/trunk/test/namespace/TestNamespace.py Message-ID: <20101115184903.D0FA52A6C12E@llvm.org> Author: johnny Date: Mon Nov 15 12:49:03 2010 New Revision: 119171 URL: http://llvm.org/viewvc/llvm-project?rev=119171&view=rev Log: Add radar info for failed expression command test sequences which are now commented out. Modified: lldb/trunk/test/namespace/TestNamespace.py Modified: lldb/trunk/test/namespace/TestNamespace.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/namespace/TestNamespace.py?rev=119171&r1=119170&r2=119171&view=diff ============================================================================== --- lldb/trunk/test/namespace/TestNamespace.py (original) +++ lldb/trunk/test/namespace/TestNamespace.py Mon Nov 15 12:49:03 2010 @@ -81,9 +81,11 @@ startstr = "(int) $0 = 7") # (int) $0 = 7 - self.runCmd("expression -- '(anonymous namespace)::i'") - - self.runCmd("expression -- 'A::B::j'") + # rdar://problem/8668674 + # expression command with fully qualified namespace for a variable does not work + #self.runCmd("expression -- '(anonymous namespace)::i'") + # + #self.runCmd("expression -- 'A::B::j'") if __name__ == '__main__': From johnny.chen at apple.com Mon Nov 15 13:10:53 2010 From: johnny.chen at apple.com (Johnny Chen) Date: Mon, 15 Nov 2010 19:10:53 -0000 Subject: [Lldb-commits] [lldb] r119172 - /lldb/trunk/test/namespace/TestNamespace.py Message-ID: <20101115191053.DAD292A6C12C@llvm.org> Author: johnny Date: Mon Nov 15 13:10:53 2010 New Revision: 119172 URL: http://llvm.org/viewvc/llvm-project?rev=119172&view=rev Log: Check in a test case for rdar://problem/8668740: 'frame variable' output for namespace variables look wrong Modified: lldb/trunk/test/namespace/TestNamespace.py Modified: lldb/trunk/test/namespace/TestNamespace.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/namespace/TestNamespace.py?rev=119172&r1=119171&r2=119172&view=diff ============================================================================== --- lldb/trunk/test/namespace/TestNamespace.py (original) +++ lldb/trunk/test/namespace/TestNamespace.py Mon Nov 15 13:10:53 2010 @@ -54,6 +54,18 @@ substrs = ['state is stopped', 'stop reason = breakpoint']) + # rdar://problem/8668740 + # 'frame variable' output for namespace variables look wrong + # (lldb) frame variable + # (int) a = 12 + # (A::B::uint_t) anon_uint = 0 + # (A::B::uint_t) a_uint = 1 + # (A::B::uint_t) b_uint = 2 + # (A::B::uint_t) y_uint = 3 + # (lldb) + self.expect('frame variable', VARIABLES_DISPLAYED_CORRECTLY, + substrs = ['']) + # 'frame variable' with basename 'i' should work. self.expect("frame variable -c -G i", startstr = "main.cpp:%d: (int) (anonymous namespace)::i = 3" % self.line_var_i) From gclayton at apple.com Mon Nov 15 20:10:55 2010 From: gclayton at apple.com (Greg Clayton) Date: Tue, 16 Nov 2010 02:10:55 -0000 Subject: [Lldb-commits] [lldb] r119324 - in /lldb/trunk: include/lldb/Symbol/Type.h source/Expression/ClangExpressionDeclMap.cpp source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.h source/Symbol/Type.cpp Message-ID: <20101116021055.28F3F2A6C12C@llvm.org> Author: gclayton Date: Mon Nov 15 20:10:54 2010 New Revision: 119324 URL: http://llvm.org/viewvc/llvm-project?rev=119324&view=rev Log: First attempt and getting "const" C++ method function signatures correct. It currently isn't working, but it should be close. I will work on this more when I figure out what I am not doing correctly. Modified: lldb/trunk/include/lldb/Symbol/Type.h lldb/trunk/source/Expression/ClangExpressionDeclMap.cpp lldb/trunk/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp lldb/trunk/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.h lldb/trunk/source/Symbol/Type.cpp Modified: lldb/trunk/include/lldb/Symbol/Type.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/Symbol/Type.h?rev=119324&r1=119323&r2=119324&view=diff ============================================================================== --- lldb/trunk/include/lldb/Symbol/Type.h (original) +++ lldb/trunk/include/lldb/Symbol/Type.h Mon Nov 15 20:10:54 2010 @@ -223,6 +223,9 @@ m_encoding_type = encoding_type; } + uint32_t + GetEncodingMask (); + protected: ConstString m_name; SymbolFile *m_symbol_file; Modified: lldb/trunk/source/Expression/ClangExpressionDeclMap.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Expression/ClangExpressionDeclMap.cpp?rev=119324&r1=119323&r2=119324&view=diff ============================================================================== --- lldb/trunk/source/Expression/ClangExpressionDeclMap.cpp (original) +++ lldb/trunk/source/Expression/ClangExpressionDeclMap.cpp Mon Nov 15 20:10:54 2010 @@ -1085,6 +1085,14 @@ if (!this_type) return; + if (log) + { + log->PutCString ("Type for \"this\" is: "); + StreamString strm; + this_type->Dump(&strm, true); + log->PutCString (strm.GetData()); + } + TypeFromUser this_user_type(this_type->GetClangType(), this_type->GetClangAST()); @@ -1120,12 +1128,20 @@ m_lookedup_types.insert(std::pair(name_unique_cstr, true)); // 2 The type is looked up and added, potentially causing more type loookups. - lldb::TypeSP type = m_sym_ctx.FindTypeByName (name); + lldb::TypeSP type_sp (m_sym_ctx.FindTypeByName (name)); - if (type.get()) + if (type_sp) { - TypeFromUser user_type(type->GetClangType(), - type->GetClangAST()); + if (log) + { + log->Printf ("Matching type found for \"%s\": ", name.GetCString()); + StreamString strm; + type_sp->Dump(&strm, true); + log->PutCString (strm.GetData()); + } + + TypeFromUser user_type(type_sp->GetClangType(), + type_sp->GetClangAST()); AddOneType(context, user_type, false); } Modified: lldb/trunk/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp?rev=119324&r1=119323&r2=119324&view=diff ============================================================================== --- lldb/trunk/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp (original) +++ lldb/trunk/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp Mon Nov 15 20:10:54 2010 @@ -20,6 +20,7 @@ #include "clang/Basic/SourceManager.h" #include "clang/Basic/TargetInfo.h" #include "clang/Basic/Specifiers.h" +#include "clang/Sema/DeclSpec.h" #include "lldb/Core/Module.h" #include "lldb/Core/PluginManager.h" @@ -2235,7 +2236,8 @@ bool skip_artificial, TypeList* type_list, std::vector& function_param_types, - std::vector& function_param_decls + std::vector& function_param_decls, + unsigned &type_quals ) { if (parent_die == NULL) @@ -2243,7 +2245,7 @@ const uint8_t *fixed_form_sizes = DWARFFormValue::GetFixedFormSizesForAddressSize (dwarf_cu->GetAddressByteSize()); - size_t count = 0; + size_t arg_idx = 0; const DWARFDebugInfoEntry *die; for (die = parent_die->GetFirstChild(); die != NULL; die = die->GetSibling()) { @@ -2308,7 +2310,42 @@ if (skip_artificial) { if (is_artificial) + { + // In order to determine if a C++ member function is + // "const" we have to look at the const-ness of "this"... + // Ugly, but that + if (arg_idx == 0) + { + const DWARFDebugInfoEntry *grandparent_die = parent_die->GetParent(); + if (grandparent_die && (grandparent_die->Tag() == DW_TAG_structure_type || + grandparent_die->Tag() == DW_TAG_class_type)) + { + LanguageType language = sc.comp_unit->GetLanguage(); + if (language == eLanguageTypeObjC_plus_plus || language == eLanguageTypeC_plus_plus) + { + // Often times compilers omit the "this" name for the + // specification DIEs, so we can't rely upon the name + // being in the formal parameter DIE... + if (name == NULL || ::strcmp(name, "this")==0) + { + Type *this_type = ResolveTypeUID (param_type_die_offset); + if (this_type) + { + uint32_t encoding_mask = this_type->GetEncodingMask(); + if (encoding_mask & Type::eEncodingIsPointerUID) + { + if (encoding_mask & (1u << Type::eEncodingIsConstUID)) + type_quals |= clang::DeclSpec::TQ_const; + if (encoding_mask & (1u << Type::eEncodingIsVolatileUID)) + type_quals |= clang::DeclSpec::TQ_volatile; + } + } + } + } + } + } skip = true; + } else { @@ -2336,6 +2373,7 @@ } } } + arg_idx++; } break; @@ -2343,7 +2381,7 @@ break; } } - return count; + return arg_idx; } size_t @@ -3257,7 +3295,8 @@ skip_artificial, type_list, function_param_types, - function_param_decls); + function_param_decls, + type_quals); } // clang_type will get the function prototype clang type after this call Modified: lldb/trunk/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.h?rev=119324&r1=119323&r2=119324&view=diff ============================================================================== --- lldb/trunk/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.h (original) +++ lldb/trunk/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.h Mon Nov 15 20:10:54 2010 @@ -255,7 +255,8 @@ bool skip_artificial, lldb_private::TypeList* type_list, std::vector& function_args, - std::vector& function_param_decls); + std::vector& function_param_decls, + unsigned &type_quals); size_t ParseChildEnumerators( const lldb_private::SymbolContext& sc, Modified: lldb/trunk/source/Symbol/Type.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Symbol/Type.cpp?rev=119324&r1=119323&r2=119324&view=diff ============================================================================== --- lldb/trunk/source/Symbol/Type.cpp (original) +++ lldb/trunk/source/Symbol/Type.cpp Mon Nov 15 20:10:54 2010 @@ -601,6 +601,16 @@ return child_qual_type; } +uint32_t +lldb_private::Type::GetEncodingMask () +{ + uint32_t encoding_mask = 1u << m_encoding_uid_type; + Type *encoding_type = GetEncodingType(); + assert (encoding_type != this); + if (encoding_type) + encoding_mask |= encoding_type->GetEncodingMask (); + return encoding_mask; +} clang_type_t lldb_private::Type::GetClangType () From jmolenda at apple.com Mon Nov 15 21:01:20 2010 From: jmolenda at apple.com (Jason Molenda) Date: Tue, 16 Nov 2010 03:01:20 -0000 Subject: [Lldb-commits] [lldb] r119327 - /lldb/trunk/source/Plugins/Process/Utility/UnwindAssemblyProfiler-x86.cpp Message-ID: <20101116030120.93B172A6C12C@llvm.org> Author: jmolenda Date: Mon Nov 15 21:01:20 2010 New Revision: 119327 URL: http://llvm.org/viewvc/llvm-project?rev=119327&view=rev Log: Add an UnwindPlan Row for the last instruction of a function when we're using the stack pointer to define the CFA again. Makes unwinds while sitting at the 'ret' instruction work, assuming we have accurate function address bounds. Modified: lldb/trunk/source/Plugins/Process/Utility/UnwindAssemblyProfiler-x86.cpp Modified: lldb/trunk/source/Plugins/Process/Utility/UnwindAssemblyProfiler-x86.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Plugins/Process/Utility/UnwindAssemblyProfiler-x86.cpp?rev=119327&r1=119326&r2=119327&view=diff ============================================================================== --- lldb/trunk/source/Plugins/Process/Utility/UnwindAssemblyProfiler-x86.cpp (original) +++ lldb/trunk/source/Plugins/Process/Utility/UnwindAssemblyProfiler-x86.cpp Mon Nov 15 21:01:20 2010 @@ -525,6 +525,7 @@ int current_func_text_offset = 0; int current_sp_bytes_offset_from_cfa = 0; UnwindPlan::Row::RegisterLocation initial_regloc; + Error error; if (!m_cur_insn.IsValid()) { @@ -555,7 +556,6 @@ int stack_offset, insn_len; int machine_regno; // register numbers masked directly out of instructions uint32_t lldb_regno; // register numbers in lldb's eRegisterKindLLDB numbering scheme - Error error; if (!instruction_length (m_cur_insn, insn_len) || insn_len == 0 || insn_len > kMaxInstructionByteSize) { @@ -661,6 +661,43 @@ current_func_text_offset += insn_len; } + // Now look at the byte at the end of the AddressRange for a limited attempt at describing the + // epilogue. If this function is built -fomit-frame-pointer (so the CFA is defined in terms of the + // stack pointer) we'd need to profile every instruction which causes rsp to change to backtrace + // all the time. But assuming the CFA is in terms of rbp most of the time, this one additional Row + // will be sufficient. + + if (m_func_bounds.GetByteSize() > 2) + { + Address last_insn (m_func_bounds.GetBaseAddress()); + last_insn.SetOffset (last_insn.GetOffset() + m_func_bounds.GetByteSize() - 1); + uint8_t bytebuf[1]; + if (m_target.ReadMemory (last_insn, bytebuf, 1, error) != -1) + { + if (bytebuf[0] == 0xc3) // ret aka retq + { + // Create a fresh, empty Row and RegisterLocation - don't mention any other registers + UnwindPlan::Row epi_row; + UnwindPlan::Row::RegisterLocation epi_regloc; + + // When the ret instruction is about to be executed, here's our state + epi_row.SetOffset (m_func_bounds.GetByteSize() - 1); + epi_row.SetCFARegister (m_lldb_sp_regnum); + epi_row.SetCFAOffset (m_wordsize); + + // caller's stack pointer value before the call insn is the CFA address + epi_regloc.SetIsCFAPlusOffset (0); + epi_row.SetRegisterInfo (m_lldb_sp_regnum, epi_regloc); + + // saved instruction pointer can be found at CFA - wordsize + epi_regloc.SetAtCFAPlusOffset (-m_wordsize); + epi_row.SetRegisterInfo (m_lldb_ip_regnum, epi_regloc); + + unwind_plan.AppendRow (epi_row); + } + } + } + unwind_plan.SetSourceName ("assembly insn profiling"); return true; From ctice at apple.com Mon Nov 15 23:07:41 2010 From: ctice at apple.com (Caroline Tice) Date: Tue, 16 Nov 2010 05:07:41 -0000 Subject: [Lldb-commits] [lldb] r119329 - in /lldb/trunk: include/lldb/Target/Process.h source/Core/ConnectionFileDescriptor.cpp source/Core/Debugger.cpp source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp source/Plugins/Process/gdb-remote/ProcessGDBRemote.h source/Target/Process.cpp Message-ID: <20101116050741.B3A592A6C12C@llvm.org> Author: ctice Date: Mon Nov 15 23:07:41 2010 New Revision: 119329 URL: http://llvm.org/viewvc/llvm-project?rev=119329&view=rev Log: Make processes use InputReaders for their input. Move the process ReadThread stuff into the main Process class (out of the Process Plugins). This has the (intended) side effect of disabling the command line tool from reading input/commands while the process is running (the input is directed to the running process rather than to the command interpreter). Modified: lldb/trunk/include/lldb/Target/Process.h lldb/trunk/source/Core/ConnectionFileDescriptor.cpp lldb/trunk/source/Core/Debugger.cpp lldb/trunk/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp lldb/trunk/source/Plugins/Process/gdb-remote/ProcessGDBRemote.h lldb/trunk/source/Target/Process.cpp Modified: lldb/trunk/include/lldb/Target/Process.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/Target/Process.h?rev=119329&r1=119328&r2=119329&view=diff ============================================================================== --- lldb/trunk/include/lldb/Target/Process.h (original) +++ lldb/trunk/include/lldb/Target/Process.h Mon Nov 15 23:07:41 2010 @@ -20,6 +20,7 @@ #include "lldb/Interpreter/Args.h" #include "lldb/Interpreter/Options.h" #include "lldb/Core/Broadcaster.h" +#include "lldb/Core/Communication.h" #include "lldb/Core/Error.h" #include "lldb/Core/Event.h" #include "lldb/Core/StringList.h" @@ -1678,6 +1679,10 @@ UnixSignals m_unix_signals; /// This is the current signal set for this process. ConstString m_target_triple; lldb::ABISP m_abi_sp; + lldb::InputReaderSP m_process_input_reader; + lldb_private::Communication m_stdio_communication; + lldb_private::Mutex m_stdio_comm_mutex; + std::string m_stdout_data; typedef std::map LanguageRuntimeCollection; LanguageRuntimeCollection m_language_runtimes; @@ -1738,7 +1743,33 @@ size_t WriteMemoryPrivate (lldb::addr_t addr, const void *buf, size_t size, Error &error); - + + void + AppendSTDOUT (const char *s, size_t len); + + static void + STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len); + + void + PushProcessInputReader (); + + void + PopProcessInputReader (); + + void + ResetProcessInputReader (); + + void + SetUpProcessInputReader (int file_descriptor); + + static size_t + ProcessInputReaderCallback (void *baton, + InputReader &reader, + lldb::InputReaderAction notification, + const char *bytes, + size_t bytes_len); + + private: //------------------------------------------------------------------ // For Process only Modified: lldb/trunk/source/Core/ConnectionFileDescriptor.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Core/ConnectionFileDescriptor.cpp?rev=119329&r1=119328&r2=119329&view=diff ============================================================================== --- lldb/trunk/source/Core/ConnectionFileDescriptor.cpp (original) +++ lldb/trunk/source/Core/ConnectionFileDescriptor.cpp Mon Nov 15 23:07:41 2010 @@ -38,6 +38,7 @@ ConnectionFileDescriptor::ConnectionFileDescriptor () : Connection(), m_fd (-1), + m_is_socket (false), m_should_close_fd (false) { lldb_private::LogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION | LIBLLDB_LOG_OBJECT, @@ -48,6 +49,7 @@ ConnectionFileDescriptor::ConnectionFileDescriptor (int fd, bool owns_fd) : Connection(), m_fd (fd), + m_is_socket (false), m_should_close_fd (owns_fd) { lldb_private::LogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION | LIBLLDB_LOG_OBJECT, Modified: lldb/trunk/source/Core/Debugger.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Core/Debugger.cpp?rev=119329&r1=119328&r2=119329&view=diff ============================================================================== --- lldb/trunk/source/Core/Debugger.cpp (original) +++ lldb/trunk/source/Core/Debugger.cpp Mon Nov 15 23:07:41 2010 @@ -324,22 +324,8 @@ void Debugger::DispatchInput (const char *bytes, size_t bytes_len) { - if (bytes == NULL || bytes_len == 0) - return; - - // TODO: implement the STDIO to the process as an input reader... - TargetSP target = GetSelectedTarget(); - if (target.get() != NULL) - { - ProcessSP process_sp = target->GetProcessSP(); - if (process_sp.get() != NULL - && StateIsRunningState (process_sp->GetState())) - { - Error error; - if (process_sp->PutSTDIN (bytes, bytes_len, error) == bytes_len) - return; - } - } +// if (bytes == NULL || bytes_len == 0) +// return; WriteToDefaultReader (bytes, bytes_len); } Modified: lldb/trunk/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp?rev=119329&r1=119328&r2=119329&view=diff ============================================================================== --- lldb/trunk/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp (original) +++ lldb/trunk/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp Mon Nov 15 23:07:41 2010 @@ -104,9 +104,7 @@ Process (target, listener), m_dynamic_loader_ap (), m_flags (0), - m_stdio_communication ("gdb-remote.stdio"), m_stdio_mutex (Mutex::eMutexTypeRecursive), - m_stdout_data (), m_byte_order (eByteOrderHost), m_gdb_comm(), m_debugserver_pid (LLDB_INVALID_PROCESS_ID), @@ -1634,23 +1632,23 @@ return error; } -void -ProcessGDBRemote::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len) -{ - ProcessGDBRemote *process = (ProcessGDBRemote *)baton; - process->AppendSTDOUT(static_cast(src), src_len); -} - -void -ProcessGDBRemote::AppendSTDOUT (const char* s, size_t len) -{ - ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::%s (<%d> %s) ...", __FUNCTION__, len, s); - Mutex::Locker locker(m_stdio_mutex); - m_stdout_data.append(s, len); +//void +//ProcessGDBRemote::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len) +//{ +// ProcessGDBRemote *process = (ProcessGDBRemote *)baton; +// process->AppendSTDOUT(static_cast(src), src_len); +//} - // FIXME: Make a real data object for this and put it out. - BroadcastEventIfUnique (eBroadcastBitSTDOUT); -} +//void +//ProcessGDBRemote::AppendSTDOUT (const char* s, size_t len) +//{ +// ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::%s (<%d> %s) ...", __FUNCTION__, len, s); +// Mutex::Locker locker(m_stdio_mutex); +// m_stdout_data.append(s, len); +// +// // FIXME: Make a real data object for this and put it out. +// BroadcastEventIfUnique (eBroadcastBitSTDOUT); +//} Error @@ -1867,18 +1865,7 @@ if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) { if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd) - { - std::auto_ptr conn_ap(new ConnectionFileDescriptor (pty.ReleaseMasterFileDescriptor(), true)); - if (conn_ap.get()) - { - m_stdio_communication.SetConnection(conn_ap.release()); - if (m_stdio_communication.IsConnected()) - { - m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this); - m_stdio_communication.StartReadThread(); - } - } - } + SetUpProcessInputReader (pty.ReleaseMasterFileDescriptor()); } } else Modified: lldb/trunk/source/Plugins/Process/gdb-remote/ProcessGDBRemote.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Plugins/Process/gdb-remote/ProcessGDBRemote.h?rev=119329&r1=119328&r2=119329&view=diff ============================================================================== --- lldb/trunk/source/Plugins/Process/gdb-remote/ProcessGDBRemote.h (original) +++ lldb/trunk/source/Plugins/Process/gdb-remote/ProcessGDBRemote.h Mon Nov 15 23:07:41 2010 @@ -261,11 +261,11 @@ bool ProcessIDIsValid ( ) const; - static void - STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len); +// static void +// STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len); - void - AppendSTDOUT (const char* s, size_t len); +// void +// AppendSTDOUT (const char* s, size_t len); void Clear ( ); @@ -321,9 +321,7 @@ std::auto_ptr m_dynamic_loader_ap; lldb_private::Flags m_flags; // Process specific flags (see eFlags enums) - lldb_private::Communication m_stdio_communication; lldb_private::Mutex m_stdio_mutex; // Multithreaded protection for stdio - std::string m_stdout_data; lldb::ByteOrder m_byte_order; GDBRemoteCommunication m_gdb_comm; lldb::pid_t m_debugserver_pid; Modified: lldb/trunk/source/Target/Process.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Target/Process.cpp?rev=119329&r1=119328&r2=119329&view=diff ============================================================================== --- lldb/trunk/source/Target/Process.cpp (original) +++ lldb/trunk/source/Target/Process.cpp Mon Nov 15 23:07:41 2010 @@ -14,7 +14,9 @@ #include "lldb/Breakpoint/StoppointCallbackContext.h" #include "lldb/Breakpoint/BreakpointLocation.h" #include "lldb/Core/Event.h" +#include "lldb/Core/ConnectionFileDescriptor.h" #include "lldb/Core/Debugger.h" +#include "lldb/Core/InputReader.h" #include "lldb/Core/Log.h" #include "lldb/Core/PluginManager.h" #include "lldb/Core/State.h" @@ -85,7 +87,11 @@ m_notifications (), m_persistent_vars(), m_listener(listener), - m_unix_signals () + m_unix_signals (), + m_process_input_reader (), + m_stdio_communication ("lldb.process.stdio"), + m_stdio_comm_mutex (Mutex::eMutexTypeRecursive), + m_stdout_data () { UpdateInstanceName(); @@ -1160,6 +1166,7 @@ Error error; m_target_triple.Clear(); m_abi_sp.reset(); + m_process_input_reader.reset(); Module *exe_module = m_target.GetExecutableModule().get(); if (exe_module) @@ -1305,6 +1312,7 @@ m_target_triple.Clear(); m_abi_sp.reset(); + m_process_input_reader.reset(); // Find the process and its architecture. Make sure it matches the architecture // of the current Target, and if not adjust it. @@ -1347,6 +1355,7 @@ { m_target_triple.Clear(); m_abi_sp.reset(); + m_process_input_reader.reset(); // Find the process and its architecture. Make sure it matches the architecture // of the current Target, and if not adjust it. @@ -1467,6 +1476,12 @@ DidDestroy(); StopPrivateStateThread(); } + m_stdio_communication.StopReadThread(); + m_stdio_communication.Disconnect(); + if (m_process_input_reader && m_process_input_reader->IsActive()) + m_target.GetDebugger().PopInputReader (m_process_input_reader); + if (m_process_input_reader) + m_process_input_reader.reset(); } return error; } @@ -1714,6 +1729,10 @@ { log->Printf ("\tChanging public state from: %s to %s", StateAsCString(GetState ()), StateAsCString (internal_state)); } + if (StateIsRunningState (internal_state)) + PushProcessInputReader (); + else + PopProcessInputReader (); Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get()); BroadcastEvent (event_sp); } @@ -2035,6 +2054,111 @@ return Host::GetArchSpecForExistingProcess (process_name); } +void +Process::AppendSTDOUT (const char * s, size_t len) +{ + Mutex::Locker locker (m_stdio_comm_mutex); + m_stdout_data.append (s, len); + + BroadcastEventIfUnique (eBroadcastBitSTDOUT); +} + +void +Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len) +{ + Process *process = (Process *) baton; + process->AppendSTDOUT (static_cast(src), src_len); +} + +size_t +Process::ProcessInputReaderCallback (void *baton, + InputReader &reader, + lldb::InputReaderAction notification, + const char *bytes, + size_t bytes_len) +{ + Process *process = (Process *) baton; + + switch (notification) + { + case eInputReaderActivate: + break; + + case eInputReaderDeactivate: + break; + + case eInputReaderReactivate: + break; + + case eInputReaderGotToken: + { + Error error; + process->PutSTDIN (bytes, bytes_len, error); + } + break; + + case eInputReaderDone: + break; + + } + + return bytes_len; +} + +void +Process::ResetProcessInputReader () +{ + m_process_input_reader.reset(); +} + +void +Process::SetUpProcessInputReader (int file_descriptor) +{ + // First set up the Read Thread for reading/handling process I/O + + std::auto_ptr conn_ap (new ConnectionFileDescriptor (file_descriptor, true)); + + if (conn_ap.get()) + { + m_stdio_communication.SetConnection (conn_ap.release()); + if (m_stdio_communication.IsConnected()) + { + m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this); + m_stdio_communication.StartReadThread(); + + // Now read thread is set up, set up input reader. + + if (!m_process_input_reader.get()) + { + m_process_input_reader.reset (new InputReader(m_target.GetDebugger())); + Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback, + this, + eInputReaderGranularityByte, + NULL, + NULL, + false)); + + if (err.Fail()) + m_process_input_reader.reset(); + } + } + } +} + +void +Process::PushProcessInputReader () +{ + if (m_process_input_reader && !m_process_input_reader->IsActive()) + m_target.GetDebugger().PushInputReader (m_process_input_reader); +} + +void +Process::PopProcessInputReader () +{ + if (m_process_input_reader && m_process_input_reader->IsActive()) + m_target.GetDebugger().PopInputReader (m_process_input_reader); +} + lldb::UserSettingsControllerSP Process::GetSettingsController (bool finish) { From johnny.chen at apple.com Tue Nov 16 12:11:55 2010 From: johnny.chen at apple.com (Johnny Chen) Date: Tue, 16 Nov 2010 18:11:55 -0000 Subject: [Lldb-commits] [lldb] r119353 - /lldb/trunk/test/namespace/main.cpp Message-ID: <20101116181155.F03F82A6C12C@llvm.org> Author: johnny Date: Tue Nov 16 12:11:55 2010 New Revision: 119353 URL: http://llvm.org/viewvc/llvm-project?rev=119353&view=rev Log: Disambiguate the name lookup for the data type of anon_uint variable. Modified: lldb/trunk/test/namespace/main.cpp Modified: lldb/trunk/test/namespace/main.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/namespace/main.cpp?rev=119353&r1=119352&r2=119353&view=diff ============================================================================== --- lldb/trunk/test/namespace/main.cpp (original) +++ lldb/trunk/test/namespace/main.cpp Tue Nov 16 12:11:55 2010 @@ -8,7 +8,7 @@ //===----------------------------------------------------------------------===// namespace { - typedef unsigned int uint_t; + typedef unsigned int my_uint_t; int i; // Find the line number for anonymous namespace variable i. } @@ -53,7 +53,7 @@ int Foo::myfunc(int a) { - ::uint_t anon_uint = 0; + ::my_uint_t anon_uint = 0; A::uint_t a_uint = 1; B::uint_t b_uint = 2; Y::uint_t y_uint = 3; From johnny.chen at apple.com Tue Nov 16 13:44:50 2010 From: johnny.chen at apple.com (Johnny Chen) Date: Tue, 16 Nov 2010 19:44:50 -0000 Subject: [Lldb-commits] [lldb] r119371 - in /lldb/trunk/utils/test: ./ ras.py Message-ID: <20101116194450.345482A6C12C@llvm.org> Author: johnny Date: Tue Nov 16 13:44:50 2010 New Revision: 119371 URL: http://llvm.org/viewvc/llvm-project?rev=119371&view=rev Log: Initial check-in of a Python utility to run the lldb test suite and send the result including the session logs of test failures/errors as a MIME message. Added: lldb/trunk/utils/test/ lldb/trunk/utils/test/ras.py (with props) Added: lldb/trunk/utils/test/ras.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/utils/test/ras.py?rev=119371&view=auto ============================================================================== --- lldb/trunk/utils/test/ras.py (added) +++ lldb/trunk/utils/test/ras.py Tue Nov 16 13:44:50 2010 @@ -0,0 +1,176 @@ +#!/usr/bin/env python + +""" +Run the test suite and send the result as an email message. + +The code for sending of the directory is copied from +http://docs.python.org/library/email-examples.html. +""" + +import os +import sys +import shutil +import smtplib +# For guessing MIME type based on file name extension +import mimetypes + +from optparse import OptionParser + +from email import encoders +from email.message import Message +from email.mime.audio import MIMEAudio +from email.mime.base import MIMEBase +from email.mime.image import MIMEImage +from email.mime.multipart import MIMEMultipart +from email.mime.text import MIMEText + +def runTestsuite(testDir, sessDir, envs = None): + """Run the testsuite and return a (summary, output) tuple.""" + os.chdir(testDir) + + for env in envs: + list = env.split('=') + var = list[0].strip() + val = list[1].strip() + print var + "=" + val + os.environ[var] = val + + import shlex, subprocess + + command_line = "./dotest.py -w -s %s" % sessDir + # Apply correct tokenization for subprocess.Popen(). + args = shlex.split(command_line) + + # Use subprocess module to spawn a new process. + process = subprocess.Popen(args, + stdout=subprocess.PIPE, stderr=subprocess.PIPE) + # Wait for subprocess to terminate. + stdout, stderr = process.communicate() + + # This will be used as the subject line of our email about this test. + cmd = "%s %s" % (' '.join(envs) if envs else "", command_line) + + return (cmd, stderr) + + +COMMASPACE = ', ' + +def main(): + parser = OptionParser(usage="""\ +Run lldb test suite and send the results as a MIME message. + +Usage: %prog [options] + +Unless the -o option is given, the email is sent by forwarding to the specified +SMTP server, which then does the normal delivery process. +""") + parser.add_option('-d', '--directory', + type='string', action='store', + dest='testDir', + help="""The LLDB test directory directly under the top dir. + Otherwise use the current directory.""") + # + # This is similar to TestBase.getRunSpec(self) from lldbtest.py. + # + parser.add_option('-e', '--environment', + type='string', action='append', metavar='ENVIRONMENT', + default=[], dest='environments', + help="""The environment setting as prefix to the test driver. + Example: -e 'CC=clang' -e 'ARCH=x86_64'""") + parser.add_option('-m', '--mailserver', + type='string', action='store', metavar='MAILSERVER', + dest='mailserver', + help="""The outgoing SMTP server.""") + parser.add_option('-o', '--output', + type='string', action='store', metavar='FILE', + help="""Print the composed message to FILE instead of + sending the message to the SMTP server.""") + parser.add_option('-s', '--sender', + type='string', action='store', metavar='SENDER', + help='The value of the From: header (required)') + parser.add_option('-r', '--recipient', + type='string', action='append', metavar='RECIPIENT', + default=[], dest='recipients', + help='A To: header value (at least one required)') + opts, args = parser.parse_args() + if not opts.sender or not opts.recipients: + parser.print_help() + sys.exit(1) + testDir = opts.testDir + if not testDir: + testDir = '.' + + sessDir = 'tmp-lldb-session' + if os.path.exists(sessDir): + shutil.rmtree(sessDir) + #print "environments:", opts.environments + summary, output = runTestsuite(testDir, sessDir, opts.environments) + + # Create the enclosing (outer) message + outer = MIMEMultipart() + outer['Subject'] = summary + outer['To'] = COMMASPACE.join(opts.recipients) + outer['From'] = opts.sender + outer.preamble = 'You will not see this in a MIME-aware mail reader.\n' + + # The sessDir contains all the session logs for failed/errored tests. + # Attach them all if it exists! + + if not os.path.exists(sessDir): + outer.attach(MIMEText(output, 'plain')) + else: + outer.attach(MIMEText("%s\n%s\n\n" % (output, + "Session logs of test failures/errors:"), + 'plain')) + + for filename in (os.listdir(sessDir) if os.path.exists(sessDir) else []): + path = os.path.join(sessDir, filename) + if not os.path.isfile(path): + continue + # Guess the content type based on the file's extension. Encoding + # will be ignored, although we should check for simple things like + # gzip'd or compressed files. + ctype, encoding = mimetypes.guess_type(path) + if ctype is None or encoding is not None: + # No guess could be made, or the file is encoded (compressed), so + # use a generic bag-of-bits type. + ctype = 'application/octet-stream' + maintype, subtype = ctype.split('/', 1) + if maintype == 'text': + fp = open(path) + # Note: we should handle calculating the charset + msg = MIMEText(fp.read(), _subtype=subtype) + fp.close() + elif maintype == 'image': + fp = open(path, 'rb') + msg = MIMEImage(fp.read(), _subtype=subtype) + fp.close() + elif maintype == 'audio': + fp = open(path, 'rb') + msg = MIMEAudio(fp.read(), _subtype=subtype) + fp.close() + else: + fp = open(path, 'rb') + msg = MIMEBase(maintype, subtype) + msg.set_payload(fp.read()) + fp.close() + # Encode the payload using Base64 + encoders.encode_base64(msg) + # Set the filename parameter + msg.add_header('Content-Disposition', 'attachment', filename=filename) + outer.attach(msg) + + # Now send or store the message + composed = outer.as_string() + if opts.output: + fp = open(opts.output, 'w') + fp.write(composed) + fp.close() + else: + s = smtplib.SMTP(opts.mailserver) + s.sendmail(opts.sender, opts.recipients, composed) + s.quit() + + +if __name__ == '__main__': + main() Propchange: lldb/trunk/utils/test/ras.py ------------------------------------------------------------------------------ svn:executable = * From gclayton at apple.com Tue Nov 16 16:09:25 2010 From: gclayton at apple.com (Greg Clayton) Date: Tue, 16 Nov 2010 22:09:25 -0000 Subject: [Lldb-commits] [lldb] r119396 - /lldb/trunk/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp Message-ID: <20101116220926.CAA2F2A6C12C@llvm.org> Author: gclayton Date: Tue Nov 16 16:09:25 2010 New Revision: 119396 URL: http://llvm.org/viewvc/llvm-project?rev=119396&view=rev Log: Use different qualifier enums on the request of a clang engineer. Modified: lldb/trunk/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp Modified: lldb/trunk/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp?rev=119396&r1=119395&r2=119396&view=diff ============================================================================== --- lldb/trunk/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp (original) +++ lldb/trunk/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp Tue Nov 16 16:09:25 2010 @@ -2335,9 +2335,9 @@ if (encoding_mask & Type::eEncodingIsPointerUID) { if (encoding_mask & (1u << Type::eEncodingIsConstUID)) - type_quals |= clang::DeclSpec::TQ_const; + type_quals |= clang::Qualifiers::Const; if (encoding_mask & (1u << Type::eEncodingIsVolatileUID)) - type_quals |= clang::DeclSpec::TQ_volatile; + type_quals |= clang::Qualifiers::Volatile; } } } From johnny.chen at apple.com Tue Nov 16 16:42:58 2010 From: johnny.chen at apple.com (Johnny Chen) Date: Tue, 16 Nov 2010 22:42:58 -0000 Subject: [Lldb-commits] [lldb] r119399 - /lldb/trunk/test/dotest.py Message-ID: <20101116224258.7668E2A6C12C@llvm.org> Author: johnny Date: Tue Nov 16 16:42:58 2010 New Revision: 119399 URL: http://llvm.org/viewvc/llvm-project?rev=119399&view=rev Log: Add an option '-# count' to run the specified test suite for a said number of times. This is not to be used during normal test suite run, but to be used to stress test specific test sequences repeatedly. Example: ./dotest.py -# 3 -v breakpoint_conditions will repeat the test suite 3 times for tests under the breakpoint_conditions directory. Modified: lldb/trunk/test/dotest.py Modified: lldb/trunk/test/dotest.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/dotest.py?rev=119399&r1=119398&r2=119399&view=diff ============================================================================== --- lldb/trunk/test/dotest.py (original) +++ lldb/trunk/test/dotest.py Tue Nov 16 16:42:58 2010 @@ -48,6 +48,9 @@ # The config file is optional. configFile = None +# Test suite repeat count. Can be overwritten with '-# count'. +count = 1 + # The dictionary as a result of sourcing configFile. config = {} @@ -122,6 +125,7 @@ -t : trace lldb command execution and result -v : do verbose mode of unittest framework -w : insert some wait time (currently 0.5 sec) between consecutive test cases +-# : Repeat the test suite for a specified number of times and: args : specify a list of directory names to search for test modules named after @@ -216,6 +220,7 @@ """ global configFile + global count global delay global filterspec global fs4all @@ -301,6 +306,13 @@ elif sys.argv[index].startswith('-w'): os.environ["LLDB_WAIT_BETWEEN_TEST_CASES"] = 'YES' index += 1 + elif sys.argv[index].startswith('-#'): + # Increment by 1 to fetch the repeat count argument. + index += 1 + if index >= len(sys.argv) or sys.argv[index].startswith('-'): + usage() + count = int(sys.argv[index]) + index += 1 else: print "Unknown option: ", sys.argv[index] usage() @@ -709,7 +721,7 @@ def __init__(self, *args): if LLDBTestResult.__singleton__: - raise "LLDBTestResult instantiated more than once" + raise Exception("LLDBTestResult instantiated more than once") super(LLDBTestResult, self).__init__(*args) LLDBTestResult.__singleton__ = self # Now put this singleton into the lldb module namespace. @@ -740,8 +752,12 @@ method() # Invoke the test runner. - result = unittest2.TextTestRunner(stream=sys.stderr, verbosity=verbose, - resultclass=LLDBTestResult).run(suite) + if count == 1: + result = unittest2.TextTestRunner(stream=sys.stderr, verbosity=verbose, + resultclass=LLDBTestResult).run(suite) + else: + for i in range(count): + result = unittest2.TextTestRunner(stream=sys.stderr, verbosity=verbose).run(suite) if sdir_has_content: From johnny.chen at apple.com Tue Nov 16 18:52:41 2010 From: johnny.chen at apple.com (Johnny Chen) Date: Wed, 17 Nov 2010 00:52:41 -0000 Subject: [Lldb-commits] [lldb] r119445 - in /lldb/trunk/test: lldbtest.py namespace/TestNamespace.py plugins/darwin.py Message-ID: <20101117005241.73DC02A6C12C@llvm.org> Author: johnny Date: Tue Nov 16 18:52:41 2010 New Revision: 119445 URL: http://llvm.org/viewvc/llvm-project?rev=119445&view=rev Log: Make the string matching for 'frame variable' more stringent with respect to output from clang and llvm-gcc compiled program; both generate the correct debug info with respect to the typedef scoped inside a namespace. Add a TestBase.getCompiler(self) method which returns the compiler in effect the test suite is now running with. Subclasses (like TestNamespace) can use it to distinguish among different compilers. Modified: lldb/trunk/test/lldbtest.py lldb/trunk/test/namespace/TestNamespace.py lldb/trunk/test/plugins/darwin.py Modified: lldb/trunk/test/lldbtest.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/lldbtest.py?rev=119445&r1=119444&r2=119445&view=diff ============================================================================== --- lldb/trunk/test/lldbtest.py (original) +++ lldb/trunk/test/lldbtest.py Tue Nov 16 18:52:41 2010 @@ -808,11 +808,16 @@ # End of while loop. + def getCompiler(self): + """Returns the compiler in effect the test suite is now running with.""" + module = __import__(sys.platform) + return module.getCompiler() + def getRunSpec(self): """Environment variable spec to run this test again, invoked from within dumpSessionInfo().""" module = __import__(sys.platform) - return module.getRunSpec() + return module.getRunSpec() def buildDefault(self, architecture=None, compiler=None, dictionary=None): """Platform specific way to build the default binaries.""" Modified: lldb/trunk/test/namespace/TestNamespace.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/namespace/TestNamespace.py?rev=119445&r1=119444&r2=119445&view=diff ============================================================================== --- lldb/trunk/test/namespace/TestNamespace.py (original) +++ lldb/trunk/test/namespace/TestNamespace.py Tue Nov 16 18:52:41 2010 @@ -54,17 +54,18 @@ substrs = ['state is stopped', 'stop reason = breakpoint']) - # rdar://problem/8668740 - # 'frame variable' output for namespace variables look wrong - # (lldb) frame variable - # (int) a = 12 - # (A::B::uint_t) anon_uint = 0 - # (A::B::uint_t) a_uint = 1 - # (A::B::uint_t) b_uint = 2 - # (A::B::uint_t) y_uint = 3 - # (lldb) + # On Mac OS X, gcc 4.2 emits the wrong debug info with respect to types. + slist = ['(int) a = 12', 'anon_uint', 'a_uint', 'b_uint', 'y_uint'] + if sys.platform.startswith("darwin") and self.getCompiler() in ['clang', 'llvm-gcc']: + slist = ['(int) a = 12', + '(my_uint_t) anon_uint = 0', + '(A::uint_t) a_uint = 1', + '(A::B::uint_t) b_uint = 2', + '(Y::uint_t) y_uint = 3'] + + # 'frame variable' displays the local variables with type information. self.expect('frame variable', VARIABLES_DISPLAYED_CORRECTLY, - substrs = ['']) + substrs = slist) # 'frame variable' with basename 'i' should work. self.expect("frame variable -c -G i", Modified: lldb/trunk/test/plugins/darwin.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/plugins/darwin.py?rev=119445&r1=119444&r2=119445&view=diff ============================================================================== --- lldb/trunk/test/plugins/darwin.py (original) +++ lldb/trunk/test/plugins/darwin.py Tue Nov 16 18:52:41 2010 @@ -17,6 +17,10 @@ #print "Hello, darwin plugin!" +def getCompiler(): + """Returns the compiler in effect the test suite is now running with.""" + return os.environ["CC"] if "CC" in os.environ else "" + def getRunSpec(): """Environment variable spec to run this test again, invoked from within dumpSessionInfo().""" From jingham at apple.com Tue Nov 16 20:32:00 2010 From: jingham at apple.com (Jim Ingham) Date: Wed, 17 Nov 2010 02:32:00 -0000 Subject: [Lldb-commits] [lldb] r119453 - in /lldb/trunk: include/lldb/Target/ lldb.xcodeproj/ source/Expression/ source/Plugins/Process/MacOSX-User/source/ source/Plugins/Process/gdb-remote/ source/Target/ test/foundation/ Message-ID: <20101117023200.940202A6C12C@llvm.org> Author: jingham Date: Tue Nov 16 20:32:00 2010 New Revision: 119453 URL: http://llvm.org/viewvc/llvm-project?rev=119453&view=rev Log: Added an "Interrupted" bit to the ProcessEventData. Halt now generates an event with the Interrupted bit set. Process::HandlePrivateEvent ignores Interrupted events. DoHalt is changed to ensure that the stop even is processed, and an event with the Interrupted event is posted. Finally ClangFunction is rationalized to use this facility so the that Halt is handled more deterministically. Modified: lldb/trunk/include/lldb/Target/Process.h lldb/trunk/lldb.xcodeproj/project.pbxproj lldb/trunk/source/Expression/ClangFunction.cpp lldb/trunk/source/Plugins/Process/MacOSX-User/source/ProcessMacOSX.cpp lldb/trunk/source/Plugins/Process/MacOSX-User/source/ProcessMacOSX.h lldb/trunk/source/Plugins/Process/gdb-remote/GDBRemoteCommunication.cpp lldb/trunk/source/Plugins/Process/gdb-remote/GDBRemoteCommunication.h lldb/trunk/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp lldb/trunk/source/Plugins/Process/gdb-remote/ProcessGDBRemote.h lldb/trunk/source/Target/Process.cpp lldb/trunk/test/foundation/main.m Modified: lldb/trunk/include/lldb/Target/Process.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/Target/Process.h?rev=119453&r1=119452&r2=119453&view=diff ============================================================================== --- lldb/trunk/include/lldb/Target/Process.h (original) +++ lldb/trunk/include/lldb/Target/Process.h Tue Nov 16 20:32:00 2010 @@ -273,6 +273,8 @@ class ProcessEventData : public EventData { + friend class Process; + public: ProcessEventData (); ProcessEventData (const lldb::ProcessSP &process, lldb::StateType state); @@ -286,13 +288,25 @@ GetFlavor () const; const lldb::ProcessSP & - GetProcessSP() const; - + GetProcessSP() const + { + return m_process_sp; + } lldb::StateType - GetState() const; - + GetState() const + { + return m_state; + } bool - GetRestarted () const; + GetRestarted () const + { + return m_restarted; + } + bool + GetInterrupted () const + { + return m_interrupted; + } virtual void Dump (Stream *s) const; @@ -316,20 +330,37 @@ SetRestartedInEvent (Event *event_ptr, bool new_value); static bool + GetInterruptedFromEvent (const Event *event_ptr); + + static void + SetInterruptedInEvent (Event *event_ptr, bool new_value); + + static bool SetUpdateStateOnRemoval (Event *event_ptr); private: void - SetUpdateStateOnRemoval(); - + SetUpdateStateOnRemoval() + { + m_update_state = true; + } void - SetRestarted (bool new_value); + SetRestarted (bool new_value) + { + m_restarted = new_value; + } + void + SetInterrupted (bool new_value) + { + m_interrupted = new_value; + } lldb::ProcessSP m_process_sp; lldb::StateType m_state; bool m_restarted; // For "eStateStopped" events, this is true if the target was automatically restarted. bool m_update_state; + bool m_interrupted; DISALLOW_COPY_AND_ASSIGN (ProcessEventData); }; @@ -703,7 +734,7 @@ /// @see Thread:Step() /// @see Thread:Suspend() //------------------------------------------------------------------ - virtual Error + Error Resume (); //------------------------------------------------------------------ @@ -711,11 +742,15 @@ /// /// This function is not meant to be overridden by Process /// subclasses. + /// If the process is successfully halted, a eStateStopped + /// process event with GetInterrupted will be broadcast. If false, we will + /// halt the process with no events generated by the halt. /// /// @return - /// Returns an error object. + /// Returns an error object. If the error is empty, the process is halted. + /// otherwise the halt has failed. //------------------------------------------------------------------ - virtual Error + Error Halt (); //------------------------------------------------------------------ @@ -727,7 +762,7 @@ /// @return /// Returns an error object. //------------------------------------------------------------------ - virtual Error + Error Detach (); //------------------------------------------------------------------ @@ -740,7 +775,7 @@ /// @return /// Returns an error object. //------------------------------------------------------------------ - virtual Error + Error Destroy(); //------------------------------------------------------------------ @@ -752,7 +787,7 @@ /// @return /// Returns an error object. //------------------------------------------------------------------ - virtual Error + Error Signal (int signal); virtual UnixSignals & @@ -972,12 +1007,19 @@ //------------------------------------------------------------------ /// Halts a running process. /// + /// DoHalt should consume any process events that were delivered in the + /// process of implementing the halt. + /// + /// @param[out] caused_stop + /// If true, then this Halt caused the stop, otherwise, the process was + /// already stopped. + /// /// @return /// Returns \b true if the process successfully halts, \b false /// otherwise. //------------------------------------------------------------------ virtual Error - DoHalt () = 0; + DoHalt (bool &caused_stop) = 0; //------------------------------------------------------------------ /// Called after halting a process. Modified: lldb/trunk/lldb.xcodeproj/project.pbxproj URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/lldb.xcodeproj/project.pbxproj?rev=119453&r1=119452&r2=119453&view=diff ============================================================================== --- lldb/trunk/lldb.xcodeproj/project.pbxproj (original) +++ lldb/trunk/lldb.xcodeproj/project.pbxproj Tue Nov 16 20:32:00 2010 @@ -2942,7 +2942,7 @@ GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_HIDDEN_VIRTUAL_FUNCTIONS = YES; GCC_WARN_UNUSED_VARIABLE = YES; - ONLY_ACTIVE_ARCH = NO; + ONLY_ACTIVE_ARCH = YES; PREBINDING = NO; VALID_ARCHS = "x86_64 i386"; }; Modified: lldb/trunk/source/Expression/ClangFunction.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Expression/ClangFunction.cpp?rev=119453&r1=119452&r2=119453&view=diff ============================================================================== --- lldb/trunk/source/Expression/ClangFunction.cpp (original) +++ lldb/trunk/source/Expression/ClangFunction.cpp Tue Nov 16 20:32:00 2010 @@ -26,6 +26,7 @@ #include "lldb/Expression/ClangFunction.h" #include "lldb/Symbol/Type.h" #include "lldb/Core/DataExtractor.h" +#include "lldb/Core/State.h" #include "lldb/Core/ValueObject.h" #include "lldb/Core/ValueObjectList.h" #include "lldb/Interpreter/CommandReturnObject.h" @@ -509,18 +510,25 @@ if (call_plan_sp == NULL) return eExecutionSetupError; -//#define SINGLE_STEP_EXPRESSIONS - -#ifdef SINGLE_STEP_EXPRESSIONS - return eExecutionInterrupted; -#else call_plan_sp->SetPrivate(true); exe_ctx.thread->QueueThreadPlan(call_plan_sp, true); -#endif + + Listener listener("ClangFunction temporary listener"); + exe_ctx.process->HijackProcessEvents(&listener); + + Error resume_error = exe_ctx.process->Resume (); + if (!resume_error.Success()) + { + errors.Printf("Error resuming inferior: \"%s\".\n", resume_error.AsCString()); + exe_ctx.process->RestoreProcessEvents(); + return eExecutionSetupError; + } // We need to call the function synchronously, so spin waiting for it to return. // If we get interrupted while executing, we're going to lose our context, and // won't be able to gather the result at this point. + // We set the timeout AFTER the resume, since the resume takes some time and we + // don't want to charge that to the timeout. TimeValue* timeout_ptr = NULL; TimeValue real_timeout; @@ -532,18 +540,7 @@ timeout_ptr = &real_timeout; } - Listener listener("ClangFunction temporary listener"); - exe_ctx.process->HijackProcessEvents(&listener); - - Error resume_error = exe_ctx.process->Resume (); - if (!resume_error.Success()) - { - errors.Printf("Error resuming inferior: \"%s\".\n", resume_error.AsCString()); - return eExecutionSetupError; - } - lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP)); - while (1) { lldb::EventSP event_sp; @@ -551,12 +548,11 @@ // Now wait for the process to stop again: bool got_event = listener.WaitForEvent (timeout_ptr, event_sp); - if (!got_event && !call_plan_sp->IsPlanComplete()) + if (!got_event) { // Right now this is the only way to tell we've timed out... // We should interrupt the process here... // Not really sure what to do if Halt fails here... - log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP); if (log) if (try_all_threads) log->Printf ("Running function with timeout: %d timed out, trying with all threads enabled.", @@ -568,45 +564,54 @@ if (exe_ctx.process->Halt().Success()) { timeout_ptr = NULL; - - got_event = listener.WaitForEvent (timeout_ptr, event_sp); - stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get()); - - if (stop_state == lldb::eStateInvalid) - { - errors.Printf ("Got an invalid stop state after halt."); - } - else if (stop_state != lldb::eStateStopped) - { - StreamString s; - event_sp->Dump (&s); + if (log) + log->Printf ("Halt succeeded."); - errors.Printf("Didn't get a stopped event after Halting the target, got: \"%s\"", s.GetData()); - } + // Between the time that we got the timeout and the time we halted, but target + // might have actually completed the plan. If so, we're done. Note, I call WFE here with a short + // timeout to + got_event = listener.WaitForEvent(NULL, event_sp); - if (try_all_threads) + if (got_event) { - // Between the time that we got the timeout and the time we halted, but target - // might have actually completed the plan. If so, we're done. + stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get()); + if (log) + { + log->Printf ("Stopped with event: %s", StateAsCString(stop_state)); + if (stop_state == lldb::eStateStopped && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get())) + log->Printf (" Event was the Halt interruption event."); + } + if (exe_ctx.thread->IsThreadPlanDone (call_plan_sp.get())) { + if (log) + log->Printf ("Even though we timed out, the call plan was done. Exiting wait loop."); return_value = eExecutionCompleted; break; } - - call_plan_ptr->SetStopOthers (false); - exe_ctx.process->Resume(); - continue; - } - else - { - exe_ctx.process->RestoreProcessEvents (); - return eExecutionInterrupted; + + if (try_all_threads) + { + + call_plan_ptr->SetStopOthers (false); + if (log) + log->Printf ("About to resume."); + + exe_ctx.process->Resume(); + continue; + } + else + { + exe_ctx.process->RestoreProcessEvents (); + return eExecutionInterrupted; + } } } } stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get()); + if (log) + log->Printf("Got event: %s.", StateAsCString(stop_state)); if (stop_state == lldb::eStateRunning || stop_state == lldb::eStateStepping) continue; @@ -623,7 +628,6 @@ } else { - log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP); if (log) { StreamString s; @@ -690,7 +694,6 @@ event_explanation = ts.GetData(); } while (0); - log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP); if (log) log->Printf("Execution interrupted: %s %s", s.GetData(), event_explanation); } Modified: lldb/trunk/source/Plugins/Process/MacOSX-User/source/ProcessMacOSX.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Plugins/Process/MacOSX-User/source/ProcessMacOSX.cpp?rev=119453&r1=119452&r2=119453&view=diff ============================================================================== --- lldb/trunk/source/Plugins/Process/MacOSX-User/source/ProcessMacOSX.cpp (original) +++ lldb/trunk/source/Plugins/Process/MacOSX-User/source/ProcessMacOSX.cpp Tue Nov 16 20:32:00 2010 @@ -674,7 +674,7 @@ } Error -ProcessMacOSX::DoHalt () +ProcessMacOSX::DoHalt (bool &caused_stop) { return Signal (SIGSTOP); } @@ -718,8 +718,10 @@ // Pause the Private State Thread so it doesn't intercept the events we need to wait for. PausePrivateStateThread(); - - m_thread_list.DiscardThreadPlans(); + // I don't think this is right. Halt should just stop the process, and then whoever called halt should + // arrange whatever they need to with the thread plans. + + //m_thread_list.DiscardThreadPlans(); // First jettison all the current thread plans, since we want to make sure it // really just stops. Modified: lldb/trunk/source/Plugins/Process/MacOSX-User/source/ProcessMacOSX.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Plugins/Process/MacOSX-User/source/ProcessMacOSX.h?rev=119453&r1=119452&r2=119453&view=diff ============================================================================== --- lldb/trunk/source/Plugins/Process/MacOSX-User/source/ProcessMacOSX.h (original) +++ lldb/trunk/source/Plugins/Process/MacOSX-User/source/ProcessMacOSX.h Tue Nov 16 20:32:00 2010 @@ -144,7 +144,7 @@ DoResume (); virtual lldb_private::Error - DoHalt (); + DoHalt (bool &caused_stop); virtual lldb_private::Error WillDetach (); Modified: lldb/trunk/source/Plugins/Process/gdb-remote/GDBRemoteCommunication.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Plugins/Process/gdb-remote/GDBRemoteCommunication.cpp?rev=119453&r1=119452&r2=119453&view=diff ============================================================================== --- lldb/trunk/source/Plugins/Process/gdb-remote/GDBRemoteCommunication.cpp (original) +++ lldb/trunk/source/Plugins/Process/gdb-remote/GDBRemoteCommunication.cpp Tue Nov 16 20:32:00 2010 @@ -199,14 +199,14 @@ log->Printf ("GDBRemoteCommunication::%s ()", __FUNCTION__); Mutex::Locker locker(m_sequence_mutex); - m_is_running.SetValue (true, eBroadcastNever); - // ScopedValueChanger restore_running_to_false (m_is_running, false); StateType state = eStateRunning; if (SendPacket(payload, packet_length) == 0) state = eStateInvalid; + m_is_running.SetValue (true, eBroadcastAlways); + while (state == eStateRunning) { log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS); @@ -856,3 +856,19 @@ } return false; } + +bool +GDBRemoteCommunication::WaitForIsRunning (uint32_t timeout_sec) +{ + TimeValue timeout; + if (timeout_sec) + { + timeout = TimeValue::Now(); + timeout.OffsetWithSeconds (timeout_sec); + } + bool timed_out = false; + m_is_running.WaitForValueEqualTo (true, &timeout, &timed_out); + return timed_out; +} + + Modified: lldb/trunk/source/Plugins/Process/gdb-remote/GDBRemoteCommunication.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Plugins/Process/gdb-remote/GDBRemoteCommunication.h?rev=119453&r1=119452&r2=119453&view=diff ============================================================================== --- lldb/trunk/source/Plugins/Process/gdb-remote/GDBRemoteCommunication.h (original) +++ lldb/trunk/source/Plugins/Process/gdb-remote/GDBRemoteCommunication.h Tue Nov 16 20:32:00 2010 @@ -203,6 +203,9 @@ } bool + WaitForIsRunning (uint32_t timeout_sec); + + bool GetHostInfo (uint32_t timeout_seconds); bool Modified: lldb/trunk/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp?rev=119453&r1=119452&r2=119453&view=diff ============================================================================== --- lldb/trunk/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp (original) +++ lldb/trunk/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp Tue Nov 16 20:32:00 2010 @@ -895,9 +895,15 @@ Error ProcessGDBRemote::DoResume () { + Error error; ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::Resume()"); m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (m_continue_packet.GetData(), m_continue_packet.GetSize())); - return Error(); + const uint32_t timedout_sec = 1; + if (m_gdb_comm.WaitForIsRunning (timedout_sec)) + { + error.SetErrorString("Resume timed out."); + } + return error; } size_t @@ -1115,20 +1121,47 @@ } Error -ProcessGDBRemote::DoHalt () +ProcessGDBRemote::DoHalt (bool &caused_stop) { Error error; + caused_stop = false; + if (m_gdb_comm.IsRunning()) { + PausePrivateStateThread(); bool timed_out = false; Mutex::Locker locker; - if (!m_gdb_comm.SendInterrupt (locker, 2, &timed_out)) + + if (m_gdb_comm.SendInterrupt (locker, 2, &timed_out)) + { + EventSP event_sp; + TimeValue timeout_time; + timeout_time = TimeValue::Now(); + timeout_time.OffsetWithSeconds(2); + + StateType state = WaitForStateChangedEventsPrivate (&timeout_time, event_sp); + + if (!StateIsStoppedState (state)) + { + LogSP log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); + if (log) + log->Printf("ProcessGDBRemote::DoHalt() failed to stop after sending interrupt"); + error.SetErrorString ("Did not get stopped event after interrupt succeeded."); + } + else + caused_stop = true; + } + else { if (timed_out) error.SetErrorString("timed out sending interrupt packet"); else error.SetErrorString("unknown error sending interrupt packet"); } + + // Resume the private state thread at this point. + ResumePrivateStateThread(); + } return error; } @@ -2082,6 +2115,9 @@ if (listener.WaitForEvent (NULL, event_sp)) { const uint32_t event_type = event_sp->GetType(); + if (log) + log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) Got an event of type: %d...", __FUNCTION__, arg, process->GetID(), event_type); + switch (event_type) { case eBroadcastBitAsyncContinue: Modified: lldb/trunk/source/Plugins/Process/gdb-remote/ProcessGDBRemote.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Plugins/Process/gdb-remote/ProcessGDBRemote.h?rev=119453&r1=119452&r2=119453&view=diff ============================================================================== --- lldb/trunk/source/Plugins/Process/gdb-remote/ProcessGDBRemote.h (original) +++ lldb/trunk/source/Plugins/Process/gdb-remote/ProcessGDBRemote.h Tue Nov 16 20:32:00 2010 @@ -138,7 +138,7 @@ DoResume (); virtual lldb_private::Error - DoHalt (); + DoHalt (bool &caused_stop); virtual lldb_private::Error WillDetach (); Modified: lldb/trunk/source/Target/Process.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Target/Process.cpp?rev=119453&r1=119452&r2=119453&view=diff ============================================================================== --- lldb/trunk/source/Target/Process.cpp (original) +++ lldb/trunk/source/Target/Process.cpp Tue Nov 16 20:32:00 2010 @@ -1438,9 +1438,19 @@ if (error.Success()) { - error = DoHalt(); + bool caused_stop; + error = DoHalt(caused_stop); if (error.Success()) + { DidHalt(); + if (caused_stop) + { + ProcessEventData *new_data = new ProcessEventData (GetTarget().GetProcessSP(), eStateStopped); + new_data->SetInterrupted(true); + BroadcastEvent (eBroadcastBitStateChanged, new_data); + } + } + } return error; } @@ -1591,9 +1601,14 @@ // If we are going to stop, then we always broadcast the event. // If we aren't going to stop, let the thread plans decide if we're going to report this event. // If no thread has an opinion, we don't report it. - if (state != eStateInvalid) + if (ProcessEventData::GetInterruptedFromEvent (event_ptr)) + { + if (log) + log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s", event_ptr, StateAsCString(state)); + return true; + } + else { - RefreshStateAfterStop (); if (m_thread_list.ShouldStop (event_ptr) == false) @@ -1610,7 +1625,7 @@ } if (log) - log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process", event_ptr, StateAsCString(state)); + log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state)); Resume (); } else @@ -1785,7 +1800,13 @@ control_only = false; break; } + + log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS); + if (log) + log->Printf ("Process::%s (arg = %p, pid = %i) got a control event: %d", __FUNCTION__, this, GetID(), event_sp->GetType()); + m_private_state_control_wait.SetValue (true, eBroadcastAlways); + continue; } @@ -1799,7 +1820,13 @@ if (internal_state == eStateInvalid || internal_state == eStateExited || internal_state == eStateDetached ) + { + log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS); + if (log) + log->Printf ("Process::%s (arg = %p, pid = %i) about to exit with internal state %s...", __FUNCTION__, this, GetID(), StateAsCString(internal_state)); + break; + } } // Verify log is still enabled before attempting to write to it... @@ -1820,7 +1847,8 @@ m_process_sp (), m_state (eStateInvalid), m_restarted (false), - m_update_state (false) + m_update_state (false), + m_interrupted (false) { } @@ -1829,7 +1857,8 @@ m_process_sp (process_sp), m_state (state), m_restarted (false), - m_update_state (false) + m_update_state (false), + m_interrupted (false) { } @@ -1850,30 +1879,6 @@ return ProcessEventData::GetFlavorString (); } -const ProcessSP & -Process::ProcessEventData::GetProcessSP () const -{ - return m_process_sp; -} - -StateType -Process::ProcessEventData::GetState () const -{ - return m_state; -} - -bool -Process::ProcessEventData::GetRestarted () const -{ - return m_restarted; -} - -void -Process::ProcessEventData::SetRestarted (bool new_value) -{ - m_restarted = new_value; -} - void Process::ProcessEventData::DoOnRemoval (Event *event_ptr) { @@ -1974,6 +1979,24 @@ } bool +Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr) +{ + const ProcessEventData *data = GetEventDataFromEvent (event_ptr); + if (data == NULL) + return false; + else + return data->GetInterrupted (); +} + +void +Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value) +{ + ProcessEventData *data = const_cast(GetEventDataFromEvent (event_ptr)); + if (data != NULL) + data->SetInterrupted(new_value); +} + +bool Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr) { ProcessEventData *data = const_cast(GetEventDataFromEvent (event_ptr)); @@ -1985,12 +2008,6 @@ return false; } -void -Process::ProcessEventData::SetUpdateStateOnRemoval() -{ - m_update_state = true; -} - Target * Process::CalculateTarget () { Modified: lldb/trunk/test/foundation/main.m URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/foundation/main.m?rev=119453&r1=119452&r2=119453&view=diff ============================================================================== --- lldb/trunk/test/foundation/main.m (original) +++ lldb/trunk/test/foundation/main.m Tue Nov 16 20:32:00 2010 @@ -1,13 +1,20 @@ #import +#include @interface MyString : NSObject { NSString *str; NSDate *date; + BOOL _desc_pauses; } + + at property BOOL descriptionPauses; + - (id)initWithNSString:(NSString *)string; @end @implementation MyString + at synthesize descriptionPauses = _desc_pauses; + - (id)initWithNSString:(NSString *)string { if (self = [super init]) @@ -15,6 +22,7 @@ str = [NSString stringWithString:string]; date = [NSDate date]; } + self.descriptionPauses = NO; return self; } @@ -27,6 +35,12 @@ - (NSString *)description { + if (self.descriptionPauses) + { + printf ("\nAbout to sleep.\n"); + usleep(100000); + } + return [str stringByAppendingFormat:@" with timestamp: %@", date]; } @end @@ -40,6 +54,8 @@ MyString *my = [[MyString alloc] initWithNSString:str]; NSLog(@"MyString instance: %@", [my description]); + my.descriptionPauses = YES; + id str_id = str; // Set break point at this line. SEL sel = @selector(length); BOOL responds = [str respondsToSelector:sel]; From jingham at apple.com Wed Nov 17 14:19:50 2010 From: jingham at apple.com (Jim Ingham) Date: Wed, 17 Nov 2010 20:19:50 -0000 Subject: [Lldb-commits] [lldb] r119549 - in /lldb/trunk: include/lldb/Target/ThreadPlanTracer.h source/Target/ThreadPlanTracer.cpp Message-ID: <20101117201950.4A9032A6C12C@llvm.org> Author: jingham Date: Wed Nov 17 14:19:50 2010 New Revision: 119549 URL: http://llvm.org/viewvc/llvm-project?rev=119549&view=rev Log: Add a ThreadPlanAssemblyTracer that takes just a thread (since that's how we call it from ThreadPlanBase...) Modified: lldb/trunk/include/lldb/Target/ThreadPlanTracer.h lldb/trunk/source/Target/ThreadPlanTracer.cpp Modified: lldb/trunk/include/lldb/Target/ThreadPlanTracer.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/Target/ThreadPlanTracer.h?rev=119549&r1=119548&r2=119549&view=diff ============================================================================== --- lldb/trunk/include/lldb/Target/ThreadPlanTracer.h (original) +++ lldb/trunk/include/lldb/Target/ThreadPlanTracer.h Wed Nov 17 14:19:50 2010 @@ -104,11 +104,14 @@ { public: ThreadPlanAssemblyTracer (Thread &thread, lldb::StreamSP &stream_sp); + ThreadPlanAssemblyTracer (Thread &thread); virtual ~ThreadPlanAssemblyTracer (); virtual void TracingStarted (); virtual void TracingEnded (); virtual void Log(); private: + void InitializeTracer(); + Process &m_process; Target &m_target; Disassembler *m_disassembler; Modified: lldb/trunk/source/Target/ThreadPlanTracer.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Target/ThreadPlanTracer.cpp?rev=119549&r1=119548&r2=119549&view=diff ============================================================================== --- lldb/trunk/source/Target/ThreadPlanTracer.cpp (original) +++ lldb/trunk/source/Target/ThreadPlanTracer.cpp Wed Nov 17 14:19:50 2010 @@ -91,7 +91,21 @@ m_process(thread.GetProcess()), m_target(thread.GetProcess().GetTarget()) { - Process &process = thread.GetProcess(); + InitializeTracer (); +} + +ThreadPlanAssemblyTracer::ThreadPlanAssemblyTracer (Thread &thread) : + ThreadPlanTracer (thread), + m_process(thread.GetProcess()), + m_target(thread.GetProcess().GetTarget()) +{ + InitializeTracer (); +} + +void +ThreadPlanAssemblyTracer::InitializeTracer() +{ + Process &process = m_thread.GetProcess(); Target &target = process.GetTarget(); ArchSpec arch(target.GetArchitecture()); From jingham at apple.com Wed Nov 17 14:40:29 2010 From: jingham at apple.com (Jim Ingham) Date: Wed, 17 Nov 2010 20:40:29 -0000 Subject: [Lldb-commits] [lldb] r119553 - /lldb/trunk/source/Target/ThreadPlanTracer.cpp Message-ID: <20101117204029.31F722A6C12C@llvm.org> Author: jingham Date: Wed Nov 17 14:40:29 2010 New Revision: 119553 URL: http://llvm.org/viewvc/llvm-project?rev=119553&view=rev Log: Add a missing newline to the ThreadPlanAssemblyTracer output. Modified: lldb/trunk/source/Target/ThreadPlanTracer.cpp Modified: lldb/trunk/source/Target/ThreadPlanTracer.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Target/ThreadPlanTracer.cpp?rev=119553&r1=119552&r2=119553&view=diff ============================================================================== --- lldb/trunk/source/Target/ThreadPlanTracer.cpp (original) +++ lldb/trunk/source/Target/ThreadPlanTracer.cpp Wed Nov 17 14:40:29 2010 @@ -292,5 +292,5 @@ } } - stream->Printf ("Single-step: %s", desc.GetString().c_str()); + stream->Printf ("Single-step: %s\n", desc.GetString().c_str()); } From scallanan at apple.com Wed Nov 17 17:00:07 2010 From: scallanan at apple.com (Sean Callanan) Date: Wed, 17 Nov 2010 23:00:07 -0000 Subject: [Lldb-commits] [lldb] r119581 - /lldb/trunk/source/Expression/ClangExpressionDeclMap.cpp Message-ID: <20101117230007.92A2E2A6C12C@llvm.org> Author: spyffe Date: Wed Nov 17 17:00:07 2010 New Revision: 119581 URL: http://llvm.org/viewvc/llvm-project?rev=119581&view=rev Log: Whitespace fix. Modified: lldb/trunk/source/Expression/ClangExpressionDeclMap.cpp Modified: lldb/trunk/source/Expression/ClangExpressionDeclMap.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Expression/ClangExpressionDeclMap.cpp?rev=119581&r1=119580&r2=119581&view=diff ============================================================================== --- lldb/trunk/source/Expression/ClangExpressionDeclMap.cpp (original) +++ lldb/trunk/source/Expression/ClangExpressionDeclMap.cpp Wed Nov 17 17:00:07 2010 @@ -1002,7 +1002,6 @@ // doesn't start with our phony prefix of '$' if (name_unique_cstr[0] != '$') { - Variable *var = FindVariableInScope(*m_exe_ctx.frame, name); // If we found a variable in scope, no need to pull up function names From scallanan at apple.com Wed Nov 17 17:00:36 2010 From: scallanan at apple.com (Sean Callanan) Date: Wed, 17 Nov 2010 23:00:36 -0000 Subject: [Lldb-commits] [lldb] r119582 - in /lldb/trunk: include/lldb/Expression/IRForTarget.h source/Expression/IRForTarget.cpp Message-ID: <20101117230036.AB84A2A6C12C@llvm.org> Author: spyffe Date: Wed Nov 17 17:00:36 2010 New Revision: 119582 URL: http://llvm.org/viewvc/llvm-project?rev=119582&view=rev Log: Added support for constant strings of the form @"this-is-a-string". They are replaced with calls to the CoreFoundation function CFStringCreateWithBytes() by a portion of the IRForTarget pass. Modified: lldb/trunk/include/lldb/Expression/IRForTarget.h lldb/trunk/source/Expression/IRForTarget.cpp Modified: lldb/trunk/include/lldb/Expression/IRForTarget.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/Expression/IRForTarget.h?rev=119582&r1=119581&r2=119582&view=diff ============================================================================== --- lldb/trunk/include/lldb/Expression/IRForTarget.h (original) +++ lldb/trunk/include/lldb/Expression/IRForTarget.h Wed Nov 17 17:00:36 2010 @@ -17,6 +17,7 @@ class CallInst; class Constant; class Function; + class GlobalVariable; class Instruction; class Module; class Value; @@ -112,6 +113,54 @@ //------------------------------------------------------------------ bool createResultVariable(llvm::Module &M, llvm::Function &F); + + //------------------------------------------------------------------ + /// A function-level pass to find Objective-C constant strings and + /// transform them to calls to CFStringCreateWithBytes. + //------------------------------------------------------------------ + + //------------------------------------------------------------------ + /// Rewrite a single Objective-C constant string. + /// + /// @param[in] M + /// The module currently being processed. + /// + /// @param[in] NSStr + /// The constant NSString to be transformed + /// + /// @param[in] CStr + /// The constant C string inside the NSString. This will be + /// passed as the bytes argument to CFStringCreateWithBytes. + /// + /// @param[in] FirstEntryInstruction + /// An instruction early in the execution of the function. + /// When this function synthesizes a call to + /// CFStringCreateWithBytes, it places the call before this + /// instruction. The instruction should come before all + /// uses of the NSString. + /// + /// @return + /// True on success; false otherwise + //------------------------------------------------------------------ + bool rewriteObjCConstString(llvm::Module &M, + llvm::GlobalVariable *NSStr, + llvm::GlobalVariable *CStr, + llvm::Instruction *FirstEntryInstruction); + + //------------------------------------------------------------------ + /// The top-level pass implementation + /// + /// @param[in] M + /// The module currently being processed. + /// + /// @param[in] F + /// The function currently being processed. + /// + /// @return + /// True on success; false otherwise + //------------------------------------------------------------------ + bool rewriteObjCConstStrings(llvm::Module &M, + llvm::Function &F); //------------------------------------------------------------------ /// A basic block-level pass to find all Objective-C method calls and @@ -323,11 +372,40 @@ llvm::Function &F); /// Flags - bool m_resolve_vars; ///< True if external variable references and persistent variable references should be resolved + bool m_resolve_vars; ///< True if external variable references and persistent variable references should be resolved + + std::string m_func_name; ///< The name of the function to translate + lldb_private::ClangExpressionDeclMap *m_decl_map; ///< The DeclMap containing the Decls + llvm::Constant *m_CFStringCreateWithBytes; ///< The address of the function CFStringCreateWithBytes, cast to the appropriate function pointer type + llvm::Constant *m_sel_registerName; ///< The address of the function sel_registerName, cast to the appropriate function pointer type - std::string m_func_name; ///< The name of the function to translate - lldb_private::ClangExpressionDeclMap *m_decl_map; ///< The DeclMap containing the Decls - llvm::Constant *m_sel_registerName; ///< The address of the function sel_registerName, cast to the appropriate function pointer type +private: + //------------------------------------------------------------------ + /// UnfoldConstant operates on a constant [Old] which has just been + /// replaced with a value [New]. We assume that new_value has + /// been properly placed early in the function, in front of the + /// first instruction in the entry basic block + /// [FirstEntryInstruction]. + /// + /// UnfoldConstant reads through the uses of Old and replaces Old + /// in those uses with New. Where those uses are constants, the + /// function generates new instructions to compute the result of the + /// new, non-constant expression and places them before + /// FirstEntryInstruction. These instructions replace the constant + /// uses, so UnfoldConstant calls itself recursively for those. + /// + /// @param[in] M + /// The module currently being processed. + /// + /// @param[in] F + /// The function currently being processed. + /// + /// @return + /// True on success; false otherwise + //------------------------------------------------------------------ + static bool UnfoldConstant(llvm::Constant *Old, + llvm::Value *New, + llvm::Instruction *FirstEntryInstruction); }; #endif Modified: lldb/trunk/source/Expression/IRForTarget.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Expression/IRForTarget.cpp?rev=119582&r1=119581&r2=119582&view=diff ============================================================================== --- lldb/trunk/source/Expression/IRForTarget.cpp (original) +++ lldb/trunk/source/Expression/IRForTarget.cpp Wed Nov 17 17:00:36 2010 @@ -37,6 +37,7 @@ const char *func_name) : ModulePass(ID), m_decl_map(decl_map), + m_CFStringCreateWithBytes(NULL), m_sel_registerName(NULL), m_func_name(func_name), m_resolve_vars(resolve_vars) @@ -256,6 +257,295 @@ return true; } +static void DebugUsers(lldb::LogSP &log, Value *V, uint8_t depth) +{ + if (!depth) + return; + + depth--; + + log->Printf(" ", V->getNumUses()); + + for (Value::use_iterator ui = V->use_begin(), ue = V->use_end(); + ui != ue; + ++ui) + { + log->Printf(" %s", *ui, PrintValue(*ui).c_str()); + DebugUsers(log, *ui, depth); + } + + log->Printf(" "); +} + +bool +IRForTarget::rewriteObjCConstString(llvm::Module &M, + llvm::GlobalVariable *NSStr, + llvm::GlobalVariable *CStr, + Instruction *FirstEntryInstruction) +{ + lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); + + const Type *i8_ptr_ty = Type::getInt8PtrTy(M.getContext()); + const IntegerType *intptr_ty = Type::getIntNTy(M.getContext(), + (M.getPointerSize() == Module::Pointer64) ? 64 : 32); + const Type *i32_ty = Type::getInt32Ty(M.getContext()); + const Type *i8_ty = Type::getInt8Ty(M.getContext()); + + if (!m_CFStringCreateWithBytes) + { + lldb::addr_t CFStringCreateWithBytes_addr; + + static lldb_private::ConstString g_CFStringCreateWithBytes_str ("CFStringCreateWithBytes"); + + if (!m_decl_map->GetFunctionAddress (g_CFStringCreateWithBytes_str, CFStringCreateWithBytes_addr)) + { + if (log) + log->PutCString("Couldn't find CFStringCreateWithBytes in the target"); + + return false; + } + + if (log) + log->Printf("Found CFStringCreateWithBytes at 0x%llx", CFStringCreateWithBytes_addr); + + // Build the function type: + // + // CFStringRef CFStringCreateWithBytes ( + // CFAllocatorRef alloc, + // const UInt8 *bytes, + // CFIndex numBytes, + // CFStringEncoding encoding, + // Boolean isExternalRepresentation + // ); + // + // We make the following substitutions: + // + // CFStringRef -> i8* + // CFAllocatorRef -> i8* + // UInt8 * -> i8* + // CFIndex -> long (i32 or i64, as appropriate; we ask the module for its pointer size for now) + // CFStringEncoding -> i32 + // Boolean -> i8 + + std::vector CFSCWB_arg_types; + CFSCWB_arg_types.push_back(i8_ptr_ty); + CFSCWB_arg_types.push_back(i8_ptr_ty); + CFSCWB_arg_types.push_back(intptr_ty); + CFSCWB_arg_types.push_back(i32_ty); + CFSCWB_arg_types.push_back(i8_ty); + llvm::Type *CFSCWB_ty = FunctionType::get(i8_ptr_ty, CFSCWB_arg_types, false); + + // Build the constant containing the pointer to the function + PointerType *CFSCWB_ptr_ty = PointerType::getUnqual(CFSCWB_ty); + Constant *CFSCWB_addr_int = ConstantInt::get(intptr_ty, CFStringCreateWithBytes_addr, false); + m_CFStringCreateWithBytes = ConstantExpr::getIntToPtr(CFSCWB_addr_int, CFSCWB_ptr_ty); + } + + ConstantArray *string_array = dyn_cast(CStr->getInitializer()); + + SmallVector CFSCWB_arguments; + + Constant *alloc_arg = Constant::getNullValue(i8_ptr_ty); + Constant *bytes_arg = ConstantExpr::getBitCast(CStr, i8_ptr_ty); + Constant *numBytes_arg = ConstantInt::get(intptr_ty, string_array->getType()->getNumElements(), false); + Constant *encoding_arg = ConstantInt::get(i32_ty, 0x0600, false); /* 0x0600 is kCFStringEncodingASCII */ + Constant *isExternal_arg = ConstantInt::get(i8_ty, 0x0, false); /* 0x0 is false */ + + CFSCWB_arguments.push_back(alloc_arg); + CFSCWB_arguments.push_back(bytes_arg); + CFSCWB_arguments.push_back(numBytes_arg); + CFSCWB_arguments.push_back(encoding_arg); + CFSCWB_arguments.push_back(isExternal_arg); + + CallInst *CFSCWB_call = CallInst::Create(m_CFStringCreateWithBytes, + CFSCWB_arguments.begin(), + CFSCWB_arguments.end(), + "CFStringCreateWithBytes", + FirstEntryInstruction); + + Constant *initializer = NSStr->getInitializer(); + + if (!UnfoldConstant(NSStr, CFSCWB_call, FirstEntryInstruction)) + { + if (log) + log->PutCString("Couldn't replace the NSString with the result of the call"); + + return false; + } + + NSStr->eraseFromParent(); + + return true; +} + +bool +IRForTarget::rewriteObjCConstStrings(Module &M, + Function &F) +{ + lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); + + ValueSymbolTable& value_symbol_table = M.getValueSymbolTable(); + + BasicBlock &entry_block(F.getEntryBlock()); + Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg()); + + if (!FirstEntryInstruction) + { + if (log) + log->PutCString("Couldn't find first instruction for rewritten Objective-C strings"); + + return false; + } + + for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end(); + vi != ve; + ++vi) + { + if (strstr(vi->first(), "_unnamed_cfstring_")) + { + Value *nsstring_value = vi->second; + + GlobalVariable *nsstring_global = dyn_cast(nsstring_value); + + if (!nsstring_global) + { + if (log) + log->PutCString("NSString variable is not a GlobalVariable"); + return false; + } + + if (!nsstring_global->hasInitializer()) + { + if (log) + log->PutCString("NSString variable does not have an initializer"); + return false; + } + + ConstantStruct *nsstring_struct = dyn_cast(nsstring_global->getInitializer()); + + if (!nsstring_struct) + { + if (log) + log->PutCString("NSString variable's initializer is not a ConstantStruct"); + return false; + } + + // We expect the following structure: + // + // struct { + // int *isa; + // int flags; + // char *str; + // long length; + // }; + + if (nsstring_struct->getNumOperands() != 4) + { + if (log) + log->Printf("NSString variable's initializer structure has an unexpected number of members. Should be 4, is %d", nsstring_struct->getNumOperands()); + return false; + } + + Constant *nsstring_member = nsstring_struct->getOperand(2); + + if (!nsstring_member) + { + if (log) + log->PutCString("NSString initializer's str element was empty"); + return false; + } + + ConstantExpr *nsstring_expr = dyn_cast(nsstring_member); + + if (!nsstring_expr) + { + if (log) + log->PutCString("NSString initializer's str element is not a ConstantExpr"); + return false; + } + + if (nsstring_expr->getOpcode() != Instruction::GetElementPtr) + { + if (log) + log->Printf("NSString initializer's str element is not a GetElementPtr expression, it's a %s", nsstring_expr->getOpcodeName()); + return false; + } + + Constant *nsstring_cstr = nsstring_expr->getOperand(0); + + GlobalVariable *cstr_global = dyn_cast(nsstring_cstr); + + if (!cstr_global) + { + if (log) + log->PutCString("NSString initializer's str element is not a GlobalVariable"); + + nsstring_cstr->dump(); + + return false; + } + + if (!cstr_global->hasInitializer()) + { + if (log) + log->PutCString("NSString initializer's str element does not have an initializer"); + return false; + } + + ConstantArray *cstr_array = dyn_cast(cstr_global->getInitializer()); + + if (!cstr_array) + { + if (log) + log->PutCString("NSString initializer's str element is not a ConstantArray"); + return false; + } + + if (!cstr_array->isCString()) + { + if (log) + log->PutCString("NSString initializer's str element is not a C string array"); + return false; + } + + if (log) + log->Printf("Found NSString constant %s, which contains \"%s\"", vi->first(), cstr_array->getAsString().c_str()); + + if (!rewriteObjCConstString(M, nsstring_global, cstr_global, FirstEntryInstruction)) + { + if (log) + log->PutCString("Error rewriting the constant string"); + return false; + } + + + } + } + + for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end(); + vi != ve; + ++vi) + { + if (!strcmp(vi->first(), "__CFConstantStringClassReference")) + { + GlobalVariable *gv = dyn_cast(vi->second); + + if (!gv) + { + if (log) + log->PutCString("__CFConstantStringClassReference is not a global variable"); + return false; + } + + gv->eraseFromParent(); + + break; + } + } + + return true; +} + static bool isObjCSelectorRef(Value *V) { GlobalVariable *GV = dyn_cast(V); @@ -366,7 +656,7 @@ CallInst *srN_call = CallInst::Create(m_sel_registerName, srN_arguments.begin(), srN_arguments.end(), - "srN", + "sel_registerName", selector_load); // Replace the load with the call in all users @@ -638,14 +928,14 @@ bool IRForTarget::MaybeHandleCallArguments(Module &M, - CallInst *C) + CallInst *Old) { // lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); - for (unsigned op_index = 0, num_ops = C->getNumArgOperands(); + for (unsigned op_index = 0, num_ops = Old->getNumArgOperands(); op_index < num_ops; ++op_index) - if (!MaybeHandleVariable(M, C->getArgOperand(op_index))) // conservatively believe that this is a store + if (!MaybeHandleVariable(M, Old->getArgOperand(op_index))) // conservatively believe that this is a store return false; return true; @@ -813,9 +1103,9 @@ static bool isGuardVariableRef(Value *V) { - Constant *C; + Constant *Old; - if (!(C = dyn_cast(V))) + if (!(Old = dyn_cast(V))) return false; ConstantExpr *CE; @@ -825,10 +1115,10 @@ if (CE->getOpcode() != Instruction::BitCast) return false; - C = CE->getOperand(0); + Old = CE->getOperand(0); } - GlobalVariable *GV = dyn_cast(C); + GlobalVariable *GV = dyn_cast(Old); if (!GV || !GV->hasName() || !GV->getName().startswith("_ZGV")) return false; @@ -909,19 +1199,8 @@ return true; } -// UnfoldConstant operates on a constant [C] which has just been replaced with a value -// [new_value]. We assume that new_value has been properly placed early in the function, -// most likely somewhere in front of the first instruction in the entry basic block -// [first_entry_instruction]. -// -// UnfoldConstant reads through the uses of C and replaces C in those uses with new_value. -// Where those uses are constants, the function generates new instructions to compute the -// result of the new, non-constant expression and places them before first_entry_instruction. -// These instructions replace the constant uses, so UnfoldConstant calls itself recursively -// for those. - -static bool -UnfoldConstant(Constant *C, Value *new_value, Instruction *first_entry_instruction) +bool +IRForTarget::UnfoldConstant(Constant *Old, Value *New, Instruction *FirstEntryInstruction) { lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); @@ -931,8 +1210,8 @@ // We do this because the use list might change, invalidating our iterator. // Much better to keep a work list ourselves. - for (ui = C->use_begin(); - ui != C->use_end(); + for (ui = Old->use_begin(); + ui != Old->use_end(); ++ui) users.push_back(*ui); @@ -961,12 +1240,12 @@ Value *s = constant_expr->getOperand(0); - if (s == C) - s = new_value; + if (s == Old) + s = New; - BitCastInst *bit_cast(new BitCastInst(s, C->getType(), "", first_entry_instruction)); + BitCastInst *bit_cast(new BitCastInst(s, Old->getType(), "", FirstEntryInstruction)); - UnfoldConstant(constant_expr, bit_cast, first_entry_instruction); + UnfoldConstant(constant_expr, bit_cast, FirstEntryInstruction); } break; case Instruction::GetElementPtr: @@ -977,8 +1256,8 @@ Value *ptr = constant_expr->getOperand(0); - if (ptr == C) - ptr = new_value; + if (ptr == Old) + ptr = New; SmallVector indices; @@ -991,15 +1270,15 @@ { Value *operand = constant_expr->getOperand(operand_index); - if (operand == C) - operand = new_value; + if (operand == Old) + operand = New; indices.push_back(operand); } - GetElementPtrInst *get_element_ptr(GetElementPtrInst::Create(ptr, indices.begin(), indices.end(), "", first_entry_instruction)); + GetElementPtrInst *get_element_ptr(GetElementPtrInst::Create(ptr, indices.begin(), indices.end(), "", FirstEntryInstruction)); - UnfoldConstant(constant_expr, get_element_ptr, first_entry_instruction); + UnfoldConstant(constant_expr, get_element_ptr, FirstEntryInstruction); } break; } @@ -1014,7 +1293,7 @@ else { // simple fall-through case for non-constants - user->replaceUsesOfWith(C, new_value); + user->replaceUsesOfWith(Old, New); } } @@ -1067,9 +1346,9 @@ log->Printf("Arg: \"%s\"", PrintValue(argument).c_str()); BasicBlock &entry_block(F.getEntryBlock()); - Instruction *first_entry_instruction(entry_block.getFirstNonPHIOrDbg()); + Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg()); - if (!first_entry_instruction) + if (!FirstEntryInstruction) return false; LLVMContext &context(M.getContext()); @@ -1096,11 +1375,11 @@ offset); ConstantInt *offset_int(ConstantInt::getSigned(offset_type, offset)); - GetElementPtrInst *get_element_ptr = GetElementPtrInst::Create(argument, offset_int, "", first_entry_instruction); - BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType(), "", first_entry_instruction); + GetElementPtrInst *get_element_ptr = GetElementPtrInst::Create(argument, offset_int, "", FirstEntryInstruction); + BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType(), "", FirstEntryInstruction); if (Constant *constant = dyn_cast(value)) - UnfoldConstant(constant, bit_cast, first_entry_instruction); + UnfoldConstant(constant, bit_cast, FirstEntryInstruction); else value->replaceAllUsesWith(bit_cast); @@ -1138,6 +1417,37 @@ if (!createResultVariable(M, *function)) return false; + /////////////////////////////////////////////////////////////////////////////// + // Fix all Objective-C constant strings to use NSStringWithCString:encoding: + // + + if (log) + { + std::string s; + raw_string_ostream oss(s); + + M.print(oss, NULL); + + oss.flush(); + + log->Printf("Module after creating the result variable: \n\"%s\"", s.c_str()); + } + + if (!rewriteObjCConstStrings(M, *function)) + return false; + + if (log) + { + std::string s; + raw_string_ostream oss(s); + + M.print(oss, NULL); + + oss.flush(); + + log->Printf("Module after rewriting Objective-C const strings: \n\"%s\"", s.c_str()); + } + ////////////////////////////////// // Run basic-block level passes // From jingham at apple.com Wed Nov 17 20:47:08 2010 From: jingham at apple.com (Jim Ingham) Date: Thu, 18 Nov 2010 02:47:08 -0000 Subject: [Lldb-commits] [lldb] r119675 - in /lldb/trunk: include/lldb/Target/Thread.h lldb.xcodeproj/project.pbxproj source/Expression/ClangFunction.cpp source/Plugins/Process/MacOSX-User/source/ThreadMacOSX.cpp source/Plugins/Process/gdb-remote/ThreadGDBRemote.cpp source/Target/Thread.cpp source/Target/ThreadPlanBase.cpp Message-ID: <20101118024708.3E6CD2A6C12C@llvm.org> Author: jingham Date: Wed Nov 17 20:47:07 2010 New Revision: 119675 URL: http://llvm.org/viewvc/llvm-project?rev=119675&view=rev Log: The thread plan destructors may call Thread virtual methods. That means they have to get cleaned up in the derived class's destructor. Make sure that happens. Modified: lldb/trunk/include/lldb/Target/Thread.h lldb/trunk/lldb.xcodeproj/project.pbxproj lldb/trunk/source/Expression/ClangFunction.cpp lldb/trunk/source/Plugins/Process/MacOSX-User/source/ThreadMacOSX.cpp lldb/trunk/source/Plugins/Process/gdb-remote/ThreadGDBRemote.cpp lldb/trunk/source/Target/Thread.cpp lldb/trunk/source/Target/ThreadPlanBase.cpp Modified: lldb/trunk/include/lldb/Target/Thread.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/Target/Thread.h?rev=119675&r1=119674&r2=119675&view=diff ============================================================================== --- lldb/trunk/include/lldb/Target/Thread.h (original) +++ lldb/trunk/include/lldb/Target/Thread.h Wed Nov 17 20:47:07 2010 @@ -616,7 +616,7 @@ // type than the actual system thread ID. uint32_t GetIndexID () const; - + //------------------------------------------------------------------ // lldb::ExecutionContextScope pure virtual functions //------------------------------------------------------------------ @@ -642,6 +642,10 @@ friend class ThreadPlan; friend class StackFrameList; + + // This is necessary to make sure thread assets get destroyed while the thread is still in good shape + // to call virtual thread methods. This must be called by classes that derive from Thread in their destructor. + virtual void DestroyThread (); void PushPlan (lldb::ThreadPlanSP &plan_sp); @@ -688,6 +692,7 @@ int m_resume_signal; ///< The signal that should be used when continuing this thread. lldb::StateType m_resume_state; ///< The state that indicates what this thread should do when the process is resumed. std::auto_ptr m_unwinder_ap; + bool m_destroy_called; // This is used internally to make sure derived Thread classes call DestroyThread. private: //------------------------------------------------------------------ // For Thread only Modified: lldb/trunk/lldb.xcodeproj/project.pbxproj URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/lldb.xcodeproj/project.pbxproj?rev=119675&r1=119674&r2=119675&view=diff ============================================================================== --- lldb/trunk/lldb.xcodeproj/project.pbxproj (original) +++ lldb/trunk/lldb.xcodeproj/project.pbxproj Wed Nov 17 20:47:07 2010 @@ -2452,7 +2452,6 @@ isa = PBXProject; buildConfigurationList = 1DEB91EF08733DB70010E9CD /* Build configuration list for PBXProject "lldb" */; compatibilityVersion = "Xcode 3.1"; - developmentRegion = English; hasScannedForEncodings = 1; knownRegions = ( en, Modified: lldb/trunk/source/Expression/ClangFunction.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Expression/ClangFunction.cpp?rev=119675&r1=119674&r2=119675&view=diff ============================================================================== --- lldb/trunk/source/Expression/ClangFunction.cpp (original) +++ lldb/trunk/source/Expression/ClangFunction.cpp Wed Nov 17 20:47:07 2010 @@ -590,7 +590,8 @@ break; } - if (try_all_threads) + if (try_all_threads + && (stop_state == lldb::eStateStopped && Process::ProcessEventData::GetInterruptedFromEvent (event_sp.get()))) { call_plan_ptr->SetStopOthers (false); Modified: lldb/trunk/source/Plugins/Process/MacOSX-User/source/ThreadMacOSX.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Plugins/Process/MacOSX-User/source/ThreadMacOSX.cpp?rev=119675&r1=119674&r2=119675&view=diff ============================================================================== --- lldb/trunk/source/Plugins/Process/MacOSX-User/source/ThreadMacOSX.cpp (original) +++ lldb/trunk/source/Plugins/Process/MacOSX-User/source/ThreadMacOSX.cpp Wed Nov 17 20:47:07 2010 @@ -55,6 +55,7 @@ ThreadMacOSX::~ThreadMacOSX () { + DestroyThread(); } #if defined (__i386__) || defined (__x86_64__) Modified: lldb/trunk/source/Plugins/Process/gdb-remote/ThreadGDBRemote.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Plugins/Process/gdb-remote/ThreadGDBRemote.cpp?rev=119675&r1=119674&r2=119675&view=diff ============================================================================== --- lldb/trunk/source/Plugins/Process/gdb-remote/ThreadGDBRemote.cpp (original) +++ lldb/trunk/source/Plugins/Process/gdb-remote/ThreadGDBRemote.cpp Wed Nov 17 20:47:07 2010 @@ -48,6 +48,7 @@ ThreadGDBRemote::~ThreadGDBRemote () { ProcessGDBRemoteLog::LogIf(GDBR_LOG_THREAD, "%p: ThreadGDBRemote::~ThreadGDBRemote (pid = %i, tid = 0x%4.4x)", this, m_process.GetID(), GetID()); + DestroyThread(); } Modified: lldb/trunk/source/Target/Thread.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Target/Thread.cpp?rev=119675&r1=119674&r2=119675&view=diff ============================================================================== --- lldb/trunk/source/Target/Thread.cpp (original) +++ lldb/trunk/source/Target/Thread.cpp Wed Nov 17 20:47:07 2010 @@ -54,7 +54,8 @@ m_curr_frames_ap (), m_resume_signal (LLDB_INVALID_SIGNAL_NUMBER), m_resume_state (eStateRunning), - m_unwinder_ap () + m_unwinder_ap (), + m_destroy_called (false) { LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT)); @@ -71,6 +72,17 @@ LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT)); if (log) log->Printf ("%p Thread::~Thread(tid = 0x%4.4x)", this, GetID()); + /// If you hit this assert, it means your derived class forgot to call DoDestroy in its destructor. + assert (m_destroy_called); +} + +void +Thread::DestroyThread () +{ + m_plan_stack.clear(); + m_discarded_plan_stack.clear(); + m_completed_plan_stack.clear(); + m_destroy_called = true; } int @@ -625,7 +637,6 @@ } } - // FIXME: What should we do about the immediate plans? } ThreadPlan * Modified: lldb/trunk/source/Target/ThreadPlanBase.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Target/ThreadPlanBase.cpp?rev=119675&r1=119674&r2=119675&view=diff ============================================================================== --- lldb/trunk/source/Target/ThreadPlanBase.cpp (original) +++ lldb/trunk/source/Target/ThreadPlanBase.cpp Wed Nov 17 20:47:07 2010 @@ -36,7 +36,14 @@ ThreadPlan(ThreadPlan::eKindBase, "base plan", thread, eVoteYes, eVoteNoOpinion) { // Set the tracer to a default tracer. + // FIXME: need to add a thread settings variable to pix various tracers... +#define THREAD_PLAN_USE_ASSEMBLY_TRACER 1 + +#ifdef THREAD_PLAN_USE_ASSEMBLY_TRACER + ThreadPlanTracerSP new_tracer_sp (new ThreadPlanAssemblyTracer (m_thread)); +#else ThreadPlanTracerSP new_tracer_sp (new ThreadPlanTracer (m_thread)); +#endif new_tracer_sp->EnableTracing (m_thread.GetTraceEnabledState()); SetThreadPlanTracer(new_tracer_sp); } From scallanan at apple.com Wed Nov 17 20:56:28 2010 From: scallanan at apple.com (Sean Callanan) Date: Thu, 18 Nov 2010 02:56:28 -0000 Subject: [Lldb-commits] [lldb] r119677 - in /lldb/trunk: include/lldb/Core/ClangForward.h include/lldb/Expression/ClangASTSource.h include/lldb/Expression/ClangExpressionParser.h include/lldb/Symbol/ClangASTContext.h llvm.zip scripts/build-llvm.pl source/Expression/ClangASTSource.cpp source/Expression/ClangExpressionParser.cpp source/Symbol/ClangASTContext.cpp source/Symbol/ClangASTType.cpp Message-ID: <20101118025628.2D2C12A6C12C@llvm.org> Author: spyffe Date: Wed Nov 17 20:56:27 2010 New Revision: 119677 URL: http://llvm.org/viewvc/llvm-project?rev=119677&view=rev Log: Updated to the LLVM/Clang of 2010-11-17 at 3:30pm. Modified: lldb/trunk/include/lldb/Core/ClangForward.h lldb/trunk/include/lldb/Expression/ClangASTSource.h lldb/trunk/include/lldb/Expression/ClangExpressionParser.h lldb/trunk/include/lldb/Symbol/ClangASTContext.h lldb/trunk/llvm.zip lldb/trunk/scripts/build-llvm.pl lldb/trunk/source/Expression/ClangASTSource.cpp lldb/trunk/source/Expression/ClangExpressionParser.cpp lldb/trunk/source/Symbol/ClangASTContext.cpp lldb/trunk/source/Symbol/ClangASTType.cpp Modified: lldb/trunk/include/lldb/Core/ClangForward.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/Core/ClangForward.h?rev=119677&r1=119676&r2=119677&view=diff ============================================================================== --- lldb/trunk/include/lldb/Core/ClangForward.h (original) +++ lldb/trunk/include/lldb/Core/ClangForward.h Wed Nov 17 20:56:27 2010 @@ -57,6 +57,8 @@ class ExternalASTSource; class ExtVectorElementExpr; class FieldDecl; + class FileManager; + class FileSystemOptions; class FloatingLiteral; class FrontendOptions; class FunctionDecl; Modified: lldb/trunk/include/lldb/Expression/ClangASTSource.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/Expression/ClangASTSource.h?rev=119677&r1=119676&r2=119677&view=diff ============================================================================== --- lldb/trunk/include/lldb/Expression/ClangASTSource.h (original) +++ lldb/trunk/include/lldb/Expression/ClangASTSource.h Wed Nov 17 20:56:27 2010 @@ -76,6 +76,11 @@ /// Interface stub that returns 0. //------------------------------------------------------------------ uint32_t GetNumExternalSelectors(); + + //------------------------------------------------------------------ + /// Interface stub that returns NULL. + //------------------------------------------------------------------ + clang::CXXBaseSpecifier *GetExternalCXXBaseSpecifiers(uint64_t Offset); //------------------------------------------------------------------ /// Look up all Decls that match a particular name. Only handles Modified: lldb/trunk/include/lldb/Expression/ClangExpressionParser.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/Expression/ClangExpressionParser.h?rev=119677&r1=119676&r2=119677&view=diff ============================================================================== --- lldb/trunk/include/lldb/Expression/ClangExpressionParser.h (original) +++ lldb/trunk/include/lldb/Expression/ClangExpressionParser.h Wed Nov 17 20:56:27 2010 @@ -173,6 +173,8 @@ ClangExpression &m_expr; ///< The expression to be parsed std::string m_target_triple; ///< The target triple used to initialize LLVM + std::auto_ptr m_file_manager; ///< The Clang file manager object used by the compiler + std::auto_ptr m_file_system_options; ///< The Clang file system options object used by the compiler std::auto_ptr m_compiler; ///< The Clang compiler used to parse expressions into IR std::auto_ptr m_builtin_context; ///< Context for Clang built-ins std::auto_ptr m_ast_context; ///< The AST context used to hold types and names for the parser Modified: lldb/trunk/include/lldb/Symbol/ClangASTContext.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/Symbol/ClangASTContext.h?rev=119677&r1=119676&r2=119677&view=diff ============================================================================== --- lldb/trunk/include/lldb/Symbol/ClangASTContext.h (original) +++ lldb/trunk/include/lldb/Symbol/ClangASTContext.h Wed Nov 17 20:56:27 2010 @@ -72,6 +72,12 @@ clang::SelectorTable * getSelectorTable(); + clang::FileManager * + getFileManager(); + + clang::FileSystemOptions * + getFileSystemOptions(); + clang::SourceManager * getSourceManager(); @@ -604,6 +610,8 @@ std::string m_target_triple; std::auto_ptr m_ast_context_ap; std::auto_ptr m_language_options_ap; + std::auto_ptr m_file_manager_ap; + std::auto_ptr m_file_system_options_ap; std::auto_ptr m_source_manager_ap; std::auto_ptr m_diagnostic_ap; std::auto_ptr m_target_options_ap; Modified: lldb/trunk/llvm.zip URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/llvm.zip?rev=119677&r1=119676&r2=119677&view=diff ============================================================================== Binary files - no diff available. Modified: lldb/trunk/scripts/build-llvm.pl URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/scripts/build-llvm.pl?rev=119677&r1=119676&r2=119677&view=diff ============================================================================== --- lldb/trunk/scripts/build-llvm.pl (original) +++ lldb/trunk/scripts/build-llvm.pl Wed Nov 17 20:56:27 2010 @@ -25,7 +25,7 @@ our $llvm_configuration = $ENV{LLVM_CONFIGURATION}; -our $llvm_revision = "'{2010-10-28T19:00}'"; +our $llvm_revision = "'{2010-11-17T15:30}'"; our $llvm_source_dir = "$ENV{SRCROOT}"; our $cc = "$ENV{DEVELOPER_BIN_DIR}/gcc-4.2"; our $cxx = "$ENV{DEVELOPER_BIN_DIR}/g++-4.2"; Modified: lldb/trunk/source/Expression/ClangASTSource.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Expression/ClangASTSource.cpp?rev=119677&r1=119676&r2=119677&view=diff ============================================================================== --- lldb/trunk/source/Expression/ClangASTSource.cpp (original) +++ lldb/trunk/source/Expression/ClangASTSource.cpp Wed Nov 17 20:56:27 2010 @@ -36,6 +36,7 @@ // for method signatures!) might help. Selector ClangASTSource::GetExternalSelector(uint32_t) { return Selector(); } uint32_t ClangASTSource::GetNumExternalSelectors() { return 0; } +CXXBaseSpecifier *ClangASTSource::GetExternalCXXBaseSpecifiers(uint64_t Offset) { return NULL; } // The core lookup interface. DeclContext::lookup_result ClangASTSource::FindExternalVisibleDeclsByName Modified: lldb/trunk/source/Expression/ClangExpressionParser.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Expression/ClangExpressionParser.cpp?rev=119677&r1=119676&r2=119677&view=diff ============================================================================== --- lldb/trunk/source/Expression/ClangExpressionParser.cpp (original) +++ lldb/trunk/source/Expression/ClangExpressionParser.cpp Wed Nov 17 20:56:27 2010 @@ -243,8 +243,11 @@ // 5. Set up the source management objects inside the compiler + m_file_manager.reset(new clang::FileManager()); + m_file_system_options.reset(new clang::FileSystemOptions()); + if (!m_compiler->hasSourceManager()) - m_compiler->createSourceManager(); + m_compiler->createSourceManager(*m_file_manager.get(), *m_file_system_options.get()); m_compiler->createFileManager(); m_compiler->createPreprocessor(); Modified: lldb/trunk/source/Symbol/ClangASTContext.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Symbol/ClangASTContext.cpp?rev=119677&r1=119676&r2=119677&view=diff ============================================================================== --- lldb/trunk/source/Symbol/ClangASTContext.cpp (original) +++ lldb/trunk/source/Symbol/ClangASTContext.cpp Wed Nov 17 20:56:27 2010 @@ -23,6 +23,7 @@ #include "clang/AST/Type.h" #include "clang/Basic/Builtins.h" #include "clang/Basic/FileManager.h" +#include "clang/Basic/FileSystemOptions.h" #include "clang/Basic/SourceManager.h" #include "clang/Basic/TargetInfo.h" #include "clang/Basic/TargetOptions.h" @@ -351,11 +352,27 @@ return m_selector_table_ap.get(); } +clang::FileManager * +ClangASTContext::getFileManager() +{ + if (m_file_manager_ap.get() == NULL) + m_file_manager_ap.reset(new clang::FileManager()); + return m_file_manager_ap.get(); +} + +clang::FileSystemOptions * +ClangASTContext::getFileSystemOptions() +{ + if (m_file_system_options_ap.get() == NULL) + m_file_system_options_ap.reset(new clang::FileSystemOptions()); + return m_file_system_options_ap.get(); +} + clang::SourceManager * ClangASTContext::getSourceManager() { if (m_source_manager_ap.get() == NULL) - m_source_manager_ap.reset(new clang::SourceManager(*getDiagnostic())); + m_source_manager_ap.reset(new clang::SourceManager(*getDiagnostic(), *getFileManager(), *getFileSystemOptions())); return m_source_manager_ap.get(); } @@ -730,9 +747,10 @@ NullDiagnosticClient *null_client = new NullDiagnosticClient; Diagnostic diagnostics(null_client); FileManager file_manager; + FileSystemOptions file_system_options; ASTImporter importer(diagnostics, - *dest_context, file_manager, - *source_context, file_manager); + *dest_context, file_manager, file_system_options, + *source_context, file_manager, file_system_options); QualType src = QualType::getFromOpaquePtr(clang_type); QualType dst = importer.Import(src); @@ -750,9 +768,10 @@ NullDiagnosticClient *null_client = new NullDiagnosticClient; Diagnostic diagnostics(null_client); FileManager file_manager; + FileSystemOptions file_system_options; ASTImporter importer(diagnostics, - *dest_context, file_manager, - *source_context, file_manager); + *dest_context, file_manager, file_system_options, + *source_context, file_manager, file_system_options); return importer.Import(source_decl); } @@ -2095,9 +2114,9 @@ if (base_class->isVirtual()) - bit_offset = record_layout.getVBaseClassOffset(base_class_decl); + bit_offset = record_layout.getVBaseClassOffset(base_class_decl).getQuantity(); else - bit_offset = record_layout.getBaseClassOffset(base_class_decl); + bit_offset = record_layout.getBaseClassOffset(base_class_decl).getQuantity(); // Base classes should be a multiple of 8 bits in size assert (bit_offset % 8 == 0); Modified: lldb/trunk/source/Symbol/ClangASTType.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Symbol/ClangASTType.cpp?rev=119677&r1=119676&r2=119677&view=diff ============================================================================== --- lldb/trunk/source/Symbol/ClangASTType.cpp (original) +++ lldb/trunk/source/Symbol/ClangASTType.cpp Wed Nov 17 20:56:27 2010 @@ -367,9 +367,9 @@ continue; if (base_class->isVirtual()) - field_bit_offset = record_layout.getVBaseClassOffset(base_class_decl); + field_bit_offset = record_layout.getVBaseClassOffset(base_class_decl).getQuantity(); else - field_bit_offset = record_layout.getBaseClassOffset(base_class_decl); + field_bit_offset = record_layout.getBaseClassOffset(base_class_decl).getQuantity(); field_byte_offset = field_bit_offset / 8; assert (field_bit_offset % 8 == 0); if (child_idx == 0) From scallanan at apple.com Wed Nov 17 21:56:18 2010 From: scallanan at apple.com (Sean Callanan) Date: Thu, 18 Nov 2010 03:56:18 -0000 Subject: [Lldb-commits] [lldb] r119679 - /lldb/trunk/docs/building-with-debug-llvm.txt Message-ID: <20101118035618.25C082A6C12C@llvm.org> Author: spyffe Date: Wed Nov 17 21:56:17 2010 New Revision: 119679 URL: http://llvm.org/viewvc/llvm-project?rev=119679&view=rev Log: Instructions for building LLDB with a debug LLVM build under Xcode. Added: lldb/trunk/docs/building-with-debug-llvm.txt Added: lldb/trunk/docs/building-with-debug-llvm.txt URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/docs/building-with-debug-llvm.txt?rev=119679&view=auto ============================================================================== --- lldb/trunk/docs/building-with-debug-llvm.txt (added) +++ lldb/trunk/docs/building-with-debug-llvm.txt Wed Nov 17 21:56:17 2010 @@ -0,0 +1,50 @@ +This document describes how to build a debug version of LLVM for use with +LLDB, and how to make LLDB use it. + +It assumes that you are using the Xcode 3 series (I used 3.2.4) to build +LLDB. It also assumes that your shell is /bin/bash, and that you are +currently at a shell prompt in a checked-out LLDB repository. + +1. Check out LLVM and Clang from their repositories. To determine + the revision to use, consult scripts/build-llvm.pl (this is done + in the first command line below). !!! WARNING Do not use the + name "llvm" for your checkout, for reasons described in part 3 + below. + + $ export CLANG_REVISION=`cat scripts/build-llvm.pl | grep ^our.*llvm_revision | cut -d \' -f 2,2` + $ svn co -r $CLANG_REVISION http://llvm.org/svn/llvm-project/llvm/trunk llvm.checkout + $ svn co -r $CLANG_REVISION http://llvm.org/svn/llvm-project/cfe/trunk llvm.checkout/tools/clang + +2. Configure LLVM/Clang with the proper options and compilers. I use: + + $ cd llvm.checkout + $ CC="cc -g -O0" CXX="c++ -g -O0" ./configure --disable-optimized --enable-assertions --enable-targets=x86_64,arm + $ CC="cc -g -O0" CXX="c++ -g -O0" make -j 2 + $ cd .. + +3. Create a link to the built LLVM. !!! WARNING: Do not rename the + directory! The LLVM builder script that runs as part of the Xcode + build keys off the fact that llvm/ is a symlink to recognize that + we are building with a custom debug build. + + $ ln -sf llvm.checkout llvm + +4. Make sure that your Xcode project is set up correctly. Open + lldb.xcodeproj and do the following: + + Under "Targets" in the Groups & Files navigator, double-click + lldb-tool. In the resulting window, select "Debug" from the + "Configuration:" drop-down. Then, make sure that the setting + "Build Active Architecture Only" is enabled. Close the window. + + Under "Targets" in the Groups & Files navigator, double-click + LLDB. In the resulting window, select "Debug" from the + "Configuration:" drop-down. Then, make sure that the setting + "Build Active Architecture Only" is enabled. Close the window. + +5. Ensure that Xcode is building the lldb-tool target in Debug + configuration for your architecture (typically x86_64). You + can usually pick these options from the Overview drop-down at + the top left of the Xcode window. + +6. Build lldb.xcodeproj. \ No newline at end of file From gclayton at apple.com Wed Nov 17 23:57:03 2010 From: gclayton at apple.com (Greg Clayton) Date: Thu, 18 Nov 2010 05:57:03 -0000 Subject: [Lldb-commits] [lldb] r119680 - in /lldb/trunk: include/lldb/API/ include/lldb/Target/ lldb.xcodeproj/ source/Plugins/DynamicLoader/MacOSX-DYLD/ source/Plugins/Process/MacOSX-User/source/ source/Plugins/Process/gdb-remote/ source/Target/ tools/debugserver/debugserver.xcodeproj/ tools/debugserver/source/ tools/debugserver/source/MacOSX/ tools/debugserver/source/MacOSX/arm/ tools/debugserver/source/MacOSX/i386/ tools/debugserver/source/MacOSX/ppc/ tools/debugserver/source/MacOSX/x86_64/ Message-ID: <20101118055703.BFCB22A6C12C@llvm.org> Author: gclayton Date: Wed Nov 17 23:57:03 2010 New Revision: 119680 URL: http://llvm.org/viewvc/llvm-project?rev=119680&view=rev Log: Fixed Process::Halt() as it was broken for "process halt" after recent changes to the DoHalt down in ProcessGDBRemote. I also moved the functionality that was in ProcessGDBRemote::DoHalt up into Process::Halt so not every class has to implement a tricky halt/resume on the internal state thread. The functionality is the same as it was before with two changes: - when we eat the event we now just reuse the event we consume when the private state thread is paused and set the interrupted bool on the event if needed - we also properly update the Process::m_public_state with the state of the event we consume. Prior to this, if you issued a "process halt" it would eat the event, not update the process state, and then produce a new event with the interrupted bit set and send it. Anyone listening to the event would get the stopped event with a process that whose state was set to "running". Fixed debugserver to not have to be spawned with the architecture of the inferior process. This worked fine for launching processes, but when attaching to processes by name or pid without a file in lldb, it would fail. Now debugserver can support multiple architectures for a native debug session on the current host. This currently means i386 and x86_64 are supported in the same binary and a x86_64 debugserver can attach to a i386 executable. This change involved a lot of changes to make sure we dynamically detect the correct registers for the inferior process. Modified: lldb/trunk/include/lldb/API/SBThread.h lldb/trunk/include/lldb/Target/Process.h lldb/trunk/lldb.xcodeproj/project.pbxproj lldb/trunk/source/Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderMacOSXDYLD.cpp lldb/trunk/source/Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderMacOSXDYLD.h lldb/trunk/source/Plugins/Process/MacOSX-User/source/ProcessMacOSX.cpp lldb/trunk/source/Plugins/Process/MacOSX-User/source/ProcessMacOSX.h lldb/trunk/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp lldb/trunk/source/Plugins/Process/gdb-remote/ProcessGDBRemote.h lldb/trunk/source/Target/Process.cpp lldb/trunk/tools/debugserver/debugserver.xcodeproj/project.pbxproj lldb/trunk/tools/debugserver/source/DNB.cpp lldb/trunk/tools/debugserver/source/DNB.h lldb/trunk/tools/debugserver/source/DNBArch.h lldb/trunk/tools/debugserver/source/MacOSX/MachProcess.cpp lldb/trunk/tools/debugserver/source/MacOSX/MachProcess.h lldb/trunk/tools/debugserver/source/MacOSX/MachThread.cpp lldb/trunk/tools/debugserver/source/MacOSX/MachThread.h lldb/trunk/tools/debugserver/source/MacOSX/MachThreadList.cpp lldb/trunk/tools/debugserver/source/MacOSX/MachThreadList.h lldb/trunk/tools/debugserver/source/MacOSX/arm/DNBArchImpl.h lldb/trunk/tools/debugserver/source/MacOSX/i386/DNBArchImplI386.cpp lldb/trunk/tools/debugserver/source/MacOSX/i386/DNBArchImplI386.h lldb/trunk/tools/debugserver/source/MacOSX/ppc/DNBArchImpl.h lldb/trunk/tools/debugserver/source/MacOSX/x86_64/DNBArchImplX86_64.cpp lldb/trunk/tools/debugserver/source/MacOSX/x86_64/DNBArchImplX86_64.h lldb/trunk/tools/debugserver/source/RNBRemote.cpp lldb/trunk/tools/debugserver/source/RNBRemote.h lldb/trunk/tools/debugserver/source/debugserver.cpp Modified: lldb/trunk/include/lldb/API/SBThread.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/API/SBThread.h?rev=119680&r1=119679&r2=119680&view=diff ============================================================================== --- lldb/trunk/include/lldb/API/SBThread.h (original) +++ lldb/trunk/include/lldb/API/SBThread.h Wed Nov 17 23:57:03 2010 @@ -35,6 +35,30 @@ lldb::StopReason GetStopReason(); +// +// // Get the number of words associated with the stop reason. +// size_t +// GetStopReasonDataCount(); +// +// //-------------------------------------------------------------------------- +// // Get information associated with a stop reason. +// // +// // Breakpoint and watchpoint stop reasons will have data that consists of +// // pairs of breakpoint/watchpoint IDs followed by the breakpoint/watchpoint +// // location IDs (they always come in pairs). +// // +// // Stop Reason Count Data Type +// // ======================== ===== ========================================== +// // eStopReasonNone 0 +// // eStopReasonTrace 0 +// // eStopReasonBreakpoint N duple: {breakpoint id, location id} +// // eStopReasonWatchpoint N duple: {watchpoint id, location id} +// // eStopReasonSignal 1 unix signal number +// // eStopReasonException N exception data +// // eStopReasonPlanComplete 0 +// //-------------------------------------------------------------------------- +// uint64_t +// GetStopReasonDataAtIndex(uint32_t idx); size_t GetStopDescription (char *dst, size_t dst_len); Modified: lldb/trunk/include/lldb/Target/Process.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/Target/Process.h?rev=119680&r1=119679&r2=119680&view=diff ============================================================================== --- lldb/trunk/include/lldb/Target/Process.h (original) +++ lldb/trunk/include/lldb/Target/Process.h Wed Nov 17 23:57:03 2010 @@ -628,6 +628,12 @@ uint32_t GetAddressByteSize(); + void + SetAddressByteSize (uint32_t addr_byte_size) + { + m_addr_byte_size = addr_byte_size; + } + //------------------------------------------------------------------ /// Get the image information address for the current process. /// @@ -1007,12 +1013,12 @@ //------------------------------------------------------------------ /// Halts a running process. /// - /// DoHalt should consume any process events that were delivered in the - /// process of implementing the halt. + /// DoHalt should consume any process events that were delivered in + /// the process of implementing the halt. /// /// @param[out] caused_stop - /// If true, then this Halt caused the stop, otherwise, the process was - /// already stopped. + /// If true, then this Halt caused the stop, otherwise, the + /// process was already stopped. /// /// @return /// Returns \b true if the process successfully halts, \b false @@ -1633,8 +1639,17 @@ /// @return /// A valid ByteOrder enumeration, or eByteOrderInvalid. //------------------------------------------------------------------ - virtual lldb::ByteOrder - GetByteOrder () const = 0; + lldb::ByteOrder + GetByteOrder () const + { + return m_byte_order; + } + + void + SetByteOrder (lldb::ByteOrder byte_order) + { + m_byte_order = byte_order; + } const ConstString & GetTargetTriple () @@ -1720,10 +1735,12 @@ std::auto_ptr m_dynamic_checkers_ap; ///< The functions used by the expression parser to validate data that expressions use. UnixSignals m_unix_signals; /// This is the current signal set for this process. ConstString m_target_triple; + lldb::ByteOrder m_byte_order; /// The byte order of the process. Should be set in DidLaunch/DidAttach. + uint32_t m_addr_byte_size; /// The size in bytes of an address/pointer for the inferior process. Should be set in DidLaunch/DidAttach. lldb::ABISP m_abi_sp; lldb::InputReaderSP m_process_input_reader; lldb_private::Communication m_stdio_communication; - lldb_private::Mutex m_stdio_comm_mutex; + lldb_private::Mutex m_stdio_communication_mutex; std::string m_stdout_data; typedef std::map LanguageRuntimeCollection; Modified: lldb/trunk/lldb.xcodeproj/project.pbxproj URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/lldb.xcodeproj/project.pbxproj?rev=119680&r1=119679&r2=119680&view=diff ============================================================================== --- lldb/trunk/lldb.xcodeproj/project.pbxproj (original) +++ lldb/trunk/lldb.xcodeproj/project.pbxproj Wed Nov 17 23:57:03 2010 @@ -2452,6 +2452,7 @@ isa = PBXProject; buildConfigurationList = 1DEB91EF08733DB70010E9CD /* Build configuration list for PBXProject "lldb" */; compatibilityVersion = "Xcode 3.1"; + developmentRegion = English; hasScannedForEncodings = 1; knownRegions = ( en, @@ -2941,7 +2942,7 @@ GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_HIDDEN_VIRTUAL_FUNCTIONS = YES; GCC_WARN_UNUSED_VARIABLE = YES; - ONLY_ACTIVE_ARCH = YES; + ONLY_ACTIVE_ARCH = NO; PREBINDING = NO; VALID_ARCHS = "x86_64 i386"; }; Modified: lldb/trunk/source/Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderMacOSXDYLD.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderMacOSXDYLD.cpp?rev=119680&r1=119679&r2=119680&view=diff ============================================================================== --- lldb/trunk/source/Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderMacOSXDYLD.cpp (original) +++ lldb/trunk/source/Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderMacOSXDYLD.cpp Wed Nov 17 23:57:03 2010 @@ -59,8 +59,10 @@ m_dyld(), m_dyld_all_image_infos_addr(LLDB_INVALID_ADDRESS), m_dyld_all_image_infos(), + m_dyld_all_image_infos_stop_id (UINT32_MAX), m_break_id(LLDB_INVALID_BREAK_ID), m_dyld_image_infos(), + m_dyld_image_infos_stop_id (UINT32_MAX), m_mutex(Mutex::eMutexTypeRecursive) { } @@ -83,10 +85,8 @@ DynamicLoaderMacOSXDYLD::DidAttach () { PrivateInitialize(m_process); - if (NeedToLocateDYLD ()) - LocateDYLD (); + LocateDYLD (); SetNotificationBreakpoint (); - UpdateAllImageInfos(); } //------------------------------------------------------------------ @@ -99,10 +99,8 @@ DynamicLoaderMacOSXDYLD::DidLaunch () { PrivateInitialize(m_process); - if (NeedToLocateDYLD ()) - LocateDYLD (); + LocateDYLD (); SetNotificationBreakpoint (); - UpdateAllImageInfos(); } @@ -401,12 +399,23 @@ DynamicLoaderMacOSXDYLD::ReadAllImageInfosStructure () { Mutex::Locker locker(m_mutex); + + // the all image infos is already valid for this process stop ID + if (m_process->GetStopID() == m_dyld_all_image_infos_stop_id) + return true; + m_dyld_all_image_infos.Clear(); if (m_dyld_all_image_infos_addr != LLDB_INVALID_ADDRESS) { - const ByteOrder endian = m_process->GetByteOrder(); - const uint32_t addr_size = m_process->GetAddressByteSize(); + ByteOrder byte_order = m_process->GetByteOrder(); + uint32_t addr_size = 4; + if (m_dyld_all_image_infos_addr > UINT32_MAX) + addr_size = 8; + uint8_t buf[256]; + DataExtractor data (buf, sizeof(buf), byte_order, addr_size); + uint32_t offset = 0; + const size_t count_v2 = sizeof (uint32_t) + // version sizeof (uint32_t) + // infoArrayCount addr_size + // infoArray @@ -434,9 +443,23 @@ Error error; if (m_process->ReadMemory (m_dyld_all_image_infos_addr, buf, 4, error) == 4) { - DataExtractor data(buf, 4, endian, addr_size); - uint32_t offset = 0; m_dyld_all_image_infos.version = data.GetU32(&offset); + // If anything in the high byte is set, we probably got the byte + // order incorrect (the process might not have it set correctly + // yet due to attaching to a program without a specified file). + if (m_dyld_all_image_infos.version & 0xff000000) + { + // We have guessed the wrong byte order. Swap it and try + // reading the version again. + if (byte_order == eByteOrderLittle) + byte_order = eByteOrderBig; + else + byte_order = eByteOrderLittle; + + data.SetByteOrder (byte_order); + offset = 0; + m_dyld_all_image_infos.version = data.GetU32(&offset); + } } else { @@ -451,8 +474,7 @@ const size_t bytes_read = m_process->ReadMemory (m_dyld_all_image_infos_addr, buf, count, error); if (bytes_read == count) { - DataExtractor data(buf, count, endian, addr_size); - uint32_t offset = 0; + offset = 0; m_dyld_all_image_infos.version = data.GetU32(&offset); m_dyld_all_image_infos.dylib_info_count = data.GetU32(&offset); m_dyld_all_image_infos.dylib_info_addr = data.GetPointer(&offset); @@ -486,6 +508,7 @@ m_dyld_all_image_infos.notification = m_dyld_all_image_infos.dyldImageLoadAddress + notification_offset; } } + m_dyld_all_image_infos_stop_id = m_process->GetStopID(); return true; } } @@ -504,6 +527,9 @@ if (ReadAllImageInfosStructure ()) { Mutex::Locker locker(m_mutex); + if (m_process->GetStopID() == m_dyld_image_infos_stop_id) + m_dyld_image_infos.size(); + uint32_t idx; uint32_t i = 0; DYLDImageInfo::collection old_dyld_all_image_infos; @@ -511,8 +537,8 @@ // If we made it here, we are assuming that the all dylib info data should // be valid, lets read the info array. - const ByteOrder endian = m_process->GetByteOrder(); - const uint32_t addr_size = m_process->GetAddressByteSize(); + const ByteOrder endian = m_dyld.GetByteOrder(); + const uint32_t addr_size = m_dyld.GetAddressByteSize(); if (m_dyld_all_image_infos.dylib_info_count > 0) { @@ -605,6 +631,7 @@ if (log) PutToLog(log.get()); } + m_dyld_image_infos_stop_id = m_process->GetStopID(); } else { Modified: lldb/trunk/source/Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderMacOSXDYLD.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderMacOSXDYLD.h?rev=119680&r1=119679&r2=119680&view=diff ============================================================================== --- lldb/trunk/source/Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderMacOSXDYLD.h (original) +++ lldb/trunk/source/Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderMacOSXDYLD.h Wed Nov 17 23:57:03 2010 @@ -266,6 +266,41 @@ return uuid.IsValid(); } + uint32_t + GetAddressByteSize () + { + if (header.cputype) + { + if (header.cputype & llvm::MachO::CPUArchABI64) + return 8; + else + return 4; + } + return 0; + } + + lldb::ByteOrder + GetByteOrder() + { + switch (header.magic) + { + case llvm::MachO::HeaderMagic32: // MH_MAGIC + case llvm::MachO::HeaderMagic64: // MH_MAGIC_64 + return lldb::eByteOrderHost; + + case llvm::MachO::HeaderMagic32Swapped: // MH_CIGAM + case llvm::MachO::HeaderMagic64Swapped: // MH_CIGAM_64 + if (lldb::eByteOrderHost == lldb::eByteOrderLittle) + return lldb::eByteOrderBig; + else + return lldb::eByteOrderLittle; + default: + assert (!"invalid header.magic value"); + break; + } + return lldb::eByteOrderHost; + } + const Segment * FindSegment (const lldb_private::ConstString &name) const; @@ -348,8 +383,10 @@ DYLDImageInfo m_dyld; // Info about the curent dyld being used lldb::addr_t m_dyld_all_image_infos_addr; DYLDAllImageInfos m_dyld_all_image_infos; + uint32_t m_dyld_all_image_infos_stop_id; lldb::user_id_t m_break_id; DYLDImageInfo::collection m_dyld_image_infos; // Current shared libraries information + uint32_t m_dyld_image_infos_stop_id; // The process stop ID that "m_dyld_image_infos" is valid for mutable lldb_private::Mutex m_mutex; lldb_private::Process::Notifications m_notification_callbacks; Modified: lldb/trunk/source/Plugins/Process/MacOSX-User/source/ProcessMacOSX.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Plugins/Process/MacOSX-User/source/ProcessMacOSX.cpp?rev=119680&r1=119679&r2=119680&view=diff ============================================================================== --- lldb/trunk/source/Plugins/Process/MacOSX-User/source/ProcessMacOSX.cpp (original) +++ lldb/trunk/source/Plugins/Process/MacOSX-User/source/ProcessMacOSX.cpp Wed Nov 17 23:57:03 2010 @@ -235,9 +235,7 @@ m_exception_messages (), m_exception_messages_mutex (Mutex::eMutexTypeRecursive), m_arch_spec (), - m_dynamic_loader_ap (), -// m_wait_thread (LLDB_INVALID_HOST_THREAD), - m_byte_order (eByteOrderHost) + m_dynamic_loader_ap () { } @@ -676,6 +674,7 @@ Error ProcessMacOSX::DoHalt (bool &caused_stop) { + caused_stop = true; return Signal (SIGSTOP); } Modified: lldb/trunk/source/Plugins/Process/MacOSX-User/source/ProcessMacOSX.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Plugins/Process/MacOSX-User/source/ProcessMacOSX.h?rev=119680&r1=119679&r2=119680&view=diff ============================================================================== --- lldb/trunk/source/Plugins/Process/MacOSX-User/source/ProcessMacOSX.h (original) +++ lldb/trunk/source/Plugins/Process/MacOSX-User/source/ProcessMacOSX.h Wed Nov 17 23:57:03 2010 @@ -247,8 +247,6 @@ lldb_private::Mutex m_exception_messages_mutex; // Multithreaded protection for m_exception_messages lldb_private::ArchSpec m_arch_spec; std::auto_ptr m_dynamic_loader_ap; -// lldb::thread_t m_wait_thread; - lldb::ByteOrder m_byte_order; //---------------------------------------------------------------------- // Child process control Modified: lldb/trunk/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp?rev=119680&r1=119679&r2=119680&view=diff ============================================================================== --- lldb/trunk/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp (original) +++ lldb/trunk/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp Wed Nov 17 23:57:03 2010 @@ -105,7 +105,6 @@ m_dynamic_loader_ap (), m_flags (0), m_stdio_mutex (Mutex::eMutexTypeRecursive), - m_byte_order (eByteOrderHost), m_gdb_comm(), m_debugserver_pid (LLDB_INVALID_PROCESS_ID), m_debugserver_thread (LLDB_INVALID_HOST_THREAD), @@ -339,13 +338,13 @@ } Error -ProcessGDBRemote::WillAttach (lldb::pid_t pid) +ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid) { return WillLaunchOrAttach (); } Error -ProcessGDBRemote::WillAttach (const char *process_name, bool wait_for_launch) +ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch) { return WillLaunchOrAttach (); } @@ -556,8 +555,6 @@ if (response.IsOKPacket()) m_gdb_comm.SetAckMode (false); } - - BuildDynamicRegisterInfo (); } return error; } @@ -574,22 +571,23 @@ { m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS; - Module * exe_module = GetTarget().GetExecutableModule ().get(); + BuildDynamicRegisterInfo (); + + m_byte_order = m_gdb_comm.GetByteOrder(); + + Module * exe_module = GetTarget().GetExecutableModule().get(); assert(exe_module); ObjectFile *exe_objfile = exe_module->GetObjectFile(); assert(exe_objfile); - m_byte_order = exe_objfile->GetByteOrder(); - assert (m_byte_order != eByteOrderInvalid); - StreamString strm; ArchSpec inferior_arch; // See if the GDB server supports the qHostInfo information const char *vendor = m_gdb_comm.GetVendorString().AsCString(); const char *os_type = m_gdb_comm.GetOSString().AsCString(); - ArchSpec arch_spec = GetTarget().GetArchitecture(); + ArchSpec arch_spec (GetTarget().GetArchitecture()); if (arch_spec.IsValid() && arch_spec == ArchSpec ("arm")) { @@ -858,25 +856,8 @@ void ProcessGDBRemote::DidAttach () { - // If we haven't got an executable module yet, then we should make a dynamic loader, and - // see if it can find the executable module for us. If we do have an executable module, - // make sure it matches the process we've just attached to. - - ModuleSP exe_module_sp = GetTarget().GetExecutableModule(); - if (!m_dynamic_loader_ap.get()) - { - m_dynamic_loader_ap.reset(DynamicLoader::FindPlugin(this, "dynamic-loader.macosx-dyld")); - } - if (m_dynamic_loader_ap.get()) m_dynamic_loader_ap->DidAttach(); - - Module * new_exe_module = GetTarget().GetExecutableModule().get(); - if (new_exe_module == NULL) - { - - } - DidLaunchOrAttach (); } @@ -1124,45 +1105,26 @@ ProcessGDBRemote::DoHalt (bool &caused_stop) { Error error; - caused_stop = false; if (m_gdb_comm.IsRunning()) { - PausePrivateStateThread(); + caused_stop = true; bool timed_out = false; Mutex::Locker locker; - if (m_gdb_comm.SendInterrupt (locker, 2, &timed_out)) - { - EventSP event_sp; - TimeValue timeout_time; - timeout_time = TimeValue::Now(); - timeout_time.OffsetWithSeconds(2); - - StateType state = WaitForStateChangedEventsPrivate (&timeout_time, event_sp); - - if (!StateIsStoppedState (state)) - { - LogSP log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); - if (log) - log->Printf("ProcessGDBRemote::DoHalt() failed to stop after sending interrupt"); - error.SetErrorString ("Did not get stopped event after interrupt succeeded."); - } - else - caused_stop = true; - } - else + if (!m_gdb_comm.SendInterrupt (locker, 2, &timed_out)) { if (timed_out) error.SetErrorString("timed out sending interrupt packet"); else error.SetErrorString("unknown error sending interrupt packet"); } - - // Resume the private state thread at this point. - ResumePrivateStateThread(); - } + else + { + caused_stop = false; + } + return error; } @@ -1265,12 +1227,6 @@ return error; } -ByteOrder -ProcessGDBRemote::GetByteOrder () const -{ - return m_byte_order; -} - //------------------------------------------------------------------ // Process Queries //------------------------------------------------------------------ Modified: lldb/trunk/source/Plugins/Process/gdb-remote/ProcessGDBRemote.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Plugins/Process/gdb-remote/ProcessGDBRemote.h?rev=119680&r1=119679&r2=119680&view=diff ============================================================================== --- lldb/trunk/source/Plugins/Process/gdb-remote/ProcessGDBRemote.h (original) +++ lldb/trunk/source/Plugins/Process/gdb-remote/ProcessGDBRemote.h Wed Nov 17 23:57:03 2010 @@ -90,10 +90,10 @@ DidLaunch (); virtual lldb_private::Error - WillAttach (lldb::pid_t pid); + WillAttachToProcessWithID (lldb::pid_t pid); virtual lldb_private::Error - WillAttach (const char *process_name, bool wait_for_launch); + WillAttachToProcessWithName (const char *process_name, bool wait_for_launch); lldb_private::Error WillLaunchOrAttach (); @@ -215,9 +215,6 @@ virtual lldb_private::Error DisableWatchpoint (lldb_private::WatchpointLocation *wp_loc); - virtual lldb::ByteOrder - GetByteOrder () const; - virtual lldb_private::DynamicLoader * GetDynamicLoader (); @@ -322,7 +319,6 @@ std::auto_ptr m_dynamic_loader_ap; lldb_private::Flags m_flags; // Process specific flags (see eFlags enums) lldb_private::Mutex m_stdio_mutex; // Multithreaded protection for stdio - lldb::ByteOrder m_byte_order; GDBRemoteCommunication m_gdb_comm; lldb::pid_t m_debugserver_pid; lldb::thread_t m_debugserver_thread; Modified: lldb/trunk/source/Target/Process.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Target/Process.cpp?rev=119680&r1=119679&r2=119680&view=diff ============================================================================== --- lldb/trunk/source/Target/Process.cpp (original) +++ lldb/trunk/source/Target/Process.cpp Wed Nov 17 23:57:03 2010 @@ -85,12 +85,19 @@ m_exit_string (), m_thread_list (this), m_notifications (), - m_persistent_vars(), - m_listener(listener), + m_image_tokens (), + m_listener (listener), + m_breakpoint_site_list (), + m_persistent_vars (), + m_dynamic_checkers_ap (), m_unix_signals (), + m_target_triple (), + m_byte_order (eByteOrderHost), + m_addr_byte_size (0), + m_abi_sp (), m_process_input_reader (), m_stdio_communication ("lldb.process.stdio"), - m_stdio_comm_mutex (Mutex::eMutexTypeRecursive), + m_stdio_communication_mutex (Mutex::eMutexTypeRecursive), m_stdout_data () { UpdateInstanceName(); @@ -1438,19 +1445,71 @@ if (error.Success()) { - bool caused_stop; + + bool caused_stop = false; + EventSP event_sp; + + // Pause our private state thread so we can ensure no one else eats + // the stop event out from under us. + PausePrivateStateThread(); + + // Ask the process subclass to actually halt our process error = DoHalt(caused_stop); if (error.Success()) { - DidHalt(); + // If "caused_stop" is true, then DoHalt stopped the process. If + // "caused_stop" is false, the process was already stopped. + // If the DoHalt caused the process to stop, then we want to catch + // this event and set the interrupted bool to true before we pass + // this along so clients know that the process was interrupted by + // a halt command. if (caused_stop) { - ProcessEventData *new_data = new ProcessEventData (GetTarget().GetProcessSP(), eStateStopped); - new_data->SetInterrupted(true); - BroadcastEvent (eBroadcastBitStateChanged, new_data); + // Wait for 2 seconds for the process to stop. + TimeValue timeout_time; + timeout_time = TimeValue::Now(); + timeout_time.OffsetWithSeconds(2); + StateType state = WaitForStateChangedEventsPrivate (&timeout_time, event_sp); + + if (state == eStateInvalid) + { + // We timeout out and didn't get a stop event... + error.SetErrorString ("Halt timed out."); + } + else + { + // Since we are eating the event, we need to update our state + // otherwise the process state will not match reality... + SetPublicState(state); + + if (StateIsStoppedState (state)) + { + // We caused the process to interrupt itself, so mark this + // as such in the stop event so clients can tell an interrupted + // process from a natural stop + ProcessEventData::SetInterruptedInEvent (event_sp.get(), true); + } + else + { + LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); + if (log) + log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state)); + error.SetErrorString ("Did not get stopped event after halt."); + } + } } + DidHalt(); + } - + // Resume our private state thread before we post the event (if any) + ResumePrivateStateThread(); + + // Post any event we might have consumed. If all goes well, we will have + // stopped the process, intercepted the event and set the interrupted + // bool in the event. + if (event_sp) + BroadcastEvent(event_sp); + } return error; } @@ -1530,7 +1589,9 @@ uint32_t Process::GetAddressByteSize() { - return m_target.GetArchitecture().GetAddressByteSize(); + if (m_addr_byte_size == 0) + return m_target.GetArchitecture().GetAddressByteSize(); + return m_addr_byte_size; } bool @@ -1603,8 +1664,8 @@ // If no thread has an opinion, we don't report it. if (ProcessEventData::GetInterruptedFromEvent (event_ptr)) { - if (log) - log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s", event_ptr, StateAsCString(state)); + if (log) + log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s", event_ptr, StateAsCString(state)); return true; } else @@ -2074,7 +2135,7 @@ void Process::AppendSTDOUT (const char * s, size_t len) { - Mutex::Locker locker (m_stdio_comm_mutex); + Mutex::Locker locker (m_stdio_communication_mutex); m_stdout_data.append (s, len); BroadcastEventIfUnique (eBroadcastBitSTDOUT); Modified: lldb/trunk/tools/debugserver/debugserver.xcodeproj/project.pbxproj URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/debugserver/debugserver.xcodeproj/project.pbxproj?rev=119680&r1=119679&r2=119680&view=diff ============================================================================== --- lldb/trunk/tools/debugserver/debugserver.xcodeproj/project.pbxproj (original) +++ lldb/trunk/tools/debugserver/debugserver.xcodeproj/project.pbxproj Wed Nov 17 23:57:03 2010 @@ -7,6 +7,7 @@ objects = { /* Begin PBXBuildFile section */ + 264D5D581293835600ED4C01 /* DNBArch.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 264D5D571293835600ED4C01 /* DNBArch.cpp */; }; 2660D9CE1192280900958FBD /* StringExtractor.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 2660D9CC1192280900958FBD /* StringExtractor.cpp */; }; 26CE05A7115C360D0022F371 /* DNBError.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 26C637DE0C71334A0024798E /* DNBError.cpp */; }; 26CE05A8115C36170022F371 /* DNBThreadResumeActions.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 260E7331114BFFE600D1DFB3 /* DNBThreadResumeActions.cpp */; }; @@ -48,6 +49,7 @@ 260E7332114BFFE600D1DFB3 /* DNBThreadResumeActions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = DNBThreadResumeActions.h; sourceTree = ""; }; 260FC7320E5B290400043FC9 /* debugnub-exports */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = "debugnub-exports"; sourceTree = SOURCE_ROOT; }; 26242C390DDBD33C0054A4CC /* debugserver-entitlements.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = "debugserver-entitlements.plist"; sourceTree = ""; }; + 264D5D571293835600ED4C01 /* DNBArch.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = DNBArch.cpp; sourceTree = ""; }; 26593A060D4931CC001C9FE3 /* ChangeLog */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = ChangeLog; sourceTree = ""; }; 2660D9CC1192280900958FBD /* StringExtractor.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = StringExtractor.cpp; path = ../../source/Utility/StringExtractor.cpp; sourceTree = SOURCE_ROOT; }; 2660D9CD1192280900958FBD /* StringExtractor.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = StringExtractor.h; path = ../../source/Utility/StringExtractor.h; sourceTree = SOURCE_ROOT; }; @@ -190,6 +192,7 @@ 26C637D70C71334A0024798E /* DNB.h */, 26C637D60C71334A0024798E /* DNB.cpp */, 26C637D80C71334A0024798E /* DNBArch.h */, + 264D5D571293835600ED4C01 /* DNBArch.cpp */, 26C637DA0C71334A0024798E /* DNBBreakpoint.h */, 26C637D90C71334A0024798E /* DNBBreakpoint.cpp */, 26C637DC0C71334A0024798E /* DNBDataRef.h */, @@ -441,6 +444,7 @@ 26CE05C5115C36590022F371 /* CFBundle.cpp in Sources */, 26CE05F1115C387C0022F371 /* PseudoTerminal.cpp in Sources */, 2660D9CE1192280900958FBD /* StringExtractor.cpp in Sources */, + 264D5D581293835600ED4C01 /* DNBArch.cpp in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; Modified: lldb/trunk/tools/debugserver/source/DNB.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/debugserver/source/DNB.cpp?rev=119680&r1=119679&r2=119680&view=diff ============================================================================== --- lldb/trunk/tools/debugserver/source/DNB.cpp (original) +++ lldb/trunk/tools/debugserver/source/DNB.cpp Wed Nov 17 23:57:03 2010 @@ -265,10 +265,8 @@ DNBLogError ("%6u - %s\n", matching_proc_infos[i].kp_proc.p_pid, matching_proc_infos[i].kp_proc.p_comm); return INVALID_NUB_PROCESS; } - else - { - return DNBProcessAttach (matching_proc_infos[0].kp_proc.p_pid, timeout, err_str, err_len); - } + + return DNBProcessAttach (matching_proc_infos[0].kp_proc.p_pid, timeout, err_str, err_len); } nub_process_t @@ -294,15 +292,20 @@ while (pid != INVALID_NUB_PROCESS) { // Wait for process to start up and hit entry point - DNBLogThreadedIf (LOG_PROCESS, "%s DNBProcessWaitForEvent (%4.4x, eEventProcessRunningStateChanged " - "| eEventProcessStoppedStateChanged, true, INFINITE)...", - __FUNCTION__, pid); + DNBLogThreadedIf (LOG_PROCESS, + "%s DNBProcessWaitForEvent (%4.4x, eEventProcessRunningStateChanged | eEventProcessStoppedStateChanged, true, INFINITE)...", + __FUNCTION__, + pid); nub_event_t set_events = DNBProcessWaitForEvents (pid, - eEventProcessRunningStateChanged | eEventProcessStoppedStateChanged, - true, timeout); - DNBLogThreadedIf (LOG_PROCESS, "%s DNBProcessWaitForEvent (%4.4x, eEventProcessRunningStateChanged " - "| eEventProcessStoppedStateChanged, true, INFINITE) => 0x%8.8x", - __FUNCTION__, pid, set_events); + eEventProcessRunningStateChanged | eEventProcessStoppedStateChanged, + true, + timeout); + + DNBLogThreadedIf (LOG_PROCESS, + "%s DNBProcessWaitForEvent (%4.4x, eEventProcessRunningStateChanged | eEventProcessStoppedStateChanged, true, INFINITE) => 0x%8.8x", + __FUNCTION__, + pid, + set_events); if (set_events == 0) { @@ -320,29 +323,30 @@ switch (pid_state) { - default: - case eStateInvalid: - case eStateUnloaded: - case eStateAttaching: - case eStateLaunching: - case eStateSuspended: - break; // Ignore - - case eStateRunning: - case eStateStepping: - // Still waiting to stop at entry point... - break; - - case eStateStopped: - case eStateCrashed: - return pid; - case eStateDetached: - case eStateExited: - if (err_str && err_len > 0) - snprintf(err_str, err_len, "process exited"); - return INVALID_NUB_PROCESS; - } - } + default: + case eStateInvalid: + case eStateUnloaded: + case eStateAttaching: + case eStateLaunching: + case eStateSuspended: + break; // Ignore + + case eStateRunning: + case eStateStepping: + // Still waiting to stop at entry point... + break; + + case eStateStopped: + case eStateCrashed: + return pid; + + case eStateDetached: + case eStateExited: + if (err_str && err_len > 0) + snprintf(err_str, err_len, "process exited"); + return INVALID_NUB_PROCESS; + } + } DNBProcessResetEvents(pid, set_events); } @@ -352,7 +356,7 @@ } static size_t -GetAllInfos(std::vector& proc_infos) +GetAllInfos (std::vector& proc_infos) { size_t size; int name[] = { CTL_KERN, KERN_PROC, KERN_PROC_ALL }; @@ -1722,7 +1726,7 @@ const DNBRegisterSetInfo * DNBGetRegisterSetInfo (nub_size_t *num_reg_sets) { - return DNBArch::GetRegisterSetInfo (num_reg_sets); + return DNBArchProtocol::GetRegisterSetInfo (num_reg_sets); } @@ -1998,3 +2002,20 @@ return false; } + +void +DNBInitialize() +{ + DNBLogThreadedIf (LOG_PROCESS, "DNBInitialize ()"); +#if defined (__i386__) || defined (__x86_64__) + DNBArchImplI386::Initialize(); + DNBArchImplX86_64::Initialize(); +#elif defined (__arm__) + DNBArchMachARM::Initialize(); +#endif +} + +void +DNBTerminate() +{ +} Modified: lldb/trunk/tools/debugserver/source/DNB.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/debugserver/source/DNB.h?rev=119680&r1=119679&r2=119680&view=diff ============================================================================== --- lldb/trunk/tools/debugserver/source/DNB.h (original) +++ lldb/trunk/tools/debugserver/source/DNB.h Wed Nov 17 23:57:03 2010 @@ -25,6 +25,9 @@ typedef bool (*DNBShouldCancelCallback) (void *); +void DNBInitialize (); +void DNBTerminate (); + //---------------------------------------------------------------------- // Process control //---------------------------------------------------------------------- Modified: lldb/trunk/tools/debugserver/source/DNBArch.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/debugserver/source/DNBArch.h?rev=119680&r1=119679&r2=119680&view=diff ============================================================================== --- lldb/trunk/tools/debugserver/source/DNBArch.h (original) +++ lldb/trunk/tools/debugserver/source/DNBArch.h Wed Nov 17 23:57:03 2010 @@ -22,13 +22,39 @@ struct DNBRegisterValue; struct DNBRegisterSetInfo; +class DNBArchProtocol; +class MachThread; + +typedef DNBArchProtocol * (* DNBArchCallbackCreate)(MachThread *thread); +typedef const DNBRegisterSetInfo * (* DNBArchCallbackGetRegisterSetInfo)(nub_size_t *num_reg_sets); +typedef const uint8_t * const (* DNBArchCallbackGetBreakpointOpcode)(nub_size_t byte_size); + +typedef struct DNBArchPluginInfoTag +{ + uint32_t cpu_type; + DNBArchCallbackCreate Create; + DNBArchCallbackGetRegisterSetInfo GetRegisterSetInfo; + DNBArchCallbackGetBreakpointOpcode GetBreakpointOpcode; +} DNBArchPluginInfo; class DNBArchProtocol { public: - static const DNBRegisterSetInfo * + static DNBArchProtocol * + Create (MachThread *thread); + + static const DNBRegisterSetInfo * GetRegisterSetInfo (nub_size_t *num_reg_sets); + static const uint8_t * const + GetBreakpointOpcode (nub_size_t byte_size); + + static void + RegisterArchPlugin (const DNBArchPluginInfo &arch_info); + + static void + SetDefaultArchitecture (uint32_t cpu_type); + virtual bool GetRegisterValue (int set, int reg, DNBRegisterValue *value) = 0; virtual bool SetRegisterValue (int set, int reg, const DNBRegisterValue *value) = 0; virtual nub_size_t GetRegisterContext (void *buf, nub_size_t buf_len) = 0; @@ -39,6 +65,7 @@ virtual bool RegisterSetStateIsValid (int set) const = 0; virtual uint64_t GetPC (uint64_t failValue) = 0; // Get program counter + virtual kern_return_t SetPC (uint64_t value) = 0; virtual uint64_t GetSP (uint64_t failValue) = 0; // Get stack pointer virtual void ThreadWillResume () = 0; virtual bool ThreadDidStop () = 0; Modified: lldb/trunk/tools/debugserver/source/MacOSX/MachProcess.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/debugserver/source/MacOSX/MachProcess.cpp?rev=119680&r1=119679&r2=119680&view=diff ============================================================================== --- lldb/trunk/tools/debugserver/source/MacOSX/MachProcess.cpp (original) +++ lldb/trunk/tools/debugserver/source/MacOSX/MachProcess.cpp Wed Nov 17 23:57:03 2010 @@ -115,6 +115,7 @@ m_image_infos_baton(NULL) { DNBLogThreadedIf(LOG_PROCESS | LOG_VERBOSE, "%s", __PRETTY_FUNCTION__); + bzero(&m_arch_plugin_info, sizeof(m_arch_plugin_info)); } MachProcess::~MachProcess() @@ -208,7 +209,15 @@ const DNBRegisterSetInfo * MachProcess::GetRegisterSetInfo(nub_thread_t tid, nub_size_t *num_reg_sets ) const { - return DNBArch::GetRegisterSetInfo (num_reg_sets); + MachThread *thread = m_thread_list.GetThreadByID (tid); + if (thread) + { + DNBArchProtocol *arch = thread->GetArchProtocol(); + if (arch) + return arch->GetRegisterSetInfo (num_reg_sets); + } + *num_reg_sets = 0; + return NULL; } bool @@ -766,7 +775,7 @@ const nub_size_t break_op_size = bp->ByteSize(); assert (break_op_size > 0); - const uint8_t * const break_op = DNBArch::SoftwareBreakpointOpcode(bp->ByteSize()); + const uint8_t * const break_op = DNBArchProtocol::GetBreakpointOpcode (bp->ByteSize()); if (break_op_size > 0) { // Clear a software breakoint instruction @@ -954,7 +963,7 @@ const nub_size_t break_op_size = bp->ByteSize(); assert (break_op_size != 0); - const uint8_t * const break_op = DNBArch::SoftwareBreakpointOpcode(break_op_size); + const uint8_t * const break_op = DNBArchProtocol::GetBreakpointOpcode (break_op_size); if (break_op_size > 0) { // Save the original opcode by reading it @@ -1507,7 +1516,14 @@ break; case eLaunchFlavorPosixSpawn: - m_pid = MachProcess::PosixSpawnChildForPTraceDebugging (path, argv, envp, stdio_path, this, disable_aslr, launch_err); + m_pid = MachProcess::PosixSpawnChildForPTraceDebugging (path, + m_arch_plugin_info.cpu_type, + argv, + envp, + stdio_path, + this, + disable_aslr, + launch_err); break; #if defined (__arm__) @@ -1590,6 +1606,7 @@ MachProcess::PosixSpawnChildForPTraceDebugging ( const char *path, + cpu_type_t cpu_type, char const *argv[], char const *envp[], const char *stdio_path, @@ -1628,7 +1645,6 @@ // We don't need to do this for ARM, and we really shouldn't now that we // have multiple CPU subtypes and no posix_spawnattr call that allows us // to set which CPU subtype to launch... - cpu_type_t cpu_type = DNBArch::GetCPUType(); size_t ocount = 0; err.SetError( ::posix_spawnattr_setbinpref_np (&attr, 1, &cpu_type, &ocount), DNBError::POSIX); if (err.Fail() || DNBLogCheckLogBit(LOG_PROCESS)) Modified: lldb/trunk/tools/debugserver/source/MacOSX/MachProcess.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/debugserver/source/MacOSX/MachProcess.h?rev=119680&r1=119679&r2=119680&view=diff ============================================================================== --- lldb/trunk/tools/debugserver/source/MacOSX/MachProcess.h (original) +++ lldb/trunk/tools/debugserver/source/MacOSX/MachProcess.h Wed Nov 17 23:57:03 2010 @@ -48,7 +48,7 @@ pid_t AttachForDebug (pid_t pid, char *err_str, size_t err_len); pid_t LaunchForDebug (const char *path, char const *argv[], char const *envp[], const char *stdio_path, nub_launch_flavor_t launch_flavor, int disable_aslr, DNBError &err); static pid_t ForkChildForPTraceDebugging (const char *path, char const *argv[], char const *envp[], MachProcess* process, DNBError &err); - static pid_t PosixSpawnChildForPTraceDebugging (const char *path, char const *argv[], char const *envp[], const char *stdio_path, MachProcess* process, int disable_aslr, DNBError& err); + static pid_t PosixSpawnChildForPTraceDebugging (const char *path, cpu_type_t cpu_type, char const *argv[], char const *envp[], const char *stdio_path, MachProcess* process, int disable_aslr, DNBError& err); nub_addr_t GetDYLDAllImageInfosAddress (); static const void * PrepareForAttach (const char *path, nub_launch_flavor_t launch_flavor, bool waitfor, DNBError &err_str); static void CleanupAfterAttach (const void *attach_token, bool success, DNBError &err_str); @@ -254,6 +254,7 @@ DNBCallbackCopyExecutableImageInfos m_image_infos_callback; void * m_image_infos_baton; + DNBArchPluginInfo m_arch_plugin_info; }; Modified: lldb/trunk/tools/debugserver/source/MacOSX/MachThread.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/debugserver/source/MacOSX/MachThread.cpp?rev=119680&r1=119679&r2=119680&view=diff ============================================================================== --- lldb/trunk/tools/debugserver/source/MacOSX/MachThread.cpp (original) +++ lldb/trunk/tools/debugserver/source/MacOSX/MachThread.cpp Wed Nov 17 23:57:03 2010 @@ -31,14 +31,9 @@ m_state_mutex (PTHREAD_MUTEX_RECURSIVE), m_breakID (INVALID_NUB_BREAK_ID), m_suspendCount (0), - m_arch (this), - m_regSets () + m_arch_ap (DNBArchProtocol::Create (this)), + m_reg_sets (m_arch_ap->GetRegisterSetInfo (&n_num_reg_sets)) { - nub_size_t num_reg_sets = 0; - const DNBRegisterSetInfo *regSetInfo = m_arch.GetRegisterSetInfo(&num_reg_sets); - if (num_reg_sets > 0) - m_regSets.assign(regSetInfo, regSetInfo + num_reg_sets); - // Get the thread state so we know if a thread is in a state where we can't // muck with it and also so we get the suspend count correct in case it was // already suspended @@ -251,34 +246,34 @@ bool MachThread::GetRegisterState(int flavor, bool force) { - return m_arch.GetRegisterState(flavor, force) == KERN_SUCCESS; + return m_arch_ap->GetRegisterState(flavor, force) == KERN_SUCCESS; } bool MachThread::SetRegisterState(int flavor) { - return m_arch.SetRegisterState(flavor) == KERN_SUCCESS; + return m_arch_ap->SetRegisterState(flavor) == KERN_SUCCESS; } uint64_t MachThread::GetPC(uint64_t failValue) { // Get program counter - return m_arch.GetPC(failValue); + return m_arch_ap->GetPC(failValue); } bool MachThread::SetPC(uint64_t value) { // Set program counter - return m_arch.SetPC(value); + return m_arch_ap->SetPC(value); } uint64_t MachThread::GetSP(uint64_t failValue) { // Get stack pointer - return m_arch.GetSP(failValue); + return m_arch_ap->GetSP(failValue); } nub_process_t @@ -342,7 +337,7 @@ Resume(); break; } - m_arch.ThreadWillResume(); + m_arch_ap->ThreadWillResume(); m_stop_exception.Clear(); } @@ -372,7 +367,7 @@ } else { - if (m_arch.StepNotComplete()) + if (m_arch_ap->StepNotComplete()) { step_more = true; return false; @@ -426,7 +421,7 @@ // When this method gets called, the process state is still in the // state it was in while running so we can act accordingly. - m_arch.ThreadDidStop(); + m_arch_ap->ThreadDidStop(); // We may have suspended this thread so the primary thread could step @@ -499,7 +494,7 @@ { m_stop_exception = exc; } - bool handled = m_arch.NotifyException(exc); + bool handled = m_arch_ap->NotifyException(exc); if (!handled) { handled = true; @@ -551,25 +546,25 @@ uint32_t MachThread::GetNumRegistersInSet(int regSet) const { - if (regSet < m_regSets.size()) - return m_regSets[regSet].num_registers; + if (regSet < n_num_reg_sets) + return m_reg_sets[regSet].num_registers; return 0; } const char * MachThread::GetRegisterSetName(int regSet) const { - if (regSet < m_regSets.size()) - return m_regSets[regSet].name; + if (regSet < n_num_reg_sets) + return m_reg_sets[regSet].name; return NULL; } const DNBRegisterInfo * MachThread::GetRegisterInfo(int regSet, int regIndex) const { - if (regSet < m_regSets.size()) - if (regIndex < m_regSets[regSet].num_registers) - return &m_regSets[regSet].registers[regIndex]; + if (regSet < n_num_reg_sets) + if (regIndex < m_reg_sets[regSet].num_registers) + return &m_reg_sets[regSet].registers[regIndex]; return NULL; } void @@ -577,19 +572,19 @@ { if (regSet == REGISTER_SET_ALL) { - for (regSet = 1; regSet < m_regSets.size(); regSet++) + for (regSet = 1; regSet < n_num_reg_sets; regSet++) DumpRegisterState(regSet); } else { - if (m_arch.RegisterSetStateIsValid(regSet)) + if (m_arch_ap->RegisterSetStateIsValid(regSet)) { const size_t numRegisters = GetNumRegistersInSet(regSet); size_t regIndex = 0; DNBRegisterValueClass reg; for (regIndex = 0; regIndex < numRegisters; ++regIndex) { - if (m_arch.GetRegisterValue(regSet, regIndex, ®)) + if (m_arch_ap->GetRegisterValue(regSet, regIndex, ®)) { reg.Dump(NULL, NULL); } @@ -605,39 +600,39 @@ const DNBRegisterSetInfo * MachThread::GetRegisterSetInfo(nub_size_t *num_reg_sets ) const { - *num_reg_sets = m_regSets.size(); - return &m_regSets[0]; + *num_reg_sets = n_num_reg_sets; + return &m_reg_sets[0]; } bool MachThread::GetRegisterValue ( uint32_t set, uint32_t reg, DNBRegisterValue *value ) { - return m_arch.GetRegisterValue(set, reg, value); + return m_arch_ap->GetRegisterValue(set, reg, value); } bool MachThread::SetRegisterValue ( uint32_t set, uint32_t reg, const DNBRegisterValue *value ) { - return m_arch.SetRegisterValue(set, reg, value); + return m_arch_ap->SetRegisterValue(set, reg, value); } nub_size_t MachThread::GetRegisterContext (void *buf, nub_size_t buf_len) { - return m_arch.GetRegisterContext(buf, buf_len); + return m_arch_ap->GetRegisterContext(buf, buf_len); } nub_size_t MachThread::SetRegisterContext (const void *buf, nub_size_t buf_len) { - return m_arch.SetRegisterContext(buf, buf_len); + return m_arch_ap->SetRegisterContext(buf, buf_len); } uint32_t MachThread::EnableHardwareBreakpoint (const DNBBreakpoint *bp) { if (bp != NULL && bp->IsBreakpoint()) - return m_arch.EnableHardwareBreakpoint(bp->Address(), bp->ByteSize()); + return m_arch_ap->EnableHardwareBreakpoint(bp->Address(), bp->ByteSize()); return INVALID_NUB_HW_INDEX; } @@ -645,7 +640,7 @@ MachThread::EnableHardwareWatchpoint (const DNBBreakpoint *wp) { if (wp != NULL && wp->IsWatchpoint()) - return m_arch.EnableHardwareWatchpoint(wp->Address(), wp->ByteSize(), wp->WatchpointRead(), wp->WatchpointWrite()); + return m_arch_ap->EnableHardwareWatchpoint(wp->Address(), wp->ByteSize(), wp->WatchpointRead(), wp->WatchpointWrite()); return INVALID_NUB_HW_INDEX; } @@ -653,7 +648,7 @@ MachThread::DisableHardwareBreakpoint (const DNBBreakpoint *bp) { if (bp != NULL && bp->IsHardware()) - return m_arch.DisableHardwareBreakpoint(bp->GetHardwareIndex()); + return m_arch_ap->DisableHardwareBreakpoint(bp->GetHardwareIndex()); return false; } @@ -661,7 +656,7 @@ MachThread::DisableHardwareWatchpoint (const DNBBreakpoint *wp) { if (wp != NULL && wp->IsHardware()) - return m_arch.DisableHardwareWatchpoint(wp->GetHardwareIndex()); + return m_arch_ap->DisableHardwareWatchpoint(wp->GetHardwareIndex()); return false; } Modified: lldb/trunk/tools/debugserver/source/MacOSX/MachThread.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/debugserver/source/MacOSX/MachThread.h?rev=119680&r1=119679&r2=119680&view=diff ============================================================================== --- lldb/trunk/tools/debugserver/source/MacOSX/MachThread.h (original) +++ lldb/trunk/tools/debugserver/source/MacOSX/MachThread.h Wed Nov 17 23:57:03 2010 @@ -95,6 +95,13 @@ GetBasicInfo (); const char * GetBasicInfoAsString () const; const char * GetName (); + + DNBArchProtocol* + GetArchProtocol() + { + return m_arch_ap.get(); + } + protected: static bool GetBasicInfo(thread_t threadID, struct thread_basic_info *basic_info); @@ -113,8 +120,9 @@ struct thread_basic_info m_basicInfo; // Basic information for a thread used to see if a thread is valid uint32_t m_suspendCount; // The current suspend count MachException::Data m_stop_exception; // The best exception that describes why this thread is stopped - DNBArch m_arch; // Arch specific information for register state and more - std::vector m_regSets; // Register set information for this thread + std::auto_ptr m_arch_ap; // Arch specific information for register state and more + const DNBRegisterSetInfo *const m_reg_sets; // Register set information for this thread + nub_size_t n_num_reg_sets; #ifdef THREAD_IDENTIFIER_INFO_COUNT thread_identifier_info_data_t m_ident_info; struct proc_threadinfo m_proc_threadinfo; Modified: lldb/trunk/tools/debugserver/source/MacOSX/MachThreadList.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/debugserver/source/MacOSX/MachThreadList.cpp?rev=119680&r1=119679&r2=119680&view=diff ============================================================================== --- lldb/trunk/tools/debugserver/source/MacOSX/MachThreadList.cpp (original) +++ lldb/trunk/tools/debugserver/source/MacOSX/MachThreadList.cpp Wed Nov 17 23:57:03 2010 @@ -12,6 +12,9 @@ //===----------------------------------------------------------------------===// #include "MachThreadList.h" + +#include + #include "DNBLog.h" #include "DNBThreadResumeActions.h" #include "MachProcess.h" @@ -104,6 +107,15 @@ return NULL; } +MachThread * +MachThreadList::GetThreadByID (nub_thread_t tid) const +{ + uint32_t idx = GetThreadIndexByID(tid); + if (idx < m_threads.size()) + return m_threads[idx].get(); + return NULL; +} + bool MachThreadList::GetRegisterValue ( nub_thread_t tid, uint32_t reg_set_idx, uint32_t reg_idx, DNBRegisterValue *reg_value ) const { @@ -202,9 +214,28 @@ MachThreadList::UpdateThreadList(MachProcess *process, bool update) { // locker will keep a mutex locked until it goes out of scope - DNBLogThreadedIf(LOG_THREAD | LOG_VERBOSE, "MachThreadList::UpdateThreadList (pid = %4.4x, update = %u )", process->ProcessID(), update); + DNBLogThreadedIf (LOG_THREAD, "MachThreadList::UpdateThreadList (pid = %4.4x, update = %u) process stop count = %u", process->ProcessID(), update, process->StopCount()); PTHREAD_MUTEX_LOCKER (locker, m_threads_mutex); +#if defined (__i386__) || defined (__x86_64__) + if (process->StopCount() == 0) + { + int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, process->ProcessID() }; + struct kinfo_proc processInfo; + size_t bufsize = sizeof(processInfo); + bool is_64_bit = false; + if (sysctl(mib, (unsigned)(sizeof(mib)/sizeof(int)), &processInfo, &bufsize, NULL, 0) == 0 && bufsize > 0) + { + if (processInfo.kp_proc.p_flag & P_LP64) + is_64_bit = true; + } + if (is_64_bit) + DNBArchProtocol::SetDefaultArchitecture(CPU_TYPE_X86_64); + else + DNBArchProtocol::SetDefaultArchitecture(CPU_TYPE_I386); + } +#endif + if (m_threads.empty() || update) { thread_array_t thread_list = NULL; Modified: lldb/trunk/tools/debugserver/source/MacOSX/MachThreadList.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/debugserver/source/MacOSX/MachThreadList.h?rev=119680&r1=119679&r2=119680&view=diff ============================================================================== --- lldb/trunk/tools/debugserver/source/MacOSX/MachThreadList.h (original) +++ lldb/trunk/tools/debugserver/source/MacOSX/MachThreadList.h Wed Nov 17 23:57:03 2010 @@ -55,6 +55,8 @@ bool DisableHardwareWatchpoint (const DNBBreakpoint *wp) const; uint32_t GetThreadIndexForThreadStoppedWithSignal (const int signo) const; + MachThread * GetThreadByID (nub_thread_t tid) const; + protected: typedef std::vector collection; typedef collection::iterator iterator; Modified: lldb/trunk/tools/debugserver/source/MacOSX/arm/DNBArchImpl.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/debugserver/source/MacOSX/arm/DNBArchImpl.h?rev=119680&r1=119679&r2=119680&view=diff ============================================================================== --- lldb/trunk/tools/debugserver/source/MacOSX/arm/DNBArchImpl.h (original) +++ lldb/trunk/tools/debugserver/source/MacOSX/arm/DNBArchImpl.h Wed Nov 17 23:57:03 2010 @@ -235,6 +235,5 @@ }; -typedef DNBArchMachARM DNBArch; #endif // #if defined (__arm__) #endif // #ifndef __DebugNubArchMachARM_h__ Modified: lldb/trunk/tools/debugserver/source/MacOSX/i386/DNBArchImplI386.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/debugserver/source/MacOSX/i386/DNBArchImplI386.cpp?rev=119680&r1=119679&r2=119680&view=diff ============================================================================== --- lldb/trunk/tools/debugserver/source/MacOSX/i386/DNBArchImplI386.cpp (original) +++ lldb/trunk/tools/debugserver/source/MacOSX/i386/DNBArchImplI386.cpp Wed Nov 17 23:57:03 2010 @@ -11,7 +11,7 @@ // //===----------------------------------------------------------------------===// -#if defined (__i386__) +#if defined (__i386__) || defined (__x86_64__) #include @@ -20,8 +20,6 @@ #include "MachThread.h" #include "MachProcess.h" -static const uint8_t g_breakpoint_opcode[] = { 0xCC }; - enum { gpr_eax = 0, @@ -187,21 +185,6 @@ gdb_mm7 = 48 }; - -const uint8_t * const -DNBArchImplI386::SoftwareBreakpointOpcode (nub_size_t byte_size) -{ - if (byte_size == 1) - return g_breakpoint_opcode; - return NULL; -} - -uint32_t -DNBArchImplI386::GetCPUType() -{ - return CPU_TYPE_I386; -} - uint64_t DNBArchImplI386::GetPC(uint64_t failValue) { @@ -589,6 +572,21 @@ const size_t DNBArchImplI386::k_num_register_sets = sizeof(g_reg_sets)/sizeof(DNBRegisterSetInfo); +DNBArchProtocol * +DNBArchImplI386::Create (MachThread *thread) +{ + return new DNBArchImplI386 (thread); +} + +const uint8_t * const +DNBArchImplI386::SoftwareBreakpointOpcode (nub_size_t byte_size) +{ + static const uint8_t g_breakpoint_opcode[] = { 0xCC }; + if (byte_size == 1) + return g_breakpoint_opcode; + return NULL; +} + const DNBRegisterSetInfo * DNBArchImplI386::GetRegisterSetInfo(nub_size_t *num_reg_sets) { @@ -596,6 +594,22 @@ return g_reg_sets; } + +void +DNBArchImplI386::Initialize() +{ + DNBArchPluginInfo arch_plugin_info = + { + CPU_TYPE_I386, + DNBArchImplI386::Create, + DNBArchImplI386::GetRegisterSetInfo, + DNBArchImplI386::SoftwareBreakpointOpcode + }; + + // Register this arch plug-in with the main protocol class + DNBArchProtocol::RegisterArchPlugin (arch_plugin_info); +} + bool DNBArchImplI386::GetRegisterValue(int set, int reg, DNBRegisterValue *value) { Modified: lldb/trunk/tools/debugserver/source/MacOSX/i386/DNBArchImplI386.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/debugserver/source/MacOSX/i386/DNBArchImplI386.h?rev=119680&r1=119679&r2=119680&view=diff ============================================================================== --- lldb/trunk/tools/debugserver/source/MacOSX/i386/DNBArchImplI386.h (original) +++ lldb/trunk/tools/debugserver/source/MacOSX/i386/DNBArchImplI386.h Wed Nov 17 23:57:03 2010 @@ -14,7 +14,7 @@ #ifndef __DNBArchImplI386_h__ #define __DNBArchImplI386_h__ -#if defined (__i386__) +#if defined (__i386__) || defined (__x86_64__) #include "DNBArch.h" #include @@ -34,9 +34,8 @@ virtual ~DNBArchImplI386() { } - - static const DNBRegisterSetInfo * - GetRegisterSetInfo(nub_size_t *num_reg_sets); + + static void Initialize(); virtual bool GetRegisterValue(int set, int reg, DNBRegisterValue *value); virtual bool SetRegisterValue(int set, int reg, const DNBRegisterValue *value); @@ -53,9 +52,6 @@ virtual bool ThreadDidStop(); virtual bool NotifyException(MachException::Data& exc); - static const uint8_t * const SoftwareBreakpointOpcode (nub_size_t byte_size); - static uint32_t GetCPUType(); - protected: kern_return_t EnableHardwareSingleStep (bool enable); @@ -186,11 +182,18 @@ kern_return_t SetFPUState (); kern_return_t SetEXCState (); + static DNBArchProtocol * + Create (MachThread *thread); + + static const uint8_t * const + SoftwareBreakpointOpcode (nub_size_t byte_size); + + static const DNBRegisterSetInfo * + GetRegisterSetInfo(nub_size_t *num_reg_sets); + MachThread *m_thread; State m_state; }; -typedef DNBArchImplI386 DNBArch; - -#endif // #if defined (__i386__) +#endif // #if defined (__i386__) || defined (__x86_64__) #endif // #ifndef __DNBArchImplI386_h__ Modified: lldb/trunk/tools/debugserver/source/MacOSX/ppc/DNBArchImpl.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/debugserver/source/MacOSX/ppc/DNBArchImpl.h?rev=119680&r1=119679&r2=119680&view=diff ============================================================================== --- lldb/trunk/tools/debugserver/source/MacOSX/ppc/DNBArchImpl.h (original) +++ lldb/trunk/tools/debugserver/source/MacOSX/ppc/DNBArchImpl.h Wed Nov 17 23:57:03 2010 @@ -175,6 +175,5 @@ State m_state; }; -typedef DNBArchMachPPC DNBArch; #endif // #if defined (__powerpc__) || defined (__ppc__) || defined (__ppc64__) #endif // #ifndef __DebugNubArchMachPPC_h__ Modified: lldb/trunk/tools/debugserver/source/MacOSX/x86_64/DNBArchImplX86_64.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/debugserver/source/MacOSX/x86_64/DNBArchImplX86_64.cpp?rev=119680&r1=119679&r2=119680&view=diff ============================================================================== --- lldb/trunk/tools/debugserver/source/MacOSX/x86_64/DNBArchImplX86_64.cpp (original) +++ lldb/trunk/tools/debugserver/source/MacOSX/x86_64/DNBArchImplX86_64.cpp Wed Nov 17 23:57:03 2010 @@ -11,7 +11,7 @@ // //===----------------------------------------------------------------------===// -#if defined (__x86_64__) +#if defined (__i386__) || defined (__x86_64__) #include @@ -20,22 +20,6 @@ #include "MachThread.h" #include "MachProcess.h" -static const uint8_t g_breakpoint_opcode[] = { 0xCC }; - -const uint8_t * const -DNBArchImplX86_64::SoftwareBreakpointOpcode (nub_size_t byte_size) -{ - if (byte_size == 1) - return g_breakpoint_opcode; - return NULL; -} - -uint32_t -DNBArchImplX86_64::GetCPUType() -{ - return CPU_TYPE_X86_64; -} - uint64_t DNBArchImplX86_64::GetPC(uint64_t failValue) { @@ -718,13 +702,43 @@ const size_t DNBArchImplX86_64::k_num_register_sets = sizeof(g_reg_sets)/sizeof(DNBRegisterSetInfo); +DNBArchProtocol * +DNBArchImplX86_64::Create (MachThread *thread) +{ + return new DNBArchImplX86_64 (thread); +} + +const uint8_t * const +DNBArchImplX86_64::SoftwareBreakpointOpcode (nub_size_t byte_size) +{ + static const uint8_t g_breakpoint_opcode[] = { 0xCC }; + if (byte_size == 1) + return g_breakpoint_opcode; + return NULL; +} + const DNBRegisterSetInfo * -DNBArchImplX86_64::GetRegisterSetInfo (nub_size_t *num_reg_sets) +DNBArchImplX86_64::GetRegisterSetInfo(nub_size_t *num_reg_sets) { *num_reg_sets = k_num_register_sets; return g_reg_sets; } +void +DNBArchImplX86_64::Initialize() +{ + DNBArchPluginInfo arch_plugin_info = + { + CPU_TYPE_X86_64, + DNBArchImplX86_64::Create, + DNBArchImplX86_64::GetRegisterSetInfo, + DNBArchImplX86_64::SoftwareBreakpointOpcode + }; + + // Register this arch plug-in with the main protocol class + DNBArchProtocol::RegisterArchPlugin (arch_plugin_info); +} + bool DNBArchImplX86_64::GetRegisterValue(int set, int reg, DNBRegisterValue *value) { @@ -1032,4 +1046,4 @@ -#endif // #if defined (__i386__) +#endif // #if defined (__i386__) || defined (__x86_64__) Modified: lldb/trunk/tools/debugserver/source/MacOSX/x86_64/DNBArchImplX86_64.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/debugserver/source/MacOSX/x86_64/DNBArchImplX86_64.h?rev=119680&r1=119679&r2=119680&view=diff ============================================================================== --- lldb/trunk/tools/debugserver/source/MacOSX/x86_64/DNBArchImplX86_64.h (original) +++ lldb/trunk/tools/debugserver/source/MacOSX/x86_64/DNBArchImplX86_64.h Wed Nov 17 23:57:03 2010 @@ -14,8 +14,7 @@ #ifndef __DNBArchImplX86_64_h__ #define __DNBArchImplX86_64_h__ -//#if defined (__i386__) -#if defined(__x86_64__) +#if defined (__i386__) || defined (__x86_64__) #include "DNBArch.h" #include #include @@ -35,9 +34,7 @@ { } - static const DNBRegisterSetInfo * - GetRegisterSetInfo(nub_size_t *num_reg_sets); - + static void Initialize(); virtual bool GetRegisterValue(int set, int reg, DNBRegisterValue *value); virtual bool SetRegisterValue(int set, int reg, const DNBRegisterValue *value); virtual nub_size_t GetRegisterContext (void *buf, nub_size_t buf_len); @@ -54,9 +51,6 @@ virtual bool ThreadDidStop(); virtual bool NotifyException(MachException::Data& exc); - static const uint8_t * const SoftwareBreakpointOpcode (nub_size_t byte_size); - static uint32_t GetCPUType(); - protected: kern_return_t EnableHardwareSingleStep (bool enable); @@ -189,11 +183,18 @@ kern_return_t SetFPUState (); kern_return_t SetEXCState (); + static DNBArchProtocol * + Create (MachThread *thread); + + static const uint8_t * const + SoftwareBreakpointOpcode (nub_size_t byte_size); + + static const DNBRegisterSetInfo * + GetRegisterSetInfo(nub_size_t *num_reg_sets); + MachThread *m_thread; State m_state; }; -typedef DNBArchImplX86_64 DNBArch; - -#endif // #if defined (__x86_64__) +#endif // #if defined (__i386__) || defined (__x86_64__) #endif // #ifndef __DNBArchImplX86_64_h__ Modified: lldb/trunk/tools/debugserver/source/RNBRemote.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/debugserver/source/RNBRemote.cpp?rev=119680&r1=119679&r2=119680&view=diff ============================================================================== --- lldb/trunk/tools/debugserver/source/RNBRemote.cpp (original) +++ lldb/trunk/tools/debugserver/source/RNBRemote.cpp Wed Nov 17 23:57:03 2010 @@ -60,11 +60,10 @@ extern void ASLLogCallback(void *baton, uint32_t flags, const char *format, va_list args); -RNBRemote::RNBRemote (bool use_native_regs) : - m_ctx(), - m_comm(), - m_extended_mode(false), - m_noack_mode(false), +RNBRemote::RNBRemote (bool use_native_regs, const char *arch) : + m_ctx (), + m_comm (), + m_arch (), m_continue_thread(-1), m_thread(-1), m_mutex(), @@ -75,10 +74,14 @@ m_rx_pthread(0), m_breakpoints(), m_max_payload_size(DEFAULT_GDB_REMOTE_PROTOCOL_BUFSIZE - 4), + m_extended_mode(false), + m_noack_mode(false), m_use_native_regs (use_native_regs) { DNBLogThreadedIf (LOG_RNB_REMOTE, "%s", __PRETTY_FUNCTION__); CreatePacketTable (); + if (arch && arch[0]) + m_arch.assign (arch); } @@ -803,12 +806,10 @@ reg_entry->nub_info.reg_gdb = INVALID_NUB_REGNUM; } -#if defined (__arm__) //---------------------------------------------------------------------- // ARM regiseter sets as gdb knows them //---------------------------------------------------------------------- - register_map_entry_t g_gdb_register_map_arm[] = { @@ -873,32 +874,6 @@ { 58, 4, "fpscr", {0}, NULL, 0} }; -void -RNBRemote::InitializeRegisters (int use_native_registers) -{ - if (use_native_registers) - { - RNBRemote::InitializeNativeRegisters(); - } - else - { - const size_t num_regs = sizeof (g_gdb_register_map_arm) / sizeof (register_map_entry_t); - for (uint32_t i=0; i 0 && reg_sets != NULL); + if (m_use_native_regs) + { + DNBLogThreadedIf (LOG_RNB_PROC, "RNBRemote::%s() getting native registers from DNB interface (%s)", __FUNCTION__, m_arch.c_str()); + // Discover the registers by querying the DNB interface and letting it + // state the registers that it would like to export. This allows the + // registers to be discovered using multiple qRegisterInfo calls to get + // all register information after the architecture for the process is + // determined. + if (g_dynamic_register_map.empty()) + { + nub_size_t num_reg_sets = 0; + const DNBRegisterSetInfo *reg_sets = DNBGetRegisterSetInfo (&num_reg_sets); - uint32_t regnum = 0; - for (nub_size_t set = 0; set < num_reg_sets; ++set) - { - if (reg_sets[set].registers == NULL) - continue; + assert (num_reg_sets > 0 && reg_sets != NULL); - for (uint32_t reg=0; reg < reg_sets[set].num_registers; ++reg) + uint32_t regnum = 0; + for (nub_size_t set = 0; set < num_reg_sets; ++set) { - register_map_entry_t reg_entry = { - regnum++, // register number starts at zero and goes up with no gaps - reg_sets[set].registers[reg].size, // register size in bytes - reg_sets[set].registers[reg].name, // register name - reg_sets[set].registers[reg], // DNBRegisterInfo - NULL, // Value to print if case we fail to reg this register (if this is NULL, we will return an error) - reg_sets[set].registers[reg].reg_generic != INVALID_NUB_REGNUM}; + if (reg_sets[set].registers == NULL) + continue; + + for (uint32_t reg=0; reg < reg_sets[set].num_registers; ++reg) + { + register_map_entry_t reg_entry = { + regnum++, // register number starts at zero and goes up with no gaps + reg_sets[set].registers[reg].size, // register size in bytes + reg_sets[set].registers[reg].name, // register name + reg_sets[set].registers[reg], // DNBRegisterInfo + NULL, // Value to print if case we fail to reg this register (if this is NULL, we will return an error) + reg_sets[set].registers[reg].reg_generic != INVALID_NUB_REGNUM}; - g_dynamic_register_map.push_back (reg_entry); + g_dynamic_register_map.push_back (reg_entry); + } } + g_reg_entries = g_dynamic_register_map.data(); + g_num_reg_entries = g_dynamic_register_map.size(); } - g_reg_entries = g_dynamic_register_map.data(); - g_num_reg_entries = g_dynamic_register_map.size(); + return true; } -} - - -const register_map_entry_t * -register_mapping_by_regname (const char *n) -{ - for (uint32_t reg = 0; reg < g_num_reg_entries; reg++) + else { - if (strcmp (g_reg_entries[reg].gdb_name, n) == 0) - return &g_reg_entries[reg]; + DNBLogThreadedIf (LOG_RNB_PROC, "RNBRemote::%s() getting gdb registers (%s)", __FUNCTION__, m_arch.c_str()); +#if defined (__i386__) || defined (__x86_64__) + if (m_arch.compare("x86_64") == 0) + { + const size_t num_regs = sizeof (g_gdb_register_map_x86_64) / sizeof (register_map_entry_t); + for (uint32_t i=0; iInitialize(); + RNBContext& ctx = remote->Context(); @@ -911,11 +935,6 @@ DNBLogDebug("argv[%i] = %s", i, argv[i]); } - // Now that we have read in the options and enabled logging, initialize - // the rest of RNBRemote - RNBRemote::InitializeRegisters (use_native_registers); - - // as long as we're dropping remotenub in as a replacement for gdbserver, // explicitly note that this is not gdbserver. From gclayton at apple.com Thu Nov 18 11:29:15 2010 From: gclayton at apple.com (Greg Clayton) Date: Thu, 18 Nov 2010 17:29:15 -0000 Subject: [Lldb-commits] [lldb] r119709 - /lldb/trunk/tools/debugserver/source/DNBArch.cpp Message-ID: <20101118172915.2B3442A6C12C@llvm.org> Author: gclayton Date: Thu Nov 18 11:29:15 2010 New Revision: 119709 URL: http://llvm.org/viewvc/llvm-project?rev=119709&view=rev Log: Added missing file. Added: lldb/trunk/tools/debugserver/source/DNBArch.cpp Added: lldb/trunk/tools/debugserver/source/DNBArch.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/debugserver/source/DNBArch.cpp?rev=119709&view=auto ============================================================================== --- lldb/trunk/tools/debugserver/source/DNBArch.cpp (added) +++ lldb/trunk/tools/debugserver/source/DNBArch.cpp Thu Nov 18 11:29:15 2010 @@ -0,0 +1,89 @@ +//===-- DNBArch.cpp ---------------------------------------------*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +// +// Created by Greg Clayton on 6/24/07. +// +//===----------------------------------------------------------------------===// + +#include "DNBArch.h" +#include +#include + +#include + +#include "DNBLog.h" + +typedef std::map CPUPluginInfoMap; + +#if defined (__i386__) +uint32_t g_current_cpu_type = CPU_TYPE_I386; +#elif defined (__x86_64__) +uint32_t g_current_cpu_type = CPU_TYPE_X86_64; +#elif defined (__arm__) +uint32_t g_current_cpu_type = CPU_TYPE_ARM; +#else +uint32_t g_current_cpu_type = 0; +#endif + +CPUPluginInfoMap g_arch_plugins; + + +static const DNBArchPluginInfo * +GetArchInfo () +{ + CPUPluginInfoMap::const_iterator pos = g_arch_plugins.find(g_current_cpu_type); + if (pos != g_arch_plugins.end()) + return &pos->second; + return NULL; +} + +void +DNBArchProtocol::SetDefaultArchitecture (uint32_t cpu_type) +{ + DNBLogThreadedIf (LOG_PROCESS, "DNBArchProtocol::SetDefaultArchitecture (cpu_type=0x%8.8x)", cpu_type); + g_current_cpu_type = cpu_type; + assert (g_arch_plugins.find(g_current_cpu_type) != g_arch_plugins.end()); +} + +void +DNBArchProtocol::RegisterArchPlugin (const DNBArchPluginInfo &arch_info) +{ + if (arch_info.cpu_type) + g_arch_plugins[arch_info.cpu_type] = arch_info; +} + +const DNBRegisterSetInfo * +DNBArchProtocol::GetRegisterSetInfo (nub_size_t *num_reg_sets) +{ + const DNBArchPluginInfo *arch_info = GetArchInfo (); + if (arch_info) + return arch_info->GetRegisterSetInfo (num_reg_sets); + *num_reg_sets = 0; + return NULL; +} + +DNBArchProtocol * +DNBArchProtocol::Create (MachThread *thread) +{ + const DNBArchPluginInfo *arch_info = GetArchInfo (); + if (arch_info) + return arch_info->Create (thread); + return NULL; + +} + +const uint8_t * const +DNBArchProtocol::GetBreakpointOpcode (nub_size_t byte_size) +{ + const DNBArchPluginInfo *arch_info = GetArchInfo (); + if (arch_info) + return arch_info->GetBreakpointOpcode (byte_size); + return NULL; +} + From gclayton at apple.com Thu Nov 18 12:52:37 2010 From: gclayton at apple.com (Greg Clayton) Date: Thu, 18 Nov 2010 18:52:37 -0000 Subject: [Lldb-commits] [lldb] r119720 - in /lldb/trunk: include/lldb/API/SBThread.h include/lldb/Breakpoint/BreakpointLocation.h lldb.xcodeproj/project.pbxproj source/API/SBBreakpointLocation.cpp source/API/SBThread.cpp source/Breakpoint/BreakpointLocationCollection.cpp source/Breakpoint/BreakpointSite.cpp source/Target/StopInfo.cpp tools/debugserver/debugserver.xcodeproj/project.pbxproj Message-ID: <20101118185237.335CF2A6C12C@llvm.org> Author: gclayton Date: Thu Nov 18 12:52:36 2010 New Revision: 119720 URL: http://llvm.org/viewvc/llvm-project?rev=119720&view=rev Log: Added the ability to get more information on the SBThread's stop reason by being able to get the data count and data. Each thread stop reason has one or more data words that can help describe the stop. To do this I added: size_t SBThread::GetStopReasonDataCount(); uint64_t SBThread::GetStopReasonDataAtIndex(uint32_t idx); Modified: lldb/trunk/include/lldb/API/SBThread.h lldb/trunk/include/lldb/Breakpoint/BreakpointLocation.h lldb/trunk/lldb.xcodeproj/project.pbxproj lldb/trunk/source/API/SBBreakpointLocation.cpp lldb/trunk/source/API/SBThread.cpp lldb/trunk/source/Breakpoint/BreakpointLocationCollection.cpp lldb/trunk/source/Breakpoint/BreakpointSite.cpp lldb/trunk/source/Target/StopInfo.cpp lldb/trunk/tools/debugserver/debugserver.xcodeproj/project.pbxproj Modified: lldb/trunk/include/lldb/API/SBThread.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/API/SBThread.h?rev=119720&r1=119719&r2=119720&view=diff ============================================================================== --- lldb/trunk/include/lldb/API/SBThread.h (original) +++ lldb/trunk/include/lldb/API/SBThread.h Thu Nov 18 12:52:36 2010 @@ -35,30 +35,30 @@ lldb::StopReason GetStopReason(); -// -// // Get the number of words associated with the stop reason. -// size_t -// GetStopReasonDataCount(); -// -// //-------------------------------------------------------------------------- -// // Get information associated with a stop reason. -// // -// // Breakpoint and watchpoint stop reasons will have data that consists of -// // pairs of breakpoint/watchpoint IDs followed by the breakpoint/watchpoint -// // location IDs (they always come in pairs). -// // -// // Stop Reason Count Data Type -// // ======================== ===== ========================================== -// // eStopReasonNone 0 -// // eStopReasonTrace 0 -// // eStopReasonBreakpoint N duple: {breakpoint id, location id} -// // eStopReasonWatchpoint N duple: {watchpoint id, location id} -// // eStopReasonSignal 1 unix signal number -// // eStopReasonException N exception data -// // eStopReasonPlanComplete 0 -// //-------------------------------------------------------------------------- -// uint64_t -// GetStopReasonDataAtIndex(uint32_t idx); + + // Get the number of words associated with the stop reason. + size_t + GetStopReasonDataCount(); + + //-------------------------------------------------------------------------- + // Get information associated with a stop reason. + // + // Breakpoint stop reasons will have data that consists of pairs of + // breakpoint IDs followed by the breakpoint location IDs (they always come + // in pairs). + // + // Stop Reason Count Data Type + // ======================== ===== ========================================== + // eStopReasonNone 0 + // eStopReasonTrace 0 + // eStopReasonBreakpoint N duple: {breakpoint id, location id} + // eStopReasonWatchpoint N duple: {watchpoint id, location id} + // eStopReasonSignal 1 unix signal number + // eStopReasonException N exception data + // eStopReasonPlanComplete 0 + //-------------------------------------------------------------------------- + uint64_t + GetStopReasonDataAtIndex(uint32_t idx); size_t GetStopDescription (char *dst, size_t dst_len); Modified: lldb/trunk/include/lldb/Breakpoint/BreakpointLocation.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/Breakpoint/BreakpointLocation.h?rev=119720&r1=119719&r2=119720&view=diff ============================================================================== --- lldb/trunk/include/lldb/Breakpoint/BreakpointLocation.h (original) +++ lldb/trunk/include/lldb/Breakpoint/BreakpointLocation.h Thu Nov 18 12:52:36 2010 @@ -20,11 +20,9 @@ // Project includes #include "lldb/lldb-private.h" -#include "lldb/Core/UserID.h" #include "lldb/Breakpoint/StoppointLocation.h" +#include "lldb/Core/UserID.h" #include "lldb/Core/Address.h" -#include "lldb/Breakpoint/Breakpoint.h" -#include "lldb/Breakpoint/BreakpointOptions.h" #include "lldb/Target/Process.h" #include "lldb/Core/StringList.h" @@ -165,7 +163,8 @@ /// @param[in] condition /// The condition expression to evaluate when the breakpoint is hit. //------------------------------------------------------------------ - void SetCondition (const char *condition); + void + SetCondition (const char *condition); //------------------------------------------------------------------ /// Test the breakpoint location's condition in the Execution context passed in. @@ -179,7 +178,9 @@ /// @return /// A thread plan to run to test the condition, or NULL if there is no condition. //------------------------------------------------------------------ - ThreadPlan *GetThreadPlanToTestCondition (ExecutionContext &exe_ctx, Stream &error); + ThreadPlan * + GetThreadPlanToTestCondition (ExecutionContext &exe_ctx, + Stream &error); //------------------------------------------------------------------ /// Return a pointer to the text of the condition expression. @@ -188,7 +189,8 @@ /// A pointer to the condition expression text, or NULL if no // condition has been set. //------------------------------------------------------------------ - const char *GetConditionText (); + const char * + GetConditionText (); //------------------------------------------------------------------ Modified: lldb/trunk/lldb.xcodeproj/project.pbxproj URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/lldb.xcodeproj/project.pbxproj?rev=119720&r1=119719&r2=119720&view=diff ============================================================================== --- lldb/trunk/lldb.xcodeproj/project.pbxproj (original) +++ lldb/trunk/lldb.xcodeproj/project.pbxproj Thu Nov 18 12:52:36 2010 @@ -2452,7 +2452,6 @@ isa = PBXProject; buildConfigurationList = 1DEB91EF08733DB70010E9CD /* Build configuration list for PBXProject "lldb" */; compatibilityVersion = "Xcode 3.1"; - developmentRegion = English; hasScannedForEncodings = 1; knownRegions = ( en, Modified: lldb/trunk/source/API/SBBreakpointLocation.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/API/SBBreakpointLocation.cpp?rev=119720&r1=119719&r2=119720&view=diff ============================================================================== --- lldb/trunk/source/API/SBBreakpointLocation.cpp (original) +++ lldb/trunk/source/API/SBBreakpointLocation.cpp Thu Nov 18 12:52:36 2010 @@ -14,6 +14,7 @@ #include "lldb/lldb-types.h" #include "lldb/lldb-defines.h" +#include "lldb/Breakpoint/Breakpoint.h" #include "lldb/Breakpoint/BreakpointLocation.h" #include "lldb/Target/ThreadSpec.h" #include "lldb/Core/Log.h" Modified: lldb/trunk/source/API/SBThread.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/API/SBThread.cpp?rev=119720&r1=119719&r2=119720&view=diff ============================================================================== --- lldb/trunk/source/API/SBThread.cpp (original) +++ lldb/trunk/source/API/SBThread.cpp Thu Nov 18 12:52:36 2010 @@ -12,6 +12,7 @@ #include "lldb/API/SBSymbolContext.h" #include "lldb/API/SBFileSpec.h" #include "lldb/API/SBStream.h" +#include "lldb/Breakpoint/BreakpointLocation.h" #include "lldb/Core/Debugger.h" #include "lldb/Core/Stream.h" #include "lldb/Core/StreamFile.h" @@ -109,6 +110,109 @@ } size_t +SBThread::GetStopReasonDataCount () +{ + if (m_opaque_sp) + { + StopInfoSP stop_info_sp = m_opaque_sp->GetStopInfo (); + if (stop_info_sp) + { + StopReason reason = stop_info_sp->GetStopReason(); + switch (reason) + { + case eStopReasonInvalid: + case eStopReasonNone: + case eStopReasonTrace: + case eStopReasonPlanComplete: + // There is no data for these stop reasons. + return 0; + + case eStopReasonBreakpoint: + { + break_id_t site_id = stop_info_sp->GetValue(); + lldb::BreakpointSiteSP bp_site_sp (m_opaque_sp->GetProcess().GetBreakpointSiteList().FindByID (site_id)); + if (bp_site_sp) + return bp_site_sp->GetNumberOfOwners () * 2; + else + return 0; // Breakpoint must have cleared itself... + } + break; + + case eStopReasonWatchpoint: + assert (!"implement watchpoint support in SBThread::GetStopReasonDataCount ()"); + return 0; // We don't have watchpoint support yet... + + case eStopReasonSignal: + return 1; + + case eStopReasonException: + return 1; + } + } + } + return 0; +} + +uint64_t +SBThread::GetStopReasonDataAtIndex (uint32_t idx) +{ + if (m_opaque_sp) + { + StopInfoSP stop_info_sp = m_opaque_sp->GetStopInfo (); + if (stop_info_sp) + { + StopReason reason = stop_info_sp->GetStopReason(); + switch (reason) + { + case eStopReasonInvalid: + case eStopReasonNone: + case eStopReasonTrace: + case eStopReasonPlanComplete: + // There is no data for these stop reasons. + return 0; + + case eStopReasonBreakpoint: + { + break_id_t site_id = stop_info_sp->GetValue(); + lldb::BreakpointSiteSP bp_site_sp (m_opaque_sp->GetProcess().GetBreakpointSiteList().FindByID (site_id)); + if (bp_site_sp) + { + uint32_t bp_index = idx / 2; + BreakpointLocationSP bp_loc_sp (bp_site_sp->GetOwnerAtIndex (bp_index)); + if (bp_loc_sp) + { + if (bp_index & 1) + { + // Odd idx, return the breakpoint location ID + return bp_loc_sp->GetID(); + } + else + { + // Even idx, return the breakpoint ID + return bp_loc_sp->GetBreakpoint().GetID(); + } + } + } + return LLDB_INVALID_BREAK_ID; + } + break; + + case eStopReasonWatchpoint: + assert (!"implement watchpoint support in SBThread::GetStopReasonDataCount ()"); + return 0; // We don't have watchpoint support yet... + + case eStopReasonSignal: + return stop_info_sp->GetValue(); + + case eStopReasonException: + return stop_info_sp->GetValue(); + } + } + } + return 0; +} + +size_t SBThread::GetStopDescription (char *dst, size_t dst_len) { LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); Modified: lldb/trunk/source/Breakpoint/BreakpointLocationCollection.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Breakpoint/BreakpointLocationCollection.cpp?rev=119720&r1=119719&r2=119720&view=diff ============================================================================== --- lldb/trunk/source/Breakpoint/BreakpointLocationCollection.cpp (original) +++ lldb/trunk/source/Breakpoint/BreakpointLocationCollection.cpp Thu Nov 18 12:52:36 2010 @@ -14,6 +14,7 @@ // Project includes #include "lldb/Breakpoint/BreakpointLocationCollection.h" #include "lldb/Core/ModuleList.h" +#include "lldb/Breakpoint/Breakpoint.h" #include "lldb/Breakpoint/BreakpointLocation.h" #include "lldb/Breakpoint/BreakpointLocationList.h" #include "lldb/Target/Thread.h" Modified: lldb/trunk/source/Breakpoint/BreakpointSite.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Breakpoint/BreakpointSite.cpp?rev=119720&r1=119719&r2=119720&view=diff ============================================================================== --- lldb/trunk/source/Breakpoint/BreakpointSite.cpp (original) +++ lldb/trunk/source/Breakpoint/BreakpointSite.cpp Thu Nov 18 12:52:36 2010 @@ -13,6 +13,7 @@ // C++ Includes // Other libraries and framework includes // Project includes +#include "lldb/Breakpoint/Breakpoint.h" #include "lldb/Breakpoint/BreakpointLocation.h" #include "lldb/Breakpoint/BreakpointSiteList.h" Modified: lldb/trunk/source/Target/StopInfo.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Target/StopInfo.cpp?rev=119720&r1=119719&r2=119720&view=diff ============================================================================== --- lldb/trunk/source/Target/StopInfo.cpp (original) +++ lldb/trunk/source/Target/StopInfo.cpp Thu Nov 18 12:52:36 2010 @@ -16,6 +16,7 @@ // Other libraries and framework includes // Project includes #include "lldb/Core/Log.h" +#include "lldb/Breakpoint/Breakpoint.h" #include "lldb/Breakpoint/BreakpointLocation.h" #include "lldb/Breakpoint/StoppointCallbackContext.h" #include "lldb/Core/StreamString.h" Modified: lldb/trunk/tools/debugserver/debugserver.xcodeproj/project.pbxproj URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/debugserver/debugserver.xcodeproj/project.pbxproj?rev=119720&r1=119719&r2=119720&view=diff ============================================================================== --- lldb/trunk/tools/debugserver/debugserver.xcodeproj/project.pbxproj (original) +++ lldb/trunk/tools/debugserver/debugserver.xcodeproj/project.pbxproj Thu Nov 18 12:52:36 2010 @@ -372,7 +372,6 @@ isa = PBXProject; buildConfigurationList = 1DEB914E08733D8E0010E9CD /* Build configuration list for PBXProject "debugserver" */; compatibilityVersion = "Xcode 3.1"; - developmentRegion = English; hasScannedForEncodings = 1; knownRegions = ( English, From johnny.chen at apple.com Thu Nov 18 14:20:18 2010 From: johnny.chen at apple.com (Johnny Chen) Date: Thu, 18 Nov 2010 20:20:18 -0000 Subject: [Lldb-commits] [lldb] r119732 - /lldb/trunk/test/namespace/TestNamespace.py Message-ID: <20101118202018.606AD2A6C12C@llvm.org> Author: johnny Date: Thu Nov 18 14:20:18 2010 New Revision: 119732 URL: http://llvm.org/viewvc/llvm-project?rev=119732&view=rev Log: Remove whitespace chars. Modified: lldb/trunk/test/namespace/TestNamespace.py Modified: lldb/trunk/test/namespace/TestNamespace.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/namespace/TestNamespace.py?rev=119732&r1=119731&r2=119732&view=diff ============================================================================== --- lldb/trunk/test/namespace/TestNamespace.py (original) +++ lldb/trunk/test/namespace/TestNamespace.py Thu Nov 18 14:20:18 2010 @@ -61,8 +61,8 @@ '(my_uint_t) anon_uint = 0', '(A::uint_t) a_uint = 1', '(A::B::uint_t) b_uint = 2', - '(Y::uint_t) y_uint = 3'] - + '(Y::uint_t) y_uint = 3'] + # 'frame variable' displays the local variables with type information. self.expect('frame variable', VARIABLES_DISPLAYED_CORRECTLY, substrs = slist) From johnny.chen at apple.com Thu Nov 18 14:35:54 2010 From: johnny.chen at apple.com (Johnny Chen) Date: Thu, 18 Nov 2010 20:35:54 -0000 Subject: [Lldb-commits] [lldb] r119734 - in /lldb/trunk/test/class_static: TestStaticVariables.py main.cpp Message-ID: <20101118203554.D66A72A6C12C@llvm.org> Author: johnny Date: Thu Nov 18 14:35:54 2010 New Revision: 119734 URL: http://llvm.org/viewvc/llvm-project?rev=119734&view=rev Log: Add a test for displaying file and class static variables. Added: lldb/trunk/test/class_static/TestStaticVariables.py Modified: lldb/trunk/test/class_static/main.cpp Added: lldb/trunk/test/class_static/TestStaticVariables.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/class_static/TestStaticVariables.py?rev=119734&view=auto ============================================================================== --- lldb/trunk/test/class_static/TestStaticVariables.py (added) +++ lldb/trunk/test/class_static/TestStaticVariables.py Thu Nov 18 14:35:54 2010 @@ -0,0 +1,64 @@ +""" +Test display and Python APIs on file and class static variables. +""" + +import os, time +import unittest2 +import lldb +from lldbtest import * + +class StaticVariableTestCase(TestBase): + + mydir = "class_static" + + @unittest2.skipUnless(sys.platform.startswith("darwin"), "requires Darwin") + def test_with_dsym_and_run_command(self): + """Test that file and class static variables display correctly.""" + self.buildDsym() + self.static_variable_commands() + + def test_with_dwarf_and_run_command(self): + """Test that anonymous and named namespace variables display correctly.""" + self.buildDwarf() + self.static_variable_commands() + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break at. + self.line = line_number('main.cpp', '// Set break point at this line.') + + def static_variable_commands(self): + """Test that anonymous and named namespace variables display correctly.""" + self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) + + self.expect("breakpoint set -f main.cpp -l %d" % self.line, + BREAKPOINT_CREATED, + startstr = "Breakpoint created: 1: file ='main.cpp', line = %d, locations = 1" % + self.line) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs = ['state is stopped', + 'stop reason = breakpoint']) + + # On Mac OS X, gcc 4.2 emits the wrong debug info for A::g_points. + slist = ['(PointType [2]) g_points', 'A::g_points'] + + # 'frame variable -G' finds and displays global variable(s) by name. + self.expect('frame variable -G g_points', VARIABLES_DISPLAYED_CORRECTLY, + substrs = slist) + + # A::g_points is an array of two elements. + if sys.platform.startswith("darwin") and self.getCompiler() in ['clang', 'llvm-gcc']: + self.expect("frame variable A::g_points[1].x", VARIABLES_DISPLAYED_CORRECTLY, + startstr = "(int) A::g_points[1].x = 11") + + +if __name__ == '__main__': + import atexit + lldb.SBDebugger.Initialize() + atexit.register(lambda: lldb.SBDebugger.Terminate()) + unittest2.main() Modified: lldb/trunk/test/class_static/main.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/class_static/main.cpp?rev=119734&r1=119733&r2=119734&view=diff ============================================================================== --- lldb/trunk/test/class_static/main.cpp (original) +++ lldb/trunk/test/class_static/main.cpp Thu Nov 18 14:35:54 2010 @@ -45,7 +45,7 @@ int main (int argc, char const *argv[]) { - printf ("A::g_points[1].x = %i\n", A::g_points[1].x); + printf ("A::g_points[1].x = %i\n", A::g_points[1].x); // Set break point at this line. printf ("::g_points[1].x = %i\n", g_points[1].x); return 0; } From scallanan at apple.com Thu Nov 18 16:21:59 2010 From: scallanan at apple.com (Sean Callanan) Date: Thu, 18 Nov 2010 22:21:59 -0000 Subject: [Lldb-commits] [lldb] r119750 - /lldb/trunk/source/Expression/IRForTarget.cpp Message-ID: <20101118222159.1CA312A6C12C@llvm.org> Author: spyffe Date: Thu Nov 18 16:21:58 2010 New Revision: 119750 URL: http://llvm.org/viewvc/llvm-project?rev=119750&view=rev Log: Fixed the logic in IRForTarget that recognizes externally-defined variables to match up with the code in ClangASTSource that produces them. Modified: lldb/trunk/source/Expression/IRForTarget.cpp Modified: lldb/trunk/source/Expression/IRForTarget.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Expression/IRForTarget.cpp?rev=119750&r1=119749&r2=119750&view=diff ============================================================================== --- lldb/trunk/source/Expression/IRForTarget.cpp (original) +++ lldb/trunk/source/Expression/IRForTarget.cpp Thu Nov 18 16:21:58 2010 @@ -362,9 +362,7 @@ CFSCWB_arguments.end(), "CFStringCreateWithBytes", FirstEntryInstruction); - - Constant *initializer = NSStr->getInitializer(); - + if (!UnfoldConstant(NSStr, CFSCWB_call, FirstEntryInstruction)) { if (log) @@ -1089,11 +1087,13 @@ IRForTarget::resolveExternals(Module &M, Function &F) { + lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); + for (Module::global_iterator global = M.global_begin(), end = M.global_end(); global != end; ++global) { - if ((*global).hasExternalLinkage() && + if (DeclForGlobalValue(M, global) && !MaybeHandleVariable (M, global)) return false; } From gclayton at apple.com Thu Nov 18 17:32:36 2010 From: gclayton at apple.com (Greg Clayton) Date: Thu, 18 Nov 2010 23:32:36 -0000 Subject: [Lldb-commits] [lldb] r119757 - in /lldb/trunk: include/lldb/Core/Debugger.h include/lldb/Core/Log.h include/lldb/Target/Process.h include/lldb/Target/Target.h include/lldb/Target/Thread.h lldb.xcodeproj/project.pbxproj source/Core/Debugger.cpp source/Core/Log.cpp source/Plugins/Process/MacOSX-User/source/ProcessMacOSXLog.cpp source/Plugins/Process/gdb-remote/ProcessGDBRemoteLog.cpp source/Target/Process.cpp source/Target/Target.cpp source/Target/Thread.cpp source/lldb-log.cpp source/lldb.cpp Message-ID: <20101118233236.2EC982A6C12C@llvm.org> Author: gclayton Date: Thu Nov 18 17:32:35 2010 New Revision: 119757 URL: http://llvm.org/viewvc/llvm-project?rev=119757&view=rev Log: Cleaned up code that wasn't using the Initialize and Terminate paradigm by changing it to use it. There was an extra parameter added to the static accessor global user settings controllers that wasn't needed. A bool was being used as a parameter to the accessor just so it could be used to clean up the global user settings controller which is now fixed by splitting up the initialization into the "static void Class::Initialize()", access into the "static UserSettingsControllerSP & Class::GetSettingsController()", and cleanup into "static void Class::Terminate()". Also added initialize and terminate calls to the logging code to avoid issues when LLDB is shutting down. There were cases after the logging was switched over to use shared pointers where we could crash if the global destructor chain was being run and it causes the log to be destroyed and any any logging occurred. Modified: lldb/trunk/include/lldb/Core/Debugger.h lldb/trunk/include/lldb/Core/Log.h lldb/trunk/include/lldb/Target/Process.h lldb/trunk/include/lldb/Target/Target.h lldb/trunk/include/lldb/Target/Thread.h lldb/trunk/lldb.xcodeproj/project.pbxproj lldb/trunk/source/Core/Debugger.cpp lldb/trunk/source/Core/Log.cpp lldb/trunk/source/Plugins/Process/MacOSX-User/source/ProcessMacOSXLog.cpp lldb/trunk/source/Plugins/Process/gdb-remote/ProcessGDBRemoteLog.cpp lldb/trunk/source/Target/Process.cpp lldb/trunk/source/Target/Target.cpp lldb/trunk/source/Target/Thread.cpp lldb/trunk/source/lldb-log.cpp lldb/trunk/source/lldb.cpp Modified: lldb/trunk/include/lldb/Core/Debugger.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/Core/Debugger.h?rev=119757&r1=119756&r2=119757&view=diff ============================================================================== --- lldb/trunk/include/lldb/Core/Debugger.h (original) +++ lldb/trunk/include/lldb/Core/Debugger.h Thu Nov 18 17:32:35 2010 @@ -247,7 +247,7 @@ }; static lldb::UserSettingsControllerSP & - GetSettingsController (bool finish = false); + GetSettingsController (); static lldb::DebuggerSP CreateInstance (); Modified: lldb/trunk/include/lldb/Core/Log.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/Core/Log.h?rev=119757&r1=119756&r2=119757&view=diff ============================================================================== --- lldb/trunk/include/lldb/Core/Log.h (original) +++ lldb/trunk/include/lldb/Core/Log.h Thu Nov 18 17:32:35 2010 @@ -100,6 +100,12 @@ static void ListAllLogChannels (Stream *strm); + static void + Initialize (); + + static void + Terminate (); + //------------------------------------------------------------------ // Member functions //------------------------------------------------------------------ Modified: lldb/trunk/include/lldb/Target/Process.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/Target/Process.h?rev=119757&r1=119756&r2=119757&view=diff ============================================================================== --- lldb/trunk/include/lldb/Target/Process.h (original) +++ lldb/trunk/include/lldb/Target/Process.h Thu Nov 18 17:32:35 2010 @@ -393,8 +393,14 @@ #endif - static lldb::UserSettingsControllerSP - GetSettingsController (bool finish = false); + static void + Initialize (); + + static void + Terminate (); + + static lldb::UserSettingsControllerSP & + GetSettingsController (); void UpdateInstanceName (); Modified: lldb/trunk/include/lldb/Target/Target.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/Target/Target.h?rev=119757&r1=119756&r2=119757&view=diff ============================================================================== --- lldb/trunk/include/lldb/Target/Target.h (original) +++ lldb/trunk/include/lldb/Target/Target.h Thu Nov 18 17:32:35 2010 @@ -123,8 +123,14 @@ DISALLOW_COPY_AND_ASSIGN (SettingsController); }; - static lldb::UserSettingsControllerSP - GetSettingsController (bool finish = false); + static void + Initialize (); + + static void + Terminate (); + + static lldb::UserSettingsControllerSP & + GetSettingsController (); static ArchSpec GetDefaultArchitecture (); Modified: lldb/trunk/include/lldb/Target/Thread.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/Target/Thread.h?rev=119757&r1=119756&r2=119757&view=diff ============================================================================== --- lldb/trunk/include/lldb/Target/Thread.h (original) +++ lldb/trunk/include/lldb/Target/Thread.h Thu Nov 18 17:32:35 2010 @@ -92,14 +92,14 @@ { public: - class ThreadSettingsController : public UserSettingsController + class SettingsController : public UserSettingsController { public: - ThreadSettingsController (); + SettingsController (); virtual - ~ThreadSettingsController (); + ~SettingsController (); static SettingEntry global_settings_table[]; static SettingEntry instance_settings_table[]; @@ -113,7 +113,7 @@ // Class-wide settings. - DISALLOW_COPY_AND_ASSIGN (ThreadSettingsController); + DISALLOW_COPY_AND_ASSIGN (SettingsController); }; class RegisterCheckpoint @@ -168,8 +168,14 @@ void UpdateInstanceName (); - static lldb::UserSettingsControllerSP - GetSettingsController (bool finish = false); + static void + Initialize (); + + static void + Terminate (); + + static lldb::UserSettingsControllerSP & + GetSettingsController (); Thread (Process &process, lldb::tid_t tid); virtual ~Thread(); Modified: lldb/trunk/lldb.xcodeproj/project.pbxproj URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/lldb.xcodeproj/project.pbxproj?rev=119757&r1=119756&r2=119757&view=diff ============================================================================== --- lldb/trunk/lldb.xcodeproj/project.pbxproj (original) +++ lldb/trunk/lldb.xcodeproj/project.pbxproj Thu Nov 18 17:32:35 2010 @@ -2452,6 +2452,7 @@ isa = PBXProject; buildConfigurationList = 1DEB91EF08733DB70010E9CD /* Build configuration list for PBXProject "lldb" */; compatibilityVersion = "Xcode 3.1"; + developmentRegion = English; hasScannedForEncodings = 1; knownRegions = ( en, Modified: lldb/trunk/source/Core/Debugger.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Core/Debugger.cpp?rev=119757&r1=119756&r2=119757&view=diff ============================================================================== --- lldb/trunk/source/Core/Debugger.cpp (original) +++ lldb/trunk/source/Core/Debugger.cpp Thu Nov 18 17:32:35 2010 @@ -52,12 +52,27 @@ #pragma mark Debugger +UserSettingsControllerSP & +Debugger::GetSettingsController () +{ + static UserSettingsControllerSP g_settings_controller; + return g_settings_controller; +} + void Debugger::Initialize () { if (g_shared_debugger_refcount == 0) + { lldb_private::Initialize(); + UserSettingsControllerSP &usc = GetSettingsController(); + usc.reset (new SettingsController); + UserSettingsController::InitializeSettingsController (usc, + SettingsController::global_settings_table, + SettingsController::instance_settings_table); + } g_shared_debugger_refcount++; + } void @@ -68,10 +83,16 @@ g_shared_debugger_refcount--; if (g_shared_debugger_refcount == 0) { + UserSettingsControllerSP &usc = GetSettingsController(); + UserSettingsController::FinalizeSettingsController (usc); + usc.reset(); lldb_private::WillTerminate(); lldb_private::Terminate(); } } + // Clear our master list of debugger objects + Mutex::Locker locker (GetDebuggerListMutex ()); + GetDebuggerList().clear(); } DebuggerSP @@ -144,7 +165,7 @@ Debugger::Debugger () : UserID (g_unique_id++), - DebuggerInstanceSettings (*(Debugger::GetSettingsController().get())), + DebuggerInstanceSettings (*Debugger::GetSettingsController()), m_input_comm("debugger.input"), m_input_file (), m_output_file (), @@ -536,29 +557,6 @@ return debugger_sp; } -lldb::UserSettingsControllerSP & -Debugger::GetSettingsController (bool finish) -{ - static lldb::UserSettingsControllerSP g_settings_controller (new SettingsController); - static bool initialized = false; - - if (!initialized) - { - initialized = UserSettingsController::InitializeSettingsController (g_settings_controller, - Debugger::SettingsController::global_settings_table, - Debugger::SettingsController::instance_settings_table); - } - - if (finish) - { - UserSettingsControllerSP parent = g_settings_controller->GetParent(); - if (parent) - parent->RemoveChild (g_settings_controller); - g_settings_controller.reset(); - } - return g_settings_controller; -} - static void TestPromptFormats (StackFrame *frame) { @@ -1261,7 +1259,7 @@ lldb::InstanceSettingsSP Debugger::SettingsController::CreateInstanceSettings (const char *instance_name) { - DebuggerInstanceSettings *new_settings = new DebuggerInstanceSettings (*(Debugger::GetSettingsController().get()), + DebuggerInstanceSettings *new_settings = new DebuggerInstanceSettings (*Debugger::GetSettingsController(), false, instance_name); lldb::InstanceSettingsSP new_settings_sp (new_settings); return new_settings_sp; @@ -1306,7 +1304,7 @@ } DebuggerInstanceSettings::DebuggerInstanceSettings (const DebuggerInstanceSettings &rhs) : - InstanceSettings (*(Debugger::GetSettingsController().get()), CreateInstanceName ().AsCString()), + InstanceSettings (*Debugger::GetSettingsController(), CreateInstanceName ().AsCString()), m_prompt (rhs.m_prompt), m_frame_format (rhs.m_frame_format), m_thread_format (rhs.m_thread_format), Modified: lldb/trunk/source/Core/Log.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Core/Log.cpp?rev=119757&r1=119756&r2=119757&view=diff ============================================================================== --- lldb/trunk/source/Core/Log.cpp (original) +++ lldb/trunk/source/Core/Log.cpp Thu Nov 18 17:32:35 2010 @@ -389,7 +389,7 @@ { CallbackMap &callback_map = GetCallbackMap (); CallbackMapIter pos, end = callback_map.end(); - Args args ("all"); + Args args; for (pos = callback_map.begin(); pos != end; ++pos) pos->second.disable (args, feedback_strm); @@ -401,6 +401,19 @@ } void +Log::Initialize() +{ + Log::Callbacks log_callbacks = { DisableLog, EnableLog, ListLogCategories }; + Log::RegisterLogChannel ("lldb", log_callbacks); +} + +void +Log::Terminate () +{ + DisableAllLogChannels (NULL); +} + +void Log::ListAllLogChannels (Stream *strm) { CallbackMap &callback_map = GetCallbackMap (); Modified: lldb/trunk/source/Plugins/Process/MacOSX-User/source/ProcessMacOSXLog.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Plugins/Process/MacOSX-User/source/ProcessMacOSXLog.cpp?rev=119757&r1=119756&r2=119757&view=diff ============================================================================== --- lldb/trunk/source/Plugins/Process/MacOSX-User/source/ProcessMacOSXLog.cpp (original) +++ lldb/trunk/source/Plugins/Process/MacOSX-User/source/ProcessMacOSXLog.cpp Thu Nov 18 17:32:35 2010 @@ -48,29 +48,33 @@ LogSP log (GetLog ()); if (log) { - uint32_t flag_bits = log->GetMask().Get(); + uint32_t flag_bits = 0; const size_t argc = args.GetArgumentCount (); - for (size_t i = 0; i < argc; ++i) + if (argc > 0) { - const char *arg = args.GetArgumentAtIndex (i); - - if (::strcasecmp (arg, "all") == 0 ) flag_bits &= ~PD_LOG_ALL; - else if (::strcasestr (arg, "break") == arg ) flag_bits &= ~PD_LOG_BREAKPOINTS; - else if (::strcasecmp (arg, "default") == 0 ) flag_bits &= ~PD_LOG_DEFAULT; - else if (::strcasestr (arg, "exc") == arg ) flag_bits &= ~PD_LOG_EXCEPTIONS; - else if (::strcasecmp (arg, "memory") == 0 ) flag_bits &= ~PD_LOG_MEMORY; - else if (::strcasecmp (arg, "data-short") == 0 ) flag_bits &= ~PD_LOG_MEMORY_DATA_SHORT; - else if (::strcasecmp (arg, "data-long") == 0 ) flag_bits &= ~PD_LOG_MEMORY_DATA_LONG; - else if (::strcasecmp (arg, "protections")== 0 ) flag_bits &= ~PD_LOG_PROCESS; - else if (::strcasecmp (arg, "step") == 0 ) flag_bits &= ~PD_LOG_STEP; - else if (::strcasecmp (arg, "task") == 0 ) flag_bits &= ~PD_LOG_TASK; - else if (::strcasecmp (arg, "thread") == 0 ) flag_bits &= ~PD_LOG_THREAD; - else if (::strcasecmp (arg, "verbose") == 0 ) flag_bits &= ~PD_LOG_VERBOSE; - else if (::strcasestr (arg, "watch") == arg ) flag_bits &= ~PD_LOG_WATCHPOINTS; - else + flag_bits = log->GetMask().Get(); + for (size_t i = 0; i < argc; ++i) { - feedback_strm->Printf("error: unrecognized log category '%s'\n", arg); - ListLogCategories (feedback_strm); + const char *arg = args.GetArgumentAtIndex (i); + + if (::strcasecmp (arg, "all") == 0 ) flag_bits &= ~PD_LOG_ALL; + else if (::strcasestr (arg, "break") == arg ) flag_bits &= ~PD_LOG_BREAKPOINTS; + else if (::strcasecmp (arg, "default") == 0 ) flag_bits &= ~PD_LOG_DEFAULT; + else if (::strcasestr (arg, "exc") == arg ) flag_bits &= ~PD_LOG_EXCEPTIONS; + else if (::strcasecmp (arg, "memory") == 0 ) flag_bits &= ~PD_LOG_MEMORY; + else if (::strcasecmp (arg, "data-short") == 0 ) flag_bits &= ~PD_LOG_MEMORY_DATA_SHORT; + else if (::strcasecmp (arg, "data-long") == 0 ) flag_bits &= ~PD_LOG_MEMORY_DATA_LONG; + else if (::strcasecmp (arg, "protections")== 0 ) flag_bits &= ~PD_LOG_PROCESS; + else if (::strcasecmp (arg, "step") == 0 ) flag_bits &= ~PD_LOG_STEP; + else if (::strcasecmp (arg, "task") == 0 ) flag_bits &= ~PD_LOG_TASK; + else if (::strcasecmp (arg, "thread") == 0 ) flag_bits &= ~PD_LOG_THREAD; + else if (::strcasecmp (arg, "verbose") == 0 ) flag_bits &= ~PD_LOG_VERBOSE; + else if (::strcasestr (arg, "watch") == arg ) flag_bits &= ~PD_LOG_WATCHPOINTS; + else + { + feedback_strm->Printf("error: unrecognized log category '%s'\n", arg); + ListLogCategories (feedback_strm); + } } } if (flag_bits == 0) Modified: lldb/trunk/source/Plugins/Process/gdb-remote/ProcessGDBRemoteLog.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Plugins/Process/gdb-remote/ProcessGDBRemoteLog.cpp?rev=119757&r1=119756&r2=119757&view=diff ============================================================================== --- lldb/trunk/source/Plugins/Process/gdb-remote/ProcessGDBRemoteLog.cpp (original) +++ lldb/trunk/source/Plugins/Process/gdb-remote/ProcessGDBRemoteLog.cpp Thu Nov 18 17:32:35 2010 @@ -48,33 +48,38 @@ LogSP log (GetLog ()); if (log) { - uint32_t flag_bits = log->GetMask().Get(); + uint32_t flag_bits = 0; + const size_t argc = args.GetArgumentCount (); - for (size_t i = 0; i < argc; ++i) + if (argc > 0) { - const char *arg = args.GetArgumentAtIndex (i); - - - if (::strcasecmp (arg, "all") == 0 ) flag_bits &= ~GDBR_LOG_ALL; - else if (::strcasecmp (arg, "async") == 0 ) flag_bits &= ~GDBR_LOG_ASYNC; - else if (::strcasestr (arg, "break") == arg ) flag_bits &= ~GDBR_LOG_BREAKPOINTS; - else if (::strcasestr (arg, "comm") == arg ) flag_bits &= ~GDBR_LOG_COMM; - else if (::strcasecmp (arg, "default") == 0 ) flag_bits &= ~GDBR_LOG_DEFAULT; - else if (::strcasecmp (arg, "packets") == 0 ) flag_bits &= ~GDBR_LOG_PACKETS; - else if (::strcasecmp (arg, "memory") == 0 ) flag_bits &= ~GDBR_LOG_MEMORY; - else if (::strcasecmp (arg, "data-short") == 0 ) flag_bits &= ~GDBR_LOG_MEMORY_DATA_SHORT; - else if (::strcasecmp (arg, "data-long") == 0 ) flag_bits &= ~GDBR_LOG_MEMORY_DATA_LONG; - else if (::strcasecmp (arg, "process") == 0 ) flag_bits &= ~GDBR_LOG_PROCESS; - else if (::strcasecmp (arg, "step") == 0 ) flag_bits &= ~GDBR_LOG_STEP; - else if (::strcasecmp (arg, "thread") == 0 ) flag_bits &= ~GDBR_LOG_THREAD; - else if (::strcasecmp (arg, "verbose") == 0 ) flag_bits &= ~GDBR_LOG_VERBOSE; - else if (::strcasestr (arg, "watch") == arg ) flag_bits &= ~GDBR_LOG_WATCHPOINTS; - else + flag_bits = log->GetMask().Get(); + for (size_t i = 0; i < argc; ++i) { - feedback_strm->Printf("error: unrecognized log category '%s'\n", arg); - ListLogCategories (feedback_strm); + const char *arg = args.GetArgumentAtIndex (i); + + + if (::strcasecmp (arg, "all") == 0 ) flag_bits &= ~GDBR_LOG_ALL; + else if (::strcasecmp (arg, "async") == 0 ) flag_bits &= ~GDBR_LOG_ASYNC; + else if (::strcasestr (arg, "break") == arg ) flag_bits &= ~GDBR_LOG_BREAKPOINTS; + else if (::strcasestr (arg, "comm") == arg ) flag_bits &= ~GDBR_LOG_COMM; + else if (::strcasecmp (arg, "default") == 0 ) flag_bits &= ~GDBR_LOG_DEFAULT; + else if (::strcasecmp (arg, "packets") == 0 ) flag_bits &= ~GDBR_LOG_PACKETS; + else if (::strcasecmp (arg, "memory") == 0 ) flag_bits &= ~GDBR_LOG_MEMORY; + else if (::strcasecmp (arg, "data-short") == 0 ) flag_bits &= ~GDBR_LOG_MEMORY_DATA_SHORT; + else if (::strcasecmp (arg, "data-long") == 0 ) flag_bits &= ~GDBR_LOG_MEMORY_DATA_LONG; + else if (::strcasecmp (arg, "process") == 0 ) flag_bits &= ~GDBR_LOG_PROCESS; + else if (::strcasecmp (arg, "step") == 0 ) flag_bits &= ~GDBR_LOG_STEP; + else if (::strcasecmp (arg, "thread") == 0 ) flag_bits &= ~GDBR_LOG_THREAD; + else if (::strcasecmp (arg, "verbose") == 0 ) flag_bits &= ~GDBR_LOG_VERBOSE; + else if (::strcasestr (arg, "watch") == arg ) flag_bits &= ~GDBR_LOG_WATCHPOINTS; + else + { + feedback_strm->Printf("error: unrecognized log category '%s'\n", arg); + ListLogCategories (feedback_strm); + } + } - } if (flag_bits == 0) Modified: lldb/trunk/source/Target/Process.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Target/Process.cpp?rev=119757&r1=119756&r2=119757&view=diff ============================================================================== --- lldb/trunk/source/Target/Process.cpp (original) +++ lldb/trunk/source/Target/Process.cpp Thu Nov 18 17:32:35 2010 @@ -2237,26 +2237,29 @@ m_target.GetDebugger().PopInputReader (m_process_input_reader); } -lldb::UserSettingsControllerSP -Process::GetSettingsController (bool finish) -{ - static UserSettingsControllerSP g_settings_controller (new SettingsController); - static bool initialized = false; - if (!initialized) - { - initialized = UserSettingsController::InitializeSettingsController (g_settings_controller, - Process::SettingsController::global_settings_table, - Process::SettingsController::instance_settings_table); - } +void +Process::Initialize () +{ + UserSettingsControllerSP &usc = GetSettingsController(); + usc.reset (new SettingsController); + UserSettingsController::InitializeSettingsController (usc, + SettingsController::global_settings_table, + SettingsController::instance_settings_table); +} - if (finish) - { - UserSettingsController::FinalizeSettingsController (g_settings_controller); - g_settings_controller.reset(); - initialized = false; - } +void +Process::Terminate () +{ + UserSettingsControllerSP &usc = GetSettingsController(); + UserSettingsController::FinalizeSettingsController (usc); + usc.reset(); +} +UserSettingsControllerSP & +Process::GetSettingsController () +{ + static UserSettingsControllerSP g_settings_controller; return g_settings_controller; } Modified: lldb/trunk/source/Target/Target.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Target/Target.cpp?rev=119757&r1=119756&r2=119757&view=diff ============================================================================== --- lldb/trunk/source/Target/Target.cpp (original) +++ lldb/trunk/source/Target/Target.cpp Thu Nov 18 17:32:35 2010 @@ -769,26 +769,28 @@ return m_scratch_ast_context_ap.get(); } -lldb::UserSettingsControllerSP -Target::GetSettingsController (bool finish) +void +Target::Initialize () { - static lldb::UserSettingsControllerSP g_settings_controller (new SettingsController); - static bool initialized = false; - - if (!initialized) - { - initialized = UserSettingsController::InitializeSettingsController (g_settings_controller, - Target::SettingsController::global_settings_table, - Target::SettingsController::instance_settings_table); - } + UserSettingsControllerSP &usc = GetSettingsController(); + usc.reset (new SettingsController); + UserSettingsController::InitializeSettingsController (usc, + SettingsController::global_settings_table, + SettingsController::instance_settings_table); +} - if (finish) - { - UserSettingsController::FinalizeSettingsController (g_settings_controller); - g_settings_controller.reset(); - initialized = false; - } +void +Target::Terminate () +{ + UserSettingsControllerSP &usc = GetSettingsController(); + UserSettingsController::FinalizeSettingsController (usc); + usc.reset(); +} +UserSettingsControllerSP & +Target::GetSettingsController () +{ + static UserSettingsControllerSP g_settings_controller; return g_settings_controller; } Modified: lldb/trunk/source/Target/Thread.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Target/Thread.cpp?rev=119757&r1=119756&r2=119757&view=diff ============================================================================== --- lldb/trunk/source/Target/Thread.cpp (original) +++ lldb/trunk/source/Target/Thread.cpp Thu Nov 18 17:32:35 2010 @@ -930,26 +930,29 @@ return m_process.GetThreadList().GetThreadSPForThreadPtr(this); } -lldb::UserSettingsControllerSP -Thread::GetSettingsController (bool finish) -{ - static UserSettingsControllerSP g_settings_controller (new ThreadSettingsController); - static bool initialized = false; - if (!initialized) - { - initialized = UserSettingsController::InitializeSettingsController (g_settings_controller, - Thread::ThreadSettingsController::global_settings_table, - Thread::ThreadSettingsController::instance_settings_table); - } +void +Thread::Initialize () +{ + UserSettingsControllerSP &usc = GetSettingsController(); + usc.reset (new SettingsController); + UserSettingsController::InitializeSettingsController (usc, + SettingsController::global_settings_table, + SettingsController::instance_settings_table); +} - if (finish) - { - UserSettingsController::FinalizeSettingsController (g_settings_controller); - g_settings_controller.reset(); - initialized = false; - } +void +Thread::Terminate () +{ + UserSettingsControllerSP &usc = GetSettingsController(); + UserSettingsController::FinalizeSettingsController (usc); + usc.reset(); +} +UserSettingsControllerSP & +Thread::GetSettingsController () +{ + static UserSettingsControllerSP g_settings_controller; return g_settings_controller; } @@ -1010,24 +1013,24 @@ return unknown_state_string; } -#pragma mark "Thread::ThreadSettingsController" +#pragma mark "Thread::SettingsController" //-------------------------------------------------------------- -// class Thread::ThreadSettingsController +// class Thread::SettingsController //-------------------------------------------------------------- -Thread::ThreadSettingsController::ThreadSettingsController () : +Thread::SettingsController::SettingsController () : UserSettingsController ("thread", Process::GetSettingsController()) { m_default_settings.reset (new ThreadInstanceSettings (*this, false, InstanceSettings::GetDefaultName().AsCString())); } -Thread::ThreadSettingsController::~ThreadSettingsController () +Thread::SettingsController::~SettingsController () { } lldb::InstanceSettingsSP -Thread::ThreadSettingsController::CreateInstanceSettings (const char *instance_name) +Thread::SettingsController::CreateInstanceSettings (const char *instance_name) { ThreadInstanceSettings *new_settings = new ThreadInstanceSettings (*(Thread::GetSettingsController().get()), false, instance_name); @@ -1218,11 +1221,11 @@ } //-------------------------------------------------- -// ThreadSettingsController Variable Tables +// SettingsController Variable Tables //-------------------------------------------------- SettingEntry -Thread::ThreadSettingsController::global_settings_table[] = +Thread::SettingsController::global_settings_table[] = { //{ "var-name", var-type , "default", enum-table, init'd, hidden, "help-text"}, { NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL } @@ -1230,7 +1233,7 @@ SettingEntry -Thread::ThreadSettingsController::instance_settings_table[] = +Thread::SettingsController::instance_settings_table[] = { //{ "var-name", var-type, "default", enum-table, init'd, hidden, "help-text"}, { "step-avoid-regexp", eSetVarTypeString, "", NULL, false, false, "A regular expression defining functions step-in won't stop in." }, Modified: lldb/trunk/source/lldb-log.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/lldb-log.cpp?rev=119757&r1=119756&r2=119757&view=diff ============================================================================== --- lldb/trunk/source/lldb-log.cpp (original) +++ lldb/trunk/source/lldb-log.cpp Thu Nov 18 17:32:35 2010 @@ -101,43 +101,46 @@ lldb_private::DisableLog (Args &args, Stream *feedback_strm) { LogSP log(GetLog ()); - uint32_t flag_bits; if (log) { - flag_bits = log->GetMask().Get(); + uint32_t flag_bits = 0; const size_t argc = args.GetArgumentCount (); - for (size_t i = 0; i < argc; ++i) + if (argc > 0) { - const char *arg = args.GetArgumentAtIndex (i); - - if (strcasecmp(arg, "all") == 0 ) flag_bits &= ~LIBLLDB_LOG_ALL; - else if (strcasecmp(arg, "api") == 0) flag_bits &= ~LIBLLDB_LOG_API; - else if (strcasestr(arg, "break") == arg) flag_bits &= ~LIBLLDB_LOG_BREAKPOINTS; - else if (strcasecmp(arg, "default") == 0 ) flag_bits &= ~LIBLLDB_LOG_DEFAULT; - else if (strcasecmp(arg, "dyld") == 0 ) flag_bits &= ~LIBLLDB_LOG_DYNAMIC_LOADER; - else if (strcasestr(arg, "event") == arg) flag_bits &= ~LIBLLDB_LOG_EVENTS; - else if (strcasestr(arg, "expr") == arg) flag_bits &= ~LIBLLDB_LOG_EXPRESSIONS; - else if (strcasestr(arg, "object") == arg) flag_bits &= ~LIBLLDB_LOG_OBJECT; - else if (strcasecmp(arg, "process") == 0 ) flag_bits &= ~LIBLLDB_LOG_PROCESS; - else if (strcasecmp(arg, "script") == 0) flag_bits &= ~LIBLLDB_LOG_SCRIPT; - else if (strcasecmp(arg, "state") == 0 ) flag_bits &= ~LIBLLDB_LOG_STATE; - else if (strcasecmp(arg, "step") == 0 ) flag_bits &= ~LIBLLDB_LOG_STEP; - else if (strcasecmp(arg, "thread") == 0 ) flag_bits &= ~LIBLLDB_LOG_THREAD; - else if (strcasecmp(arg, "verbose") == 0 ) flag_bits &= ~LIBLLDB_LOG_VERBOSE; - else if (strcasestr(arg, "watch") == arg) flag_bits &= ~LIBLLDB_LOG_WATCHPOINTS; - else if (strcasestr(arg, "temp") == arg) flag_bits &= ~LIBLLDB_LOG_TEMPORARY; - else if (strcasestr(arg, "comm") == arg) flag_bits &= ~LIBLLDB_LOG_COMMUNICATION; - else if (strcasestr(arg, "conn") == arg) flag_bits &= ~LIBLLDB_LOG_CONNECTION; - else if (strcasestr(arg, "host") == arg) flag_bits &= ~LIBLLDB_LOG_HOST; - else if (strcasestr(arg, "unwind") == arg) flag_bits &= ~LIBLLDB_LOG_UNWIND; - else + flag_bits = log->GetMask().Get(); + for (size_t i = 0; i < argc; ++i) { - feedback_strm->Printf ("error: unrecognized log category '%s'\n", arg); - ListLogCategories (feedback_strm); - return; + const char *arg = args.GetArgumentAtIndex (i); + + if (strcasecmp(arg, "all") == 0 ) flag_bits &= ~LIBLLDB_LOG_ALL; + else if (strcasecmp(arg, "api") == 0) flag_bits &= ~LIBLLDB_LOG_API; + else if (strcasestr(arg, "break") == arg) flag_bits &= ~LIBLLDB_LOG_BREAKPOINTS; + else if (strcasecmp(arg, "default") == 0 ) flag_bits &= ~LIBLLDB_LOG_DEFAULT; + else if (strcasecmp(arg, "dyld") == 0 ) flag_bits &= ~LIBLLDB_LOG_DYNAMIC_LOADER; + else if (strcasestr(arg, "event") == arg) flag_bits &= ~LIBLLDB_LOG_EVENTS; + else if (strcasestr(arg, "expr") == arg) flag_bits &= ~LIBLLDB_LOG_EXPRESSIONS; + else if (strcasestr(arg, "object") == arg) flag_bits &= ~LIBLLDB_LOG_OBJECT; + else if (strcasecmp(arg, "process") == 0 ) flag_bits &= ~LIBLLDB_LOG_PROCESS; + else if (strcasecmp(arg, "script") == 0) flag_bits &= ~LIBLLDB_LOG_SCRIPT; + else if (strcasecmp(arg, "state") == 0 ) flag_bits &= ~LIBLLDB_LOG_STATE; + else if (strcasecmp(arg, "step") == 0 ) flag_bits &= ~LIBLLDB_LOG_STEP; + else if (strcasecmp(arg, "thread") == 0 ) flag_bits &= ~LIBLLDB_LOG_THREAD; + else if (strcasecmp(arg, "verbose") == 0 ) flag_bits &= ~LIBLLDB_LOG_VERBOSE; + else if (strcasestr(arg, "watch") == arg) flag_bits &= ~LIBLLDB_LOG_WATCHPOINTS; + else if (strcasestr(arg, "temp") == arg) flag_bits &= ~LIBLLDB_LOG_TEMPORARY; + else if (strcasestr(arg, "comm") == arg) flag_bits &= ~LIBLLDB_LOG_COMMUNICATION; + else if (strcasestr(arg, "conn") == arg) flag_bits &= ~LIBLLDB_LOG_CONNECTION; + else if (strcasestr(arg, "host") == arg) flag_bits &= ~LIBLLDB_LOG_HOST; + else if (strcasestr(arg, "unwind") == arg) flag_bits &= ~LIBLLDB_LOG_UNWIND; + else + { + feedback_strm->Printf ("error: unrecognized log category '%s'\n", arg); + ListLogCategories (feedback_strm); + return; + } + } - } if (flag_bits == 0) GetLog ().reset(); Modified: lldb/trunk/source/lldb.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/lldb.cpp?rev=119757&r1=119756&r2=119757&view=diff ============================================================================== --- lldb/trunk/source/lldb.cpp (original) +++ lldb/trunk/source/lldb.cpp Thu Nov 18 17:32:35 2010 @@ -57,12 +57,13 @@ if (!g_inited) { g_inited = true; + Log::Initialize(); Timer::Initialize (); Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__); - - Log::Callbacks log_callbacks = { DisableLog, EnableLog, ListLogCategories }; - - Log::RegisterLogChannel ("lldb", log_callbacks); + + Target::Initialize (); + Process::Initialize (); + Thread::Initialize (); DisassemblerLLVM::Initialize(); ObjectContainerBSDArchive::Initialize(); ObjectFileELF::Initialize(); @@ -86,10 +87,6 @@ //ProcessMacOSX::Initialize(); SymbolVendorMacOSX::Initialize(); #endif - Debugger::GetSettingsController (false); - Target::GetSettingsController (false); - Process::GetSettingsController (false); - Thread::GetSettingsController (false); #ifdef __linux__ ProcessLinux::Initialize(); #endif @@ -128,14 +125,15 @@ SymbolVendorMacOSX::Terminate(); #endif - Thread::GetSettingsController (true); - Process::GetSettingsController (true); - Target::GetSettingsController (true); - Debugger::GetSettingsController (true); - + Thread::Terminate (); + Process::Terminate (); + Target::Terminate (); + #ifdef __linux__ ProcessLinux::Terminate(); #endif + + Log::Terminate(); } extern "C" const double LLDBVersionNumber; From johnny.chen at apple.com Thu Nov 18 17:33:44 2010 From: johnny.chen at apple.com (Johnny Chen) Date: Thu, 18 Nov 2010 23:33:44 -0000 Subject: [Lldb-commits] [lldb] r119758 - /lldb/trunk/test/class_static/TestStaticVariables.py Message-ID: <20101118233344.1D85F2A6C12C@llvm.org> Author: johnny Date: Thu Nov 18 17:33:43 2010 New Revision: 119758 URL: http://llvm.org/viewvc/llvm-project?rev=119758&view=rev Log: Add Python API tests for file and class static variables, too. Modified: lldb/trunk/test/class_static/TestStaticVariables.py Modified: lldb/trunk/test/class_static/TestStaticVariables.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/class_static/TestStaticVariables.py?rev=119758&r1=119757&r2=119758&view=diff ============================================================================== --- lldb/trunk/test/class_static/TestStaticVariables.py (original) +++ lldb/trunk/test/class_static/TestStaticVariables.py Thu Nov 18 17:33:43 2010 @@ -18,10 +18,21 @@ self.static_variable_commands() def test_with_dwarf_and_run_command(self): - """Test that anonymous and named namespace variables display correctly.""" + """Test that file and class static variables display correctly.""" self.buildDwarf() self.static_variable_commands() + @unittest2.skipUnless(sys.platform.startswith("darwin"), "requires Darwin") + def test_with_dsym_and_python_api(self): + """Test Python APIs on file and class static variables.""" + self.buildDsym() + self.static_variable_python() + + def test_with_dwarf_and_python_api(self): + """Test Python APIs on file and class static variables.""" + self.buildDwarf() + self.static_variable_python() + def setUp(self): # Call super's setUp(). TestBase.setUp(self) @@ -29,7 +40,7 @@ self.line = line_number('main.cpp', '// Set break point at this line.') def static_variable_commands(self): - """Test that anonymous and named namespace variables display correctly.""" + """Test that that file and class static variables display correctly.""" self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) self.expect("breakpoint set -f main.cpp -l %d" % self.line, @@ -56,6 +67,58 @@ self.expect("frame variable A::g_points[1].x", VARIABLES_DISPLAYED_CORRECTLY, startstr = "(int) A::g_points[1].x = 11") + def static_variable_python(self): + """Test Python APIs on file and class static variables.""" + exe = os.path.join(os.getcwd(), "a.out") + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target.IsValid(), VALID_TARGET) + + breakpoint = target.BreakpointCreateByLocation("main.cpp", self.line) + self.assertTrue(breakpoint.IsValid(), VALID_BREAKPOINT) + + # Now launch the process, and do not stop at entry point. + self.process = target.LaunchProcess([''], [''], os.ctermid(), 0, False) + + self.process = target.GetProcess() + self.assertTrue(self.process.IsValid(), PROCESS_IS_VALID) + + # The stop reason of the thread should be breakpoint. + thread = self.process.GetThreadAtIndex(0) + if thread.GetStopReason() != lldb.eStopReasonBreakpoint: + from lldbutil import StopReasonString + self.fail(STOPPED_DUE_TO_BREAKPOINT_WITH_STOP_REASON_AS % + StopReasonString(thread.GetStopReason())) + + # Get the SBValue of 'A::g_points' and 'g_points'. + frame = thread.GetFrameAtIndex(0) + + # arguments => False + # locals => False + # statics => True + # in_scope_only => False + valList = frame.GetVariables(False, False, True, False) + + from lldbutil import lldb_iter + for val in lldb_iter(valList, 'GetSize', 'GetValueAtIndex'): + self.DebugSBValue(frame, val) + self.assertTrue(val.GetValueType() == lldb.eValueTypeVariableGlobal) + name = val.GetName() + self.assertTrue(name in ['g_points', 'A::g_points']) + if name == 'g_points': + self.assertTrue(val.GetNumChildren() == 2) + elif name == 'A::g_points' and self.getCompiler() in ['clang', 'llvm-gcc']: + self.assertTrue(val.GetNumChildren() == 2) + child1 = val.GetChildAtIndex(1) + self.DebugSBValue(frame, child1) + child1_x = child1.GetChildAtIndex(0) + self.DebugSBValue(frame, child1_x) + self.assertTrue(child1_x.GetTypeName() == 'int' and + child1_x.GetValue(frame) == '11') + + #variable = frame.LookupVarInScope("A::g_points", "global") + #print "variable:", repr(variable) + if __name__ == '__main__': import atexit From gclayton at apple.com Thu Nov 18 19:05:25 2010 From: gclayton at apple.com (Greg Clayton) Date: Fri, 19 Nov 2010 01:05:25 -0000 Subject: [Lldb-commits] [lldb] r119771 - in /lldb/trunk: include/lldb/Expression/IRForTarget.h source/Expression/IRForTarget.cpp Message-ID: <20101119010525.76FE32A6C12C@llvm.org> Author: gclayton Date: Thu Nov 18 19:05:25 2010 New Revision: 119771 URL: http://llvm.org/viewvc/llvm-project?rev=119771&view=rev Log: Added some logging back and cleaned up the code to match LLDB's coding conventions. Modified: lldb/trunk/include/lldb/Expression/IRForTarget.h lldb/trunk/source/Expression/IRForTarget.cpp Modified: lldb/trunk/include/lldb/Expression/IRForTarget.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/Expression/IRForTarget.h?rev=119771&r1=119770&r2=119771&view=diff ============================================================================== --- lldb/trunk/include/lldb/Expression/IRForTarget.h (original) +++ lldb/trunk/include/lldb/Expression/IRForTarget.h Thu Nov 18 19:05:25 2010 @@ -72,7 +72,9 @@ //------------------------------------------------------------------ /// Run this IR transformer on a single module /// - /// @param[in] M + /// Implementation of the llvm::ModulePass::runOnModule() function. + /// + /// @param[in] llvm_module /// The module to run on. This module is searched for the function /// $__lldb_expr, and that function is passed to the passes one by /// one. @@ -80,18 +82,28 @@ /// @return /// True on success; false otherwise //------------------------------------------------------------------ - bool runOnModule(llvm::Module &M); + virtual bool + runOnModule (llvm::Module &llvm_module); //------------------------------------------------------------------ /// Interface stub + /// + /// Implementation of the llvm::ModulePass::assignPassManager() + /// function. //------------------------------------------------------------------ - void assignPassManager(llvm::PMStack &PMS, - llvm::PassManagerType T = llvm::PMT_ModulePassManager); + virtual void + assignPassManager (llvm::PMStack &pass_mgr_stack, + llvm::PassManagerType pass_mgr_type = llvm::PMT_ModulePassManager); //------------------------------------------------------------------ /// Returns PMT_ModulePassManager + /// + /// Implementation of the llvm::ModulePass::getPotentialPassManagerType() + /// function. //------------------------------------------------------------------ - llvm::PassManagerType getPotentialPassManagerType() const; + virtual llvm::PassManagerType + getPotentialPassManagerType() const; + private: //------------------------------------------------------------------ /// A function-level pass to take the generated global value @@ -102,17 +114,18 @@ //------------------------------------------------------------------ /// The top-level pass implementation /// - /// @param[in] M + /// @param[in] llvm_module /// The module currently being processed. /// - /// @param[in] F + /// @param[in] llvm_function /// The function currently being processed. /// /// @return /// True on success; false otherwise //------------------------------------------------------------------ - bool createResultVariable(llvm::Module &M, - llvm::Function &F); + bool + CreateResultVariable (llvm::Module &llvm_module, + llvm::Function &llvm_function); //------------------------------------------------------------------ /// A function-level pass to find Objective-C constant strings and @@ -122,7 +135,7 @@ //------------------------------------------------------------------ /// Rewrite a single Objective-C constant string. /// - /// @param[in] M + /// @param[in] llvm_module /// The module currently being processed. /// /// @param[in] NSStr @@ -142,25 +155,27 @@ /// @return /// True on success; false otherwise //------------------------------------------------------------------ - bool rewriteObjCConstString(llvm::Module &M, - llvm::GlobalVariable *NSStr, - llvm::GlobalVariable *CStr, - llvm::Instruction *FirstEntryInstruction); + bool + RewriteObjCConstString (llvm::Module &llvm_module, + llvm::GlobalVariable *NSStr, + llvm::GlobalVariable *CStr, + llvm::Instruction *FirstEntryInstruction); //------------------------------------------------------------------ /// The top-level pass implementation /// - /// @param[in] M + /// @param[in] llvm_module /// The module currently being processed. /// - /// @param[in] F + /// @param[in] llvm_function /// The function currently being processed. /// /// @return /// True on success; false otherwise //------------------------------------------------------------------ - bool rewriteObjCConstStrings(llvm::Module &M, - llvm::Function &F); + bool + RewriteObjCConstStrings (llvm::Module &llvm_module, + llvm::Function &llvm_function); //------------------------------------------------------------------ /// A basic block-level pass to find all Objective-C method calls and @@ -179,29 +194,31 @@ /// @param[in] selector_load /// The load of the statically-allocated selector. /// - /// @param[in] M + /// @param[in] llvm_module /// The module containing the load. /// /// @return /// True on success; false otherwise //------------------------------------------------------------------ - bool RewriteObjCSelector(llvm::Instruction* selector_load, - llvm::Module &M); + bool + RewriteObjCSelector (llvm::Instruction* selector_load, + llvm::Module &llvm_module); //------------------------------------------------------------------ /// The top-level pass implementation /// - /// @param[in] M + /// @param[in] llvm_module /// The module currently being processed. /// - /// @param[in] BB + /// @param[in] basic_block /// The basic block currently being processed. /// /// @return /// True on success; false otherwise //------------------------------------------------------------------ - bool rewriteObjCSelectors(llvm::Module &M, - llvm::BasicBlock &BB); + bool + RewriteObjCSelectors (llvm::Module &llvm_module, + llvm::BasicBlock &basic_block); //------------------------------------------------------------------ /// A basic block-level pass to find all newly-declared persistent @@ -211,7 +228,7 @@ /// variables look like normal locals, so they have an allocation. /// This pass excises these allocations and makes references look /// like external references where they will be resolved -- like all - /// other external references -- by resolveExternals(). + /// other external references -- by ResolveExternals(). //------------------------------------------------------------------ //------------------------------------------------------------------ @@ -220,26 +237,28 @@ /// @param[in] persistent_alloc /// The allocation of the persistent variable. /// - /// @param[in] M + /// @param[in] llvm_module /// The module currently being processed. /// /// @return /// True on success; false otherwise //------------------------------------------------------------------ - bool RewritePersistentAlloc(llvm::Instruction *persistent_alloc, - llvm::Module &M); + bool + RewritePersistentAlloc (llvm::Instruction *persistent_alloc, + llvm::Module &llvm_module); //------------------------------------------------------------------ /// The top-level pass implementation /// - /// @param[in] M + /// @param[in] llvm_module /// The module currently being processed. /// - /// @param[in] BB + /// @param[in] basic_block /// The basic block currently being processed. //------------------------------------------------------------------ - bool rewritePersistentAllocs(llvm::Module &M, - llvm::BasicBlock &BB); + bool + RewritePersistentAllocs (llvm::Module &llvm_module, + llvm::BasicBlock &basic_block); //------------------------------------------------------------------ /// A function-level pass to find all external variables and functions @@ -252,7 +271,7 @@ //------------------------------------------------------------------ /// Handle a single externally-defined variable /// - /// @param[in] M + /// @param[in] llvm_module /// The module currently being processed. /// /// @param[in] V @@ -264,13 +283,14 @@ /// @return /// True on success; false otherwise //------------------------------------------------------------------ - bool MaybeHandleVariable(llvm::Module &M, - llvm::Value *V); + bool + MaybeHandleVariable (llvm::Module &llvm_module, + llvm::Value *value); //------------------------------------------------------------------ /// Handle all the arguments to a function call /// - /// @param[in] M + /// @param[in] llvm_module /// The module currently being processed. /// /// @param[in] C @@ -279,13 +299,14 @@ /// @return /// True on success; false otherwise //------------------------------------------------------------------ - bool MaybeHandleCallArguments(llvm::Module &M, - llvm::CallInst *C); + bool + MaybeHandleCallArguments (llvm::Module &llvm_module, + llvm::CallInst *call_inst); //------------------------------------------------------------------ /// Handle a single external function call /// - /// @param[in] M + /// @param[in] llvm_module /// The module currently being processed. /// /// @param[in] C @@ -294,38 +315,41 @@ /// @return /// True on success; false otherwise //------------------------------------------------------------------ - bool MaybeHandleCall(llvm::Module &M, - llvm::CallInst *C); + bool + MaybeHandleCall (llvm::Module &llvm_module, + llvm::CallInst *C); //------------------------------------------------------------------ /// Resolve calls to external functions /// - /// @param[in] M + /// @param[in] llvm_module /// The module currently being processed. /// - /// @param[in] BB + /// @param[in] basic_block /// The basic block currently being processed. /// /// @return /// True on success; false otherwise //------------------------------------------------------------------ - bool resolveCalls(llvm::Module &M, - llvm::BasicBlock &BB); + bool + ResolveCalls (llvm::Module &llvm_module, + llvm::BasicBlock &basic_block); //------------------------------------------------------------------ /// The top-level pass implementation /// - /// @param[in] M + /// @param[in] llvm_module /// The module currently being processed. /// - /// @param[in] BB + /// @param[in] basic_block /// The function currently being processed. /// /// @return /// True on success; false otherwise //------------------------------------------------------------------ - bool resolveExternals(llvm::Module &M, - llvm::Function &F); + bool + ResolveExternals (llvm::Module &llvm_module, + llvm::Function &llvm_function); //------------------------------------------------------------------ /// A basic block-level pass to excise guard variables from the code. @@ -337,17 +361,18 @@ //------------------------------------------------------------------ /// The top-level pass implementation /// - /// @param[in] M + /// @param[in] llvm_module /// The module currently being processed. /// - /// @param[in] BB + /// @param[in] basic_block /// The basic block currently being processed. /// /// @return /// True on success; false otherwise //------------------------------------------------------------------ - bool removeGuards(llvm::Module &M, - llvm::BasicBlock &BB); + bool + RemoveGuards (llvm::Module &llvm_module, + llvm::BasicBlock &basic_block); //------------------------------------------------------------------ /// A function-level pass to make all external variable references @@ -359,21 +384,21 @@ //------------------------------------------------------------------ /// The top-level pass implementation /// - /// @param[in] M + /// @param[in] llvm_module /// The module currently being processed. /// - /// @param[in] F + /// @param[in] llvm_function /// The function currently being processed. /// /// @return /// True on success; false otherwise //------------------------------------------------------------------ - bool replaceVariables(llvm::Module &M, - llvm::Function &F); + bool + ReplaceVariables (llvm::Module &llvm_module, + llvm::Function &llvm_function); /// Flags bool m_resolve_vars; ///< True if external variable references and persistent variable references should be resolved - std::string m_func_name; ///< The name of the function to translate lldb_private::ClangExpressionDeclMap *m_decl_map; ///< The DeclMap containing the Decls llvm::Constant *m_CFStringCreateWithBytes; ///< The address of the function CFStringCreateWithBytes, cast to the appropriate function pointer type @@ -394,18 +419,19 @@ /// FirstEntryInstruction. These instructions replace the constant /// uses, so UnfoldConstant calls itself recursively for those. /// - /// @param[in] M + /// @param[in] llvm_module /// The module currently being processed. /// - /// @param[in] F + /// @param[in] llvm_function /// The function currently being processed. /// /// @return /// True on success; false otherwise //------------------------------------------------------------------ - static bool UnfoldConstant(llvm::Constant *Old, - llvm::Value *New, - llvm::Instruction *FirstEntryInstruction); + static bool + UnfoldConstant (llvm::Constant *old_constant, + llvm::Value *new_constant, + llvm::Instruction *first_entry_inst); }; #endif Modified: lldb/trunk/source/Expression/IRForTarget.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Expression/IRForTarget.cpp?rev=119771&r1=119770&r2=119771&view=diff ============================================================================== --- lldb/trunk/source/Expression/IRForTarget.cpp (original) +++ lldb/trunk/source/Expression/IRForTarget.cpp Thu Nov 18 19:05:25 2010 @@ -32,9 +32,9 @@ static char ID; -IRForTarget::IRForTarget(lldb_private::ClangExpressionDeclMap *decl_map, - bool resolve_vars, - const char *func_name) : +IRForTarget::IRForTarget (lldb_private::ClangExpressionDeclMap *decl_map, + bool resolve_vars, + const char *func_name) : ModulePass(ID), m_decl_map(decl_map), m_CFStringCreateWithBytes(NULL), @@ -47,11 +47,11 @@ /* Handy utility functions used at several places in the code */ static std::string -PrintValue(const Value *V, bool truncate = false) +PrintValue(const Value *value, bool truncate = false) { std::string s; raw_string_ostream rso(s); - V->print(rso); + value->print(rso); rso.flush(); if (truncate) s.resize(s.length() - 1); @@ -59,11 +59,11 @@ } static std::string -PrintType(const Type *T, bool truncate = false) +PrintType(const Type *type, bool truncate = false) { std::string s; raw_string_ostream rso(s); - T->print(rso); + type->print(rso); rso.flush(); if (truncate) s.resize(s.length() - 1); @@ -75,7 +75,7 @@ } bool -IRForTarget::createResultVariable (llvm::Module &llvm_module, llvm::Function &llvm_function) +IRForTarget::CreateResultVariable (llvm::Module &llvm_module, llvm::Function &llvm_function) { lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); @@ -257,16 +257,16 @@ return true; } -static void DebugUsers(lldb::LogSP &log, Value *V, uint8_t depth) +static void DebugUsers(lldb::LogSP &log, Value *value, uint8_t depth) { if (!depth) return; depth--; - log->Printf(" ", V->getNumUses()); + log->Printf(" ", value->getNumUses()); - for (Value::use_iterator ui = V->use_begin(), ue = V->use_end(); + for (Value::use_iterator ui = value->use_begin(), ue = value->use_end(); ui != ue; ++ui) { @@ -278,18 +278,18 @@ } bool -IRForTarget::rewriteObjCConstString(llvm::Module &M, - llvm::GlobalVariable *NSStr, - llvm::GlobalVariable *CStr, - Instruction *FirstEntryInstruction) +IRForTarget::RewriteObjCConstString (llvm::Module &llvm_module, + llvm::GlobalVariable *ns_str, + llvm::GlobalVariable *cstr, + Instruction *FirstEntryInstruction) { lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); - const Type *i8_ptr_ty = Type::getInt8PtrTy(M.getContext()); - const IntegerType *intptr_ty = Type::getIntNTy(M.getContext(), - (M.getPointerSize() == Module::Pointer64) ? 64 : 32); - const Type *i32_ty = Type::getInt32Ty(M.getContext()); - const Type *i8_ty = Type::getInt8Ty(M.getContext()); + const Type *i8_ptr_ty = Type::getInt8PtrTy(llvm_module.getContext()); + const IntegerType *intptr_ty = Type::getIntNTy(llvm_module.getContext(), + (llvm_module.getPointerSize() == Module::Pointer64) ? 64 : 32); + const Type *i32_ty = Type::getInt32Ty(llvm_module.getContext()); + const Type *i8_ty = Type::getInt8Ty(llvm_module.getContext()); if (!m_CFStringCreateWithBytes) { @@ -341,12 +341,12 @@ m_CFStringCreateWithBytes = ConstantExpr::getIntToPtr(CFSCWB_addr_int, CFSCWB_ptr_ty); } - ConstantArray *string_array = dyn_cast(CStr->getInitializer()); + ConstantArray *string_array = dyn_cast(cstr->getInitializer()); SmallVector CFSCWB_arguments; Constant *alloc_arg = Constant::getNullValue(i8_ptr_ty); - Constant *bytes_arg = ConstantExpr::getBitCast(CStr, i8_ptr_ty); + Constant *bytes_arg = ConstantExpr::getBitCast(cstr, i8_ptr_ty); Constant *numBytes_arg = ConstantInt::get(intptr_ty, string_array->getType()->getNumElements(), false); Constant *encoding_arg = ConstantInt::get(i32_ty, 0x0600, false); /* 0x0600 is kCFStringEncodingASCII */ Constant *isExternal_arg = ConstantInt::get(i8_ty, 0x0, false); /* 0x0 is false */ @@ -363,7 +363,7 @@ "CFStringCreateWithBytes", FirstEntryInstruction); - if (!UnfoldConstant(NSStr, CFSCWB_call, FirstEntryInstruction)) + if (!UnfoldConstant(ns_str, CFSCWB_call, FirstEntryInstruction)) { if (log) log->PutCString("Couldn't replace the NSString with the result of the call"); @@ -371,20 +371,19 @@ return false; } - NSStr->eraseFromParent(); + ns_str->eraseFromParent(); return true; } bool -IRForTarget::rewriteObjCConstStrings(Module &M, - Function &F) +IRForTarget::RewriteObjCConstStrings(Module &llvm_module, Function &llvm_function) { lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); - ValueSymbolTable& value_symbol_table = M.getValueSymbolTable(); + ValueSymbolTable& value_symbol_table = llvm_module.getValueSymbolTable(); - BasicBlock &entry_block(F.getEntryBlock()); + BasicBlock &entry_block(llvm_function.getEntryBlock()); Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg()); if (!FirstEntryInstruction) @@ -509,7 +508,7 @@ if (log) log->Printf("Found NSString constant %s, which contains \"%s\"", vi->first(), cstr_array->getAsString().c_str()); - if (!rewriteObjCConstString(M, nsstring_global, cstr_global, FirstEntryInstruction)) + if (!RewriteObjCConstString(llvm_module, nsstring_global, cstr_global, FirstEntryInstruction)) { if (log) log->PutCString("Error rewriting the constant string"); @@ -544,19 +543,18 @@ return true; } -static bool isObjCSelectorRef(Value *V) +static bool IsObjCSelectorRef (Value *value) { - GlobalVariable *GV = dyn_cast(V); + GlobalVariable *global_variable = dyn_cast(value); - if (!GV || !GV->hasName() || !GV->getName().startswith("\01L_OBJC_SELECTOR_REFERENCES_")) + if (!global_variable || !global_variable->hasName() || !global_variable->getName().startswith("\01L_OBJC_SELECTOR_REFERENCES_")) return false; return true; } bool -IRForTarget::RewriteObjCSelector(Instruction* selector_load, - Module &M) +IRForTarget::RewriteObjCSelector (Instruction* selector_load, Module &llvm_module) { lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); @@ -572,8 +570,8 @@ // // where %obj is the object pointer and %tmp is the selector. // - // @"\01L_OBJC_SELECTOR_REFERENCES_" is a pointer to a character array called @"\01L_OBJC_METH_VAR_NAME_". - // @"\01L_OBJC_METH_VAR_NAME_" contains the string. + // @"\01L_OBJC_SELECTOR_REFERENCES_" is a pointer to a character array called @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_". + // @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_" contains the string. // Find the pointer's initializer (a ConstantExpr with opcode GetElementPtr) and get the string from its target @@ -629,17 +627,17 @@ // Build the function type: struct objc_selector *sel_registerName(uint8_t*) // The below code would be "more correct," but in actuality what's required is uint8_t* - //Type *sel_type = StructType::get(M.getContext()); + //Type *sel_type = StructType::get(llvm_module.getContext()); //Type *sel_ptr_type = PointerType::getUnqual(sel_type); - const Type *sel_ptr_type = Type::getInt8PtrTy(M.getContext()); + const Type *sel_ptr_type = Type::getInt8PtrTy(llvm_module.getContext()); std::vector srN_arg_types; - srN_arg_types.push_back(Type::getInt8PtrTy(M.getContext())); + srN_arg_types.push_back(Type::getInt8PtrTy(llvm_module.getContext())); llvm::Type *srN_type = FunctionType::get(sel_ptr_type, srN_arg_types, false); // Build the constant containing the pointer to the function - const IntegerType *intptr_ty = Type::getIntNTy(M.getContext(), - (M.getPointerSize() == Module::Pointer64) ? 64 : 32); + const IntegerType *intptr_ty = Type::getIntNTy(llvm_module.getContext(), + (llvm_module.getPointerSize() == Module::Pointer64) ? 64 : 32); PointerType *srN_ptr_ty = PointerType::getUnqual(srN_type); Constant *srN_addr_int = ConstantInt::get(intptr_ty, sel_registerName_addr, false); m_sel_registerName = ConstantExpr::getIntToPtr(srN_addr_int, srN_ptr_ty); @@ -647,7 +645,7 @@ SmallVector srN_arguments; - Constant *omvn_pointer = ConstantExpr::getBitCast(_objc_meth_var_name_, Type::getInt8PtrTy(M.getContext())); + Constant *omvn_pointer = ConstantExpr::getBitCast(_objc_meth_var_name_, Type::getInt8PtrTy(llvm_module.getContext())); srN_arguments.push_back(omvn_pointer); @@ -667,8 +665,7 @@ } bool -IRForTarget::rewriteObjCSelectors(Module &M, - BasicBlock &BB) +IRForTarget::RewriteObjCSelectors (Module &llvm_module, BasicBlock &basic_block) { lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); @@ -679,14 +676,14 @@ InstrList selector_loads; - for (ii = BB.begin(); - ii != BB.end(); + for (ii = basic_block.begin(); + ii != basic_block.end(); ++ii) { Instruction &inst = *ii; if (LoadInst *load = dyn_cast(&inst)) - if (isObjCSelectorRef(load->getPointerOperand())) + if (IsObjCSelectorRef(load->getPointerOperand())) selector_loads.push_back(&inst); } @@ -696,7 +693,7 @@ iter != selector_loads.end(); ++iter) { - if (!RewriteObjCSelector(*iter, M)) + if (!RewriteObjCSelector(*iter, llvm_module)) { if(log) log->PutCString("Couldn't rewrite a reference to an Objective-C selector"); @@ -708,8 +705,8 @@ } bool -IRForTarget::RewritePersistentAlloc(llvm::Instruction *persistent_alloc, - llvm::Module &llvm_module) +IRForTarget::RewritePersistentAlloc (llvm::Instruction *persistent_alloc, + llvm::Module &llvm_module) { AllocaInst *alloc = dyn_cast(persistent_alloc); @@ -763,8 +760,7 @@ } bool -IRForTarget::rewritePersistentAllocs(llvm::Module &M, - llvm::BasicBlock &BB) +IRForTarget::RewritePersistentAllocs(llvm::Module &llvm_module, llvm::BasicBlock &basic_block) { if (!m_resolve_vars) return true; @@ -778,8 +774,8 @@ InstrList pvar_allocs; - for (ii = BB.begin(); - ii != BB.end(); + for (ii = basic_block.begin(); + ii != basic_block.end(); ++ii) { Instruction &inst = *ii; @@ -796,7 +792,7 @@ iter != pvar_allocs.end(); ++iter) { - if (!RewritePersistentAlloc(*iter, M)) + if (!RewritePersistentAlloc(*iter, llvm_module)) { if(log) log->PutCString("Couldn't rewrite the creation of a persistent variable"); @@ -808,8 +804,7 @@ } static clang::NamedDecl * -DeclForGlobalValue(Module &module, - GlobalValue *global_value) +DeclForGlobalValue(Module &module, GlobalValue *global_value) { NamedMDNode *named_metadata = module.getNamedMetadata("clang.global.decl.ptrs"); @@ -848,11 +843,7 @@ } bool -IRForTarget::MaybeHandleVariable -( - Module &llvm_module, - Value *llvm_value_ptr -) +IRForTarget::MaybeHandleVariable (Module &llvm_module, Value *llvm_value_ptr) { lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); @@ -874,7 +865,7 @@ if (!named_decl) { - if (isObjCSelectorRef(llvm_value_ptr)) + if (IsObjCSelectorRef(llvm_value_ptr)) return true; if (log) @@ -925,23 +916,21 @@ } bool -IRForTarget::MaybeHandleCallArguments(Module &M, - CallInst *Old) +IRForTarget::MaybeHandleCallArguments (Module &llvm_module, CallInst *Old) { // lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); for (unsigned op_index = 0, num_ops = Old->getNumArgOperands(); op_index < num_ops; ++op_index) - if (!MaybeHandleVariable(M, Old->getArgOperand(op_index))) // conservatively believe that this is a store + if (!MaybeHandleVariable(llvm_module, Old->getArgOperand(op_index))) // conservatively believe that this is a store return false; return true; } bool -IRForTarget::MaybeHandleCall(Module &llvm_module, - CallInst *llvm_call_inst) +IRForTarget::MaybeHandleCall (Module &llvm_module, CallInst *llvm_call_inst) { lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); @@ -1060,7 +1049,7 @@ } bool -IRForTarget::resolveCalls(Module &M, BasicBlock &BB) +IRForTarget::ResolveCalls(Module &llvm_module, BasicBlock &basic_block) { ///////////////////////////////////////////////////////////////////////// // Prepare the current basic block for execution in the remote process @@ -1068,15 +1057,15 @@ BasicBlock::iterator ii; - for (ii = BB.begin(); - ii != BB.end(); + for (ii = basic_block.begin(); + ii != basic_block.end(); ++ii) { Instruction &inst = *ii; CallInst *call = dyn_cast(&inst); - if (call && !MaybeHandleCall(M, call)) + if (call && !MaybeHandleCall(llvm_module, call)) return false; } @@ -1084,17 +1073,21 @@ } bool -IRForTarget::resolveExternals(Module &M, - Function &F) +IRForTarget::ResolveExternals (Module &llvm_module, Function &llvm_function) { lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); - for (Module::global_iterator global = M.global_begin(), end = M.global_end(); + for (Module::global_iterator global = llvm_module.global_begin(), end = llvm_module.global_end(); global != end; ++global) { - if (DeclForGlobalValue(M, global) && - !MaybeHandleVariable (M, global)) + if (log) + log->Printf("Examining %s, DeclForGlobalValue returns %p", + (*global).getName().str().c_str(), + DeclForGlobalValue(llvm_module, global)); + + if (DeclForGlobalValue(llvm_module, global) && + !MaybeHandleVariable (llvm_module, global)) return false; } @@ -1126,9 +1119,9 @@ return true; } -static void TurnGuardLoadIntoZero(Instruction* guard_load, Module &M) +static void TurnGuardLoadIntoZero(Instruction* guard_load, Module &llvm_module) { - Constant* zero(ConstantInt::get(Type::getInt8Ty(M.getContext()), 0, true)); + Constant* zero(ConstantInt::get(Type::getInt8Ty(llvm_module.getContext()), 0, true)); Value::use_iterator ui; @@ -1155,7 +1148,7 @@ } bool -IRForTarget::removeGuards(Module &M, BasicBlock &BB) +IRForTarget::RemoveGuards(Module &llvm_module, BasicBlock &basic_block) { /////////////////////////////////////////////////////// // Eliminate any reference to guard variables found. @@ -1169,8 +1162,8 @@ InstrList guard_loads; InstrList guard_stores; - for (ii = BB.begin(); - ii != BB.end(); + for (ii = basic_block.begin(); + ii != basic_block.end(); ++ii) { Instruction &inst = *ii; @@ -1189,7 +1182,7 @@ for (iter = guard_loads.begin(); iter != guard_loads.end(); ++iter) - TurnGuardLoadIntoZero(*iter, M); + TurnGuardLoadIntoZero(*iter, llvm_module); for (iter = guard_stores.begin(); iter != guard_stores.end(); @@ -1200,7 +1193,7 @@ } bool -IRForTarget::UnfoldConstant(Constant *Old, Value *New, Instruction *FirstEntryInstruction) +IRForTarget::UnfoldConstant(Constant *old_constant, Value *new_constant, Instruction *first_entry_inst) { lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); @@ -1210,8 +1203,8 @@ // We do this because the use list might change, invalidating our iterator. // Much better to keep a work list ourselves. - for (ui = Old->use_begin(); - ui != Old->use_end(); + for (ui = old_constant->use_begin(); + ui != old_constant->use_end(); ++ui) users.push_back(*ui); @@ -1240,12 +1233,12 @@ Value *s = constant_expr->getOperand(0); - if (s == Old) - s = New; + if (s == old_constant) + s = new_constant; - BitCastInst *bit_cast(new BitCastInst(s, Old->getType(), "", FirstEntryInstruction)); + BitCastInst *bit_cast(new BitCastInst(s, old_constant->getType(), "", first_entry_inst)); - UnfoldConstant(constant_expr, bit_cast, FirstEntryInstruction); + UnfoldConstant(constant_expr, bit_cast, first_entry_inst); } break; case Instruction::GetElementPtr: @@ -1256,8 +1249,8 @@ Value *ptr = constant_expr->getOperand(0); - if (ptr == Old) - ptr = New; + if (ptr == old_constant) + ptr = new_constant; SmallVector indices; @@ -1270,15 +1263,15 @@ { Value *operand = constant_expr->getOperand(operand_index); - if (operand == Old) - operand = New; + if (operand == old_constant) + operand = new_constant; indices.push_back(operand); } - GetElementPtrInst *get_element_ptr(GetElementPtrInst::Create(ptr, indices.begin(), indices.end(), "", FirstEntryInstruction)); + GetElementPtrInst *get_element_ptr(GetElementPtrInst::Create(ptr, indices.begin(), indices.end(), "", first_entry_inst)); - UnfoldConstant(constant_expr, get_element_ptr, FirstEntryInstruction); + UnfoldConstant(constant_expr, get_element_ptr, first_entry_inst); } break; } @@ -1293,7 +1286,7 @@ else { // simple fall-through case for non-constants - user->replaceUsesOfWith(Old, New); + user->replaceUsesOfWith(old_constant, new_constant); } } @@ -1301,7 +1294,7 @@ } bool -IRForTarget::replaceVariables(Module &M, Function &F) +IRForTarget::ReplaceVariables (Module &llvm_module, Function &llvm_function) { if (!m_resolve_vars) return true; @@ -1322,9 +1315,9 @@ if (!m_decl_map->GetStructInfo (num_elements, size, alignment)) return false; - Function::arg_iterator iter(F.getArgumentList().begin()); + Function::arg_iterator iter(llvm_function.getArgumentList().begin()); - if (iter == F.getArgumentList().end()) + if (iter == llvm_function.getArgumentList().end()) return false; Argument *argument = iter; @@ -1333,7 +1326,7 @@ { ++iter; - if (iter == F.getArgumentList().end()) + if (iter == llvm_function.getArgumentList().end()) return false; argument = iter; @@ -1345,13 +1338,13 @@ if (log) log->Printf("Arg: \"%s\"", PrintValue(argument).c_str()); - BasicBlock &entry_block(F.getEntryBlock()); + BasicBlock &entry_block(llvm_function.getEntryBlock()); Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg()); if (!FirstEntryInstruction) return false; - LLVMContext &context(M.getContext()); + LLVMContext &context(llvm_module.getContext()); const IntegerType *offset_type(Type::getInt32Ty(context)); if (!offset_type) @@ -1394,11 +1387,11 @@ } bool -IRForTarget::runOnModule(Module &M) +IRForTarget::runOnModule (Module &llvm_module) { lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); - Function* function = M.getFunction(StringRef(m_func_name.c_str())); + Function* function = llvm_module.getFunction(StringRef(m_func_name.c_str())); if (!function) { @@ -1414,7 +1407,7 @@ // Replace $__lldb_expr_result with a persistent variable // - if (!createResultVariable(M, *function)) + if (!CreateResultVariable(llvm_module, *function)) return false; /////////////////////////////////////////////////////////////////////////////// @@ -1426,14 +1419,14 @@ std::string s; raw_string_ostream oss(s); - M.print(oss, NULL); + llvm_module.print(oss, NULL); oss.flush(); log->Printf("Module after creating the result variable: \n\"%s\"", s.c_str()); } - if (!rewriteObjCConstStrings(M, *function)) + if (!RewriteObjCConstStrings(llvm_module, *function)) return false; if (log) @@ -1441,7 +1434,7 @@ std::string s; raw_string_ostream oss(s); - M.print(oss, NULL); + llvm_module.print(oss, NULL); oss.flush(); @@ -1456,16 +1449,16 @@ bbi != function->end(); ++bbi) { - if (!removeGuards(M, *bbi)) + if (!RemoveGuards(llvm_module, *bbi)) return false; - if (!rewritePersistentAllocs(M, *bbi)) + if (!RewritePersistentAllocs(llvm_module, *bbi)) return false; - if (!rewriteObjCSelectors(M, *bbi)) + if (!RewriteObjCSelectors(llvm_module, *bbi)) return false; - if (!resolveCalls(M, *bbi)) + if (!ResolveCalls(llvm_module, *bbi)) return false; } @@ -1473,10 +1466,10 @@ // Run function-level passes // - if (!resolveExternals(M, *function)) + if (!ResolveExternals(llvm_module, *function)) return false; - if (!replaceVariables(M, *function)) + if (!ReplaceVariables(llvm_module, *function)) return false; if (log) @@ -1484,7 +1477,7 @@ std::string s; raw_string_ostream oss(s); - M.print(oss, NULL); + llvm_module.print(oss, NULL); oss.flush(); @@ -1495,8 +1488,7 @@ } void -IRForTarget::assignPassManager(PMStack &PMS, - PassManagerType T) +IRForTarget::assignPassManager (PMStack &pass_mgr_stack, PassManagerType pass_mgr_type) { } From scallanan at apple.com Thu Nov 18 20:52:21 2010 From: scallanan at apple.com (Sean Callanan) Date: Fri, 19 Nov 2010 02:52:21 -0000 Subject: [Lldb-commits] [lldb] r119779 - in /lldb/trunk: include/lldb/Expression/ASTResultSynthesizer.h include/lldb/Expression/ClangUserExpression.h include/lldb/Symbol/ClangASTContext.h source/Breakpoint/BreakpointOptions.cpp source/Expression/ASTResultSynthesizer.cpp source/Expression/ClangUserExpression.cpp source/Symbol/ClangASTContext.cpp Message-ID: <20101119025221.4A1BF2A6C12C@llvm.org> Author: spyffe Date: Thu Nov 18 20:52:21 2010 New Revision: 119779 URL: http://llvm.org/viewvc/llvm-project?rev=119779&view=rev Log: Added support for indicating to the expression parser that the result of an expression should be coerced to a specific type. Also made breakpoint conditions pass in the bool type for this type. The expression parser ignores this indication for now. Modified: lldb/trunk/include/lldb/Expression/ASTResultSynthesizer.h lldb/trunk/include/lldb/Expression/ClangUserExpression.h lldb/trunk/include/lldb/Symbol/ClangASTContext.h lldb/trunk/source/Breakpoint/BreakpointOptions.cpp lldb/trunk/source/Expression/ASTResultSynthesizer.cpp lldb/trunk/source/Expression/ClangUserExpression.cpp lldb/trunk/source/Symbol/ClangASTContext.cpp Modified: lldb/trunk/include/lldb/Expression/ASTResultSynthesizer.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/Expression/ASTResultSynthesizer.h?rev=119779&r1=119778&r2=119779&view=diff ============================================================================== --- lldb/trunk/include/lldb/Expression/ASTResultSynthesizer.h (original) +++ lldb/trunk/include/lldb/Expression/ASTResultSynthesizer.h Thu Nov 18 20:52:21 2010 @@ -12,6 +12,7 @@ #include "clang/Sema/SemaConsumer.h" #include "lldb/Core/ClangForward.h" +#include "lldb/Symbol/TaggedASTType.h" namespace lldb_private { @@ -39,8 +40,13 @@ /// in order to produce LLVM IR, this SemaConsumer must allow them to /// pass to the next step in the chain after processing. Passthrough is /// the next ASTConsumer, or NULL if none is required. + /// + /// @param[in] desired_type + /// The type that the result should have. May be initialized with a + /// NULL type, in which case the type is inferred. //---------------------------------------------------------------------- - ASTResultSynthesizer(clang::ASTConsumer *passthrough); + ASTResultSynthesizer(clang::ASTConsumer *passthrough, + TypeFromUser desired_type); //---------------------------------------------------------------------- /// Destructor @@ -128,6 +134,7 @@ clang::ASTConsumer *m_passthrough; ///< The ASTConsumer down the chain, for passthrough. NULL if it's a SemaConsumer. clang::SemaConsumer *m_passthrough_sema; ///< The SemaConsumer down the chain, for passthrough. NULL if it's an ASTConsumer. clang::Sema *m_sema; ///< The Sema to use. + TypeFromUser m_desired_type; ///< If non-NULL, the type to coerce the result to. }; } Modified: lldb/trunk/include/lldb/Expression/ClangUserExpression.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/Expression/ClangUserExpression.h?rev=119779&r1=119778&r2=119779&view=diff ============================================================================== --- lldb/trunk/include/lldb/Expression/ClangUserExpression.h (original) +++ lldb/trunk/include/lldb/Expression/ClangUserExpression.h Thu Nov 18 20:52:21 2010 @@ -25,6 +25,7 @@ #include "lldb/Core/ClangForward.h" #include "lldb/Expression/ClangExpression.h" #include "lldb/Expression/ClangExpressionVariable.h" +#include "lldb/Symbol/TaggedASTType.h" #include "llvm/ExecutionEngine/JITMemoryManager.h" @@ -73,11 +74,17 @@ /// are needed for parsing (locations of functions, types of /// variables, persistent variables, etc.) /// + /// @param[in] desired_type + /// The type that the expression should be coerced to. If NULL, + /// inferred from the expression itself. + /// /// @return /// True on success (no errors); false otherwise. //------------------------------------------------------------------ bool - Parse (Stream &error_stream, ExecutionContext &exe_ctx); + Parse (Stream &error_stream, + ExecutionContext &exe_ctx, + TypeFromUser desired_type); //------------------------------------------------------------------ /// Execute the parsed expression @@ -238,6 +245,7 @@ std::string m_expr_text; ///< The text of the expression, as typed by the user std::string m_expr_prefix; ///< The text of the translation-level definitions, as provided by the user std::string m_transformed_text; ///< The text of the expression, as send to the parser + TypeFromUser m_desired_type; ///< The type to coerce the expression's result to. If NULL, inferred from the expression. std::auto_ptr m_expr_decl_map; ///< The map to use when parsing and materializing the expression. std::auto_ptr m_local_variables; ///< The local expression variables, if the expression is DWARF. Modified: lldb/trunk/include/lldb/Symbol/ClangASTContext.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/Symbol/ClangASTContext.h?rev=119779&r1=119778&r2=119779&view=diff ============================================================================== --- lldb/trunk/include/lldb/Symbol/ClangASTContext.h (original) +++ lldb/trunk/include/lldb/Symbol/ClangASTContext.h Thu Nov 18 20:52:21 2010 @@ -126,6 +126,9 @@ { return GetBuiltInType_void(getASTContext()); } + + lldb::clang_type_t + GetBuiltInType_bool(); lldb::clang_type_t GetBuiltInType_objc_id(); Modified: lldb/trunk/source/Breakpoint/BreakpointOptions.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Breakpoint/BreakpointOptions.cpp?rev=119779&r1=119778&r2=119779&view=diff ============================================================================== --- lldb/trunk/source/Breakpoint/BreakpointOptions.cpp (original) +++ lldb/trunk/source/Breakpoint/BreakpointOptions.cpp Thu Nov 18 20:52:21 2010 @@ -18,6 +18,7 @@ #include "lldb/Core/Value.h" #include "lldb/Breakpoint/StoppointCallbackContext.h" #include "lldb/Target/Process.h" +#include "lldb/Target/Target.h" #include "lldb/Target/ThreadSpec.h" #include "lldb/Target/ThreadPlanTestCondition.h" @@ -193,8 +194,12 @@ exe_ctx.process->SetDynamicCheckers(dynamic_checkers); } + + // Get the boolean type from the process's scratch AST context + ClangASTContext *ast_context = exe_ctx.target->GetScratchClangASTContext(); + TypeFromUser bool_type(ast_context->GetBuiltInType_bool(), ast_context->getASTContext()); - if (!m_condition_ap->Parse (error_stream, exe_ctx)) + if (!m_condition_ap->Parse (error_stream, exe_ctx, bool_type)) { // Errors mean we should stop. return NULL; Modified: lldb/trunk/source/Expression/ASTResultSynthesizer.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Expression/ASTResultSynthesizer.cpp?rev=119779&r1=119778&r2=119779&view=diff ============================================================================== --- lldb/trunk/source/Expression/ASTResultSynthesizer.cpp (original) +++ lldb/trunk/source/Expression/ASTResultSynthesizer.cpp Thu Nov 18 20:52:21 2010 @@ -24,11 +24,13 @@ using namespace clang; using namespace lldb_private; -ASTResultSynthesizer::ASTResultSynthesizer(ASTConsumer *passthrough) : +ASTResultSynthesizer::ASTResultSynthesizer(ASTConsumer *passthrough, + TypeFromUser desired_type) : m_ast_context (NULL), m_passthrough (passthrough), m_passthrough_sema (NULL), - m_sema (NULL) + m_sema (NULL), + m_desired_type (desired_type) { if (!m_passthrough) return; Modified: lldb/trunk/source/Expression/ClangUserExpression.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Expression/ClangUserExpression.cpp?rev=119779&r1=119778&r2=119779&view=diff ============================================================================== --- lldb/trunk/source/Expression/ClangUserExpression.cpp (original) +++ lldb/trunk/source/Expression/ClangUserExpression.cpp Thu Nov 18 20:52:21 2010 @@ -44,7 +44,8 @@ m_jit_addr(LLDB_INVALID_ADDRESS), m_cplusplus(false), m_objectivec(false), - m_needs_object_ptr(false) + m_needs_object_ptr(false), + m_desired_type(NULL, NULL) { } @@ -55,7 +56,8 @@ clang::ASTConsumer * ClangUserExpression::ASTTransformer (clang::ASTConsumer *passthrough) { - return new ASTResultSynthesizer(passthrough); + return new ASTResultSynthesizer(passthrough, + m_desired_type); } void @@ -115,7 +117,9 @@ } bool -ClangUserExpression::Parse (Stream &error_stream, ExecutionContext &exe_ctx) +ClangUserExpression::Parse (Stream &error_stream, + ExecutionContext &exe_ctx, + TypeFromUser desired_type) { lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); @@ -194,6 +198,8 @@ // Parse the expression // + m_desired_type = desired_type; + m_expr_decl_map.reset(new ClangExpressionDeclMap(&exe_ctx)); ClangExpressionParser parser(target_triple.GetCString(), *this); @@ -452,7 +458,7 @@ StreamString error_stream; - if (!user_expression.Parse (error_stream, exe_ctx)) + if (!user_expression.Parse (error_stream, exe_ctx, TypeFromUser(NULL, NULL))) { if (error_stream.GetString().empty()) error.SetErrorString ("expression failed to parse, unknown error"); Modified: lldb/trunk/source/Symbol/ClangASTContext.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Symbol/ClangASTContext.cpp?rev=119779&r1=119778&r2=119779&view=diff ============================================================================== --- lldb/trunk/source/Symbol/ClangASTContext.cpp (original) +++ lldb/trunk/source/Symbol/ClangASTContext.cpp Thu Nov 18 20:52:21 2010 @@ -671,6 +671,12 @@ } clang_type_t +ClangASTContext::GetBuiltInType_bool() +{ + return getASTContext()->BoolTy.getAsOpaquePtr(); +} + +clang_type_t ClangASTContext::GetBuiltInType_objc_id() { return getASTContext()->ObjCBuiltinIdTy.getAsOpaquePtr(); From gclayton at apple.com Thu Nov 18 21:46:01 2010 From: gclayton at apple.com (Greg Clayton) Date: Fri, 19 Nov 2010 03:46:01 -0000 Subject: [Lldb-commits] [lldb] r119784 - in /lldb/trunk: lldb.xcodeproj/project.pbxproj source/Core/Debugger.cpp source/Core/UserSettingsController.cpp source/Target/Process.cpp source/Target/Target.cpp source/Target/Thread.cpp tools/debugserver/debugserver.xcodeproj/project.pbxproj Message-ID: <20101119034601.E3F962A6C12C@llvm.org> Author: gclayton Date: Thu Nov 18 21:46:01 2010 New Revision: 119784 URL: http://llvm.org/viewvc/llvm-project?rev=119784&view=rev Log: Fixed an issue where the UserSettingsControllers were being created out of order and this was causing the target, process and thread trees to not be available. Modified: lldb/trunk/lldb.xcodeproj/project.pbxproj lldb/trunk/source/Core/Debugger.cpp lldb/trunk/source/Core/UserSettingsController.cpp lldb/trunk/source/Target/Process.cpp lldb/trunk/source/Target/Target.cpp lldb/trunk/source/Target/Thread.cpp lldb/trunk/tools/debugserver/debugserver.xcodeproj/project.pbxproj Modified: lldb/trunk/lldb.xcodeproj/project.pbxproj URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/lldb.xcodeproj/project.pbxproj?rev=119784&r1=119783&r2=119784&view=diff ============================================================================== --- lldb/trunk/lldb.xcodeproj/project.pbxproj (original) +++ lldb/trunk/lldb.xcodeproj/project.pbxproj Thu Nov 18 21:46:01 2010 @@ -2942,7 +2942,7 @@ GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_HIDDEN_VIRTUAL_FUNCTIONS = YES; GCC_WARN_UNUSED_VARIABLE = YES; - ONLY_ACTIVE_ARCH = NO; + ONLY_ACTIVE_ARCH = YES; PREBINDING = NO; VALID_ARCHS = "x86_64 i386"; }; @@ -2979,6 +2979,7 @@ GCC_MODEL_TUNING = G5; GCC_OPTIMIZATION_LEVEL = 0; INSTALL_PATH = /Developer/usr/bin; + ONLY_ACTIVE_ARCH = NO; PREBINDING = NO; PRODUCT_NAME = "darwin-debug"; }; @@ -2993,6 +2994,7 @@ GCC_ENABLE_FIX_AND_CONTINUE = NO; GCC_MODEL_TUNING = G5; INSTALL_PATH = /Developer/usr/bin; + ONLY_ACTIVE_ARCH = NO; PREBINDING = NO; PRODUCT_NAME = "darwin-debug"; ZERO_LINK = NO; @@ -3006,6 +3008,7 @@ GCC_ENABLE_FIX_AND_CONTINUE = YES; GCC_MODEL_TUNING = G5; INSTALL_PATH = /Developer/usr/bin; + ONLY_ACTIVE_ARCH = NO; PREBINDING = NO; PRODUCT_NAME = "darwin-debug"; }; Modified: lldb/trunk/source/Core/Debugger.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Core/Debugger.cpp?rev=119784&r1=119783&r2=119784&view=diff ============================================================================== --- lldb/trunk/source/Core/Debugger.cpp (original) +++ lldb/trunk/source/Core/Debugger.cpp Thu Nov 18 21:46:01 2010 @@ -64,12 +64,12 @@ { if (g_shared_debugger_refcount == 0) { - lldb_private::Initialize(); UserSettingsControllerSP &usc = GetSettingsController(); usc.reset (new SettingsController); UserSettingsController::InitializeSettingsController (usc, SettingsController::global_settings_table, SettingsController::instance_settings_table); + lldb_private::Initialize(); } g_shared_debugger_refcount++; @@ -83,11 +83,11 @@ g_shared_debugger_refcount--; if (g_shared_debugger_refcount == 0) { + lldb_private::WillTerminate(); + lldb_private::Terminate(); UserSettingsControllerSP &usc = GetSettingsController(); UserSettingsController::FinalizeSettingsController (usc); usc.reset(); - lldb_private::WillTerminate(); - lldb_private::Terminate(); } } // Clear our master list of debugger objects @@ -165,7 +165,7 @@ Debugger::Debugger () : UserID (g_unique_id++), - DebuggerInstanceSettings (*Debugger::GetSettingsController()), + DebuggerInstanceSettings (*GetSettingsController()), m_input_comm("debugger.input"), m_input_file (), m_output_file (), @@ -1259,7 +1259,7 @@ lldb::InstanceSettingsSP Debugger::SettingsController::CreateInstanceSettings (const char *instance_name) { - DebuggerInstanceSettings *new_settings = new DebuggerInstanceSettings (*Debugger::GetSettingsController(), + DebuggerInstanceSettings *new_settings = new DebuggerInstanceSettings (*GetSettingsController(), false, instance_name); lldb::InstanceSettingsSP new_settings_sp (new_settings); return new_settings_sp; Modified: lldb/trunk/source/Core/UserSettingsController.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Core/UserSettingsController.cpp?rev=119784&r1=119783&r2=119784&view=diff ============================================================================== --- lldb/trunk/source/Core/UserSettingsController.cpp (original) +++ lldb/trunk/source/Core/UserSettingsController.cpp Thu Nov 18 21:46:01 2010 @@ -71,7 +71,7 @@ { const lldb::UserSettingsControllerSP &parent = controller_sp->GetParent (); if (parent) - parent->RegisterChild (controller_sp); + parent->RegisterChild (controller_sp); controller_sp->CreateSettingsVector (global_settings, true); controller_sp->CreateSettingsVector (instance_settings, false); Modified: lldb/trunk/source/Target/Process.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Target/Process.cpp?rev=119784&r1=119783&r2=119784&view=diff ============================================================================== --- lldb/trunk/source/Target/Process.cpp (original) +++ lldb/trunk/source/Target/Process.cpp Thu Nov 18 21:46:01 2010 @@ -70,7 +70,7 @@ Process::Process(Target &target, Listener &listener) : UserID (LLDB_INVALID_PROCESS_ID), Broadcaster ("lldb.process"), - ProcessInstanceSettings (*(Process::GetSettingsController().get())), + ProcessInstanceSettings (*GetSettingsController()), m_target (target), m_public_state (eStateUnloaded), m_private_state (eStateUnloaded), @@ -2272,7 +2272,7 @@ StreamString sstr; sstr.Printf ("%s", module_sp->GetFileSpec().GetFilename().AsCString()); - Process::GetSettingsController()->RenameInstanceSettings (GetInstanceName().AsCString(), + GetSettingsController()->RenameInstanceSettings (GetInstanceName().AsCString(), sstr.GetData()); } } @@ -2295,8 +2295,9 @@ lldb::InstanceSettingsSP Process::SettingsController::CreateInstanceSettings (const char *instance_name) { - ProcessInstanceSettings *new_settings = new ProcessInstanceSettings (*(Process::GetSettingsController().get()), - false, instance_name); + ProcessInstanceSettings *new_settings = new ProcessInstanceSettings (*GetSettingsController(), + false, + instance_name); lldb::InstanceSettingsSP new_settings_sp (new_settings); return new_settings_sp; } @@ -2336,7 +2337,7 @@ } ProcessInstanceSettings::ProcessInstanceSettings (const ProcessInstanceSettings &rhs) : - InstanceSettings (*(Process::GetSettingsController().get()), CreateInstanceName().AsCString()), + InstanceSettings (*Process::GetSettingsController(), CreateInstanceName().AsCString()), m_run_args (rhs.m_run_args), m_env_vars (rhs.m_env_vars), m_input_path (rhs.m_input_path), Modified: lldb/trunk/source/Target/Target.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Target/Target.cpp?rev=119784&r1=119783&r2=119784&view=diff ============================================================================== --- lldb/trunk/source/Target/Target.cpp (original) +++ lldb/trunk/source/Target/Target.cpp Thu Nov 18 21:46:01 2010 @@ -36,7 +36,7 @@ //---------------------------------------------------------------------- Target::Target(Debugger &debugger) : Broadcaster("lldb.target"), - TargetInstanceSettings (*(Target::GetSettingsController().get())), + TargetInstanceSettings (*GetSettingsController()), m_debugger (debugger), m_images(), m_section_load_list (), @@ -797,7 +797,7 @@ ArchSpec Target::GetDefaultArchitecture () { - lldb::UserSettingsControllerSP settings_controller = Target::GetSettingsController(); + lldb::UserSettingsControllerSP &settings_controller = GetSettingsController(); lldb::SettableVariableType var_type; Error err; StringList result = settings_controller->GetVariable ("target.default-arch", var_type, "[]", err); @@ -814,8 +814,11 @@ Target::SetDefaultArchitecture (ArchSpec new_arch) { if (new_arch.IsValid()) - Target::GetSettingsController ()->SetVariable ("target.default-arch", new_arch.AsCString(), - lldb::eVarSetOperationAssign, false, "[]"); + GetSettingsController ()->SetVariable ("target.default-arch", + new_arch.AsCString(), + lldb::eVarSetOperationAssign, + false, + "[]"); } Target * @@ -848,8 +851,8 @@ sstr.Printf ("%s_%s", module_sp->GetFileSpec().GetFilename().AsCString(), module_sp->GetArchitecture().AsCString()); - Target::GetSettingsController()->RenameInstanceSettings (GetInstanceName().AsCString(), - sstr.GetData()); + GetSettingsController()->RenameInstanceSettings (GetInstanceName().AsCString(), + sstr.GetData()); } } @@ -878,8 +881,9 @@ lldb::InstanceSettingsSP Target::SettingsController::CreateInstanceSettings (const char *instance_name) { - TargetInstanceSettings *new_settings = new TargetInstanceSettings (*(Target::GetSettingsController().get()), - false, instance_name); + TargetInstanceSettings *new_settings = new TargetInstanceSettings (*GetSettingsController(), + false, + instance_name); lldb::InstanceSettingsSP new_settings_sp (new_settings); return new_settings_sp; } @@ -958,7 +962,7 @@ } TargetInstanceSettings::TargetInstanceSettings (const TargetInstanceSettings &rhs) : - InstanceSettings (*(Target::GetSettingsController().get()), CreateInstanceName().AsCString()) + InstanceSettings (*Target::GetSettingsController(), CreateInstanceName().AsCString()) { if (m_instance_name != InstanceSettings::GetDefaultName()) { Modified: lldb/trunk/source/Target/Thread.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Target/Thread.cpp?rev=119784&r1=119783&r2=119784&view=diff ============================================================================== --- lldb/trunk/source/Target/Thread.cpp (original) +++ lldb/trunk/source/Target/Thread.cpp Thu Nov 18 21:46:01 2010 @@ -42,7 +42,7 @@ Thread::Thread (Process &process, lldb::tid_t tid) : UserID (tid), - ThreadInstanceSettings (*(Thread::GetSettingsController().get())), + ThreadInstanceSettings (*GetSettingsController()), m_process (process), m_actual_stop_info_sp (), m_index_id (process.GetNextThreadIndexID ()), @@ -1032,8 +1032,9 @@ lldb::InstanceSettingsSP Thread::SettingsController::CreateInstanceSettings (const char *instance_name) { - ThreadInstanceSettings *new_settings = new ThreadInstanceSettings (*(Thread::GetSettingsController().get()), - false, instance_name); + ThreadInstanceSettings *new_settings = new ThreadInstanceSettings (*GetSettingsController(), + false, + instance_name); lldb::InstanceSettingsSP new_settings_sp (new_settings); return new_settings_sp; } @@ -1068,7 +1069,7 @@ } ThreadInstanceSettings::ThreadInstanceSettings (const ThreadInstanceSettings &rhs) : - InstanceSettings (*(Thread::GetSettingsController().get()), CreateInstanceName().AsCString()), + InstanceSettings (*Thread::GetSettingsController(), CreateInstanceName().AsCString()), m_avoid_regexp_ap (), m_trace_enabled (rhs.m_trace_enabled) { Modified: lldb/trunk/tools/debugserver/debugserver.xcodeproj/project.pbxproj URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/debugserver/debugserver.xcodeproj/project.pbxproj?rev=119784&r1=119783&r2=119784&view=diff ============================================================================== --- lldb/trunk/tools/debugserver/debugserver.xcodeproj/project.pbxproj (original) +++ lldb/trunk/tools/debugserver/debugserver.xcodeproj/project.pbxproj Thu Nov 18 21:46:01 2010 @@ -372,6 +372,7 @@ isa = PBXProject; buildConfigurationList = 1DEB914E08733D8E0010E9CD /* Build configuration list for PBXProject "debugserver" */; compatibilityVersion = "Xcode 3.1"; + developmentRegion = English; hasScannedForEncodings = 1; knownRegions = ( English, From gclayton at apple.com Thu Nov 18 22:16:11 2010 From: gclayton at apple.com (Greg Clayton) Date: Fri, 19 Nov 2010 04:16:11 -0000 Subject: [Lldb-commits] [lldb] r119786 - /lldb/trunk/source/Core/Debugger.cpp Message-ID: <20101119041611.B38982A6C12C@llvm.org> Author: gclayton Date: Thu Nov 18 22:16:11 2010 New Revision: 119786 URL: http://llvm.org/viewvc/llvm-project?rev=119786&view=rev Log: Print out addresses with the correct width for 32 bit programs. Modified: lldb/trunk/source/Core/Debugger.cpp Modified: lldb/trunk/source/Core/Debugger.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Core/Debugger.cpp?rev=119786&r1=119785&r2=119786&view=diff ============================================================================== --- lldb/trunk/source/Core/Debugger.cpp (original) +++ lldb/trunk/source/Core/Debugger.cpp Thu Nov 18 22:16:11 2010 @@ -1138,7 +1138,12 @@ if (vaddr != LLDB_INVALID_ADDRESS) { - s.Printf("0x%16.16llx", vaddr); + int addr_width = 0; + if (exe_ctx && exe_ctx->process) + addr_width = exe_ctx->process->GetAddressByteSize() * 2; + if (addr_width == 0) + addr_width = 16; + s.Printf("0x%*.*llx", addr_width, addr_width, vaddr); var_success = true; } } From johnny.chen at apple.com Fri Nov 19 12:07:14 2010 From: johnny.chen at apple.com (Johnny Chen) Date: Fri, 19 Nov 2010 18:07:14 -0000 Subject: [Lldb-commits] [lldb] r119811 - in /lldb/trunk: source/API/SBFrame.cpp test/class_static/TestStaticVariables.py test/class_static/main.cpp Message-ID: <20101119180714.D08152A6C12C@llvm.org> Author: johnny Date: Fri Nov 19 12:07:14 2010 New Revision: 119811 URL: http://llvm.org/viewvc/llvm-project?rev=119811&view=rev Log: Fill in more test sequences for Python API SBFrame.LookupVarInScope(name, scope). Change SBFrame::LookupVarInScope() to also work with "global" scope in addition to "local" and "parameter" scope. Modified: lldb/trunk/source/API/SBFrame.cpp lldb/trunk/test/class_static/TestStaticVariables.py lldb/trunk/test/class_static/main.cpp Modified: lldb/trunk/source/API/SBFrame.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/API/SBFrame.cpp?rev=119811&r1=119810&r2=119811&view=diff ============================================================================== --- lldb/trunk/source/API/SBFrame.cpp (original) +++ lldb/trunk/source/API/SBFrame.cpp Fri Nov 19 12:07:14 2010 @@ -350,26 +350,25 @@ if (var_scope != eValueTypeInvalid) { - lldb_private::VariableList variable_list; - SBSymbolContext sc = GetSymbolContext (eSymbolContextEverything); - - SBBlock block = sc.GetBlock(); - if (block.IsValid()) - block.AppendVariables (true, true, &variable_list); - - const uint32_t num_variables = variable_list.GetSize(); - - bool found = false; - for (uint32_t i = 0; i < num_variables && !found; ++i) + lldb_private::VariableList *variable_list = m_opaque_sp->GetVariableList(true); + if (variable_list) { - var_sp = variable_list.GetVariableAtIndex(i); - if (var_sp - && (var_sp.get()->GetName() == lldb_private::ConstString(var_name)) - && var_sp.get()->GetScope() == var_scope) - found = true; + const uint32_t num_variables = variable_list->GetSize(); + bool found = false; + for (uint32_t i = 0; i < num_variables && !found; ++i) + { + var_sp = variable_list->GetVariableAtIndex(i); + if (var_sp + && (var_sp.get()->GetName() == lldb_private::ConstString(var_name)) + && var_sp.get()->GetScope() == var_scope) + { + found = true; + break; + } + } + if (!found) + var_sp.reset(); } - if (!found) - var_sp.reset(); } } Modified: lldb/trunk/test/class_static/TestStaticVariables.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/class_static/TestStaticVariables.py?rev=119811&r1=119810&r2=119811&view=diff ============================================================================== --- lldb/trunk/test/class_static/TestStaticVariables.py (original) +++ lldb/trunk/test/class_static/TestStaticVariables.py Fri Nov 19 12:07:14 2010 @@ -116,8 +116,23 @@ self.assertTrue(child1_x.GetTypeName() == 'int' and child1_x.GetValue(frame) == '11') - #variable = frame.LookupVarInScope("A::g_points", "global") - #print "variable:", repr(variable) + # SBFrame.LookupVarInScope() should also work. + val = frame.LookupVarInScope("A::g_points", "global") + self.DebugSBValue(frame, val) + self.assertTrue(val.GetName() == 'A::g_points') + + # Also exercise the "parameter" and "local" scopes while we are at it. + val = frame.LookupVarInScope("argc", "parameter") + self.DebugSBValue(frame, val) + self.assertTrue(val.GetName() == 'argc') + + val = frame.LookupVarInScope("argv", "parameter") + self.DebugSBValue(frame, val) + self.assertTrue(val.GetName() == 'argv') + + val = frame.LookupVarInScope("hello_world", "local") + self.DebugSBValue(frame, val) + self.assertTrue(val.GetName() == 'hello_world') if __name__ == '__main__': Modified: lldb/trunk/test/class_static/main.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/class_static/main.cpp?rev=119811&r1=119810&r2=119811&view=diff ============================================================================== --- lldb/trunk/test/class_static/main.cpp (original) +++ lldb/trunk/test/class_static/main.cpp Fri Nov 19 12:07:14 2010 @@ -45,7 +45,9 @@ int main (int argc, char const *argv[]) { + const char *hello_world = "Hello, world!"; printf ("A::g_points[1].x = %i\n", A::g_points[1].x); // Set break point at this line. printf ("::g_points[1].x = %i\n", g_points[1].x); + printf ("%s\n", hello_world); return 0; } From scallanan at apple.com Fri Nov 19 14:20:02 2010 From: scallanan at apple.com (Sean Callanan) Date: Fri, 19 Nov 2010 20:20:02 -0000 Subject: [Lldb-commits] [lldb] r119835 - in /lldb/trunk: include/lldb/Expression/ClangExpressionDeclMap.h include/lldb/Expression/ClangExpressionParser.h source/Expression/ClangExpressionDeclMap.cpp source/Expression/ClangExpressionParser.cpp Message-ID: <20101119202002.C8DC52A6C12C@llvm.org> Author: spyffe Date: Fri Nov 19 14:20:02 2010 New Revision: 119835 URL: http://llvm.org/viewvc/llvm-project?rev=119835&view=rev Log: Modifications to type handling logic. We no longer perform recursive type lookups, because these are not required for full type fidelity. We also make the SelectorTable last for the full lifetime of the Clang compiler; this was the source of many bugs. Modified: lldb/trunk/include/lldb/Expression/ClangExpressionDeclMap.h lldb/trunk/include/lldb/Expression/ClangExpressionParser.h lldb/trunk/source/Expression/ClangExpressionDeclMap.cpp lldb/trunk/source/Expression/ClangExpressionParser.cpp Modified: lldb/trunk/include/lldb/Expression/ClangExpressionDeclMap.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/Expression/ClangExpressionDeclMap.h?rev=119835&r1=119834&r2=119835&view=diff ============================================================================== --- lldb/trunk/include/lldb/Expression/ClangExpressionDeclMap.h (original) +++ lldb/trunk/include/lldb/Expression/ClangExpressionDeclMap.h Fri Nov 19 14:20:02 2010 @@ -385,15 +385,7 @@ ConstString m_result_name; ///< The name of the result variable ($1, for example) TypeFromUser m_object_pointer_type; ///< The type of the "this" variable, if one exists. - llvm::DenseMap m_lookedup_types; ///< Contains each type that has been looked up in the current type lookup stack. - ///< m_lookedup_types is used to gate the type search in GetDecls(). If a name is - ///< not in it, the following procedure occurs: - ///< 1 The name is added to m_lookedup_types. - ///< 2 The type is looked up and added, potentially causing more type loookups. - ///< 3 The name is removed from m_lookedup_types. - ///< There must be no non-fatal error path that permits the type search to complete - ///< without removing the name from m_lookedup_types at the end. - ///< m_lookedup_type assumes single threadedness. + bool m_ignore_lookups; ///< True during an import when we should be ignoring type lookups. //------------------------------------------------------------------ /// Given a stack frame, find a variable that matches the given name and @@ -611,6 +603,27 @@ TypeFromUser type, lldb::addr_t addr, Error &err); + + //------------------------------------------------------------------ + /// A wrapper for ClangASTContext::CopyType that sets a flag that + /// indicates that we should not respond to queries during import. + /// + /// @param[in] dest_context + /// The target AST context, typically the parser's AST context. + /// + /// @param[in] source_context + /// The source AST context, typically the AST context of whatever + /// symbol file the type was found in. + /// + /// @param[in] clang_type + /// The source type. + /// + /// @return + /// The imported type. + //------------------------------------------------------------------ + void *GuardedCopyType (clang::ASTContext *dest_context, + clang::ASTContext *source_context, + void *clang_type); }; } // namespace lldb_private Modified: lldb/trunk/include/lldb/Expression/ClangExpressionParser.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/Expression/ClangExpressionParser.h?rev=119835&r1=119834&r2=119835&view=diff ============================================================================== --- lldb/trunk/include/lldb/Expression/ClangExpressionParser.h (original) +++ lldb/trunk/include/lldb/Expression/ClangExpressionParser.h Fri Nov 19 14:20:02 2010 @@ -177,6 +177,7 @@ std::auto_ptr m_file_system_options; ///< The Clang file system options object used by the compiler std::auto_ptr m_compiler; ///< The Clang compiler used to parse expressions into IR std::auto_ptr m_builtin_context; ///< Context for Clang built-ins + std::auto_ptr m_selector_table; ///< Selector table for Objective-C methods std::auto_ptr m_ast_context; ///< The AST context used to hold types and names for the parser std::auto_ptr m_code_generator; ///< [owned by the Execution Engine] The Clang object that generates IR RecordingMemoryManager *m_jit_mm; ///< The memory manager for the LLVM JIT Modified: lldb/trunk/source/Expression/ClangExpressionDeclMap.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Expression/ClangExpressionDeclMap.cpp?rev=119835&r1=119834&r2=119835&view=diff ============================================================================== --- lldb/trunk/source/Expression/ClangExpressionDeclMap.cpp (original) +++ lldb/trunk/source/Expression/ClangExpressionDeclMap.cpp Fri Nov 19 14:20:02 2010 @@ -57,7 +57,7 @@ m_materialized_location (0), m_result_name (), m_object_pointer_type (), - m_lookedup_types () + m_ignore_lookups (false) { if (exe_ctx) { @@ -990,6 +990,13 @@ // Back out in all cases where we're not fully initialized if (m_exe_ctx.frame == NULL) return; + + if (m_ignore_lookups) + { + if (log) + log->Printf("Ignoring a query during an import"); + return; + } SymbolContextList sc_list; @@ -1117,36 +1124,22 @@ AddOneVariable(context, pvar); } - - // See information on gating of this operation next to the definition for - // m_lookedup_types. - - if (m_lookedup_types.find(name_unique_cstr) == m_lookedup_types.end()) - { - // 1 The name is added to m_lookedup_types. - m_lookedup_types.insert(std::pair(name_unique_cstr, true)); - - // 2 The type is looked up and added, potentially causing more type loookups. - lldb::TypeSP type_sp (m_sym_ctx.FindTypeByName (name)); + lldb::TypeSP type_sp (m_sym_ctx.FindTypeByName (name)); - if (type_sp) + if (type_sp) + { + if (log) { - if (log) - { - log->Printf ("Matching type found for \"%s\": ", name.GetCString()); - StreamString strm; - type_sp->Dump(&strm, true); - log->PutCString (strm.GetData()); - } + log->Printf ("Matching type found for \"%s\": ", name.GetCString()); + StreamString strm; + type_sp->Dump(&strm, true); + log->PutCString (strm.GetData()); + } - TypeFromUser user_type(type_sp->GetClangType(), + TypeFromUser user_type(type_sp->GetClangType(), type_sp->GetClangAST()); - AddOneType(context, user_type, false); - } - - // 3 The name is removed from m_lookedup_types. - m_lookedup_types.erase(name_unique_cstr); + AddOneType(context, user_type, false); } } @@ -1225,7 +1218,7 @@ if (parser_ast_context) { - type_to_use = ClangASTContext::CopyType(parser_ast_context, var_ast_context, var_opaque_type); + type_to_use = GuardedCopyType(parser_ast_context, var_ast_context, var_opaque_type); if (parser_type) *parser_type = TypeFromParser(type_to_use, parser_ast_context); @@ -1310,9 +1303,9 @@ TypeFromUser user_type = pvar->m_user_type; - TypeFromParser parser_type(ClangASTContext::CopyType(context.GetASTContext(), - user_type.GetASTContext(), - user_type.GetOpaqueQualType()), + TypeFromParser parser_type(GuardedCopyType(context.GetASTContext(), + user_type.GetASTContext(), + user_type.GetOpaqueQualType()), context.GetASTContext()); NamedDecl *var_decl = context.AddVarDecl(parser_type.GetOpaqueQualType()); @@ -1386,7 +1379,7 @@ TypeList *type_list = fun_type->GetTypeList(); fun_ast_context = type_list->GetClangASTContext().getASTContext(); - void *copied_type = ClangASTContext::CopyType(context.GetASTContext(), fun_ast_context, fun_opaque_type); + void *copied_type = GuardedCopyType(context.GetASTContext(), fun_ast_context, fun_opaque_type); fun_decl = context.AddFunDecl(copied_type); } @@ -1436,7 +1429,7 @@ clang::ASTContext *parser_ast_context = context.GetASTContext(); clang::ASTContext *user_ast_context = ut.GetASTContext(); - void *copied_type = ClangASTContext::CopyType(parser_ast_context, user_ast_context, ut.GetOpaqueQualType()); + void *copied_type = GuardedCopyType(parser_ast_context, user_ast_context, ut.GetOpaqueQualType()); TypeFromParser parser_type(copied_type, parser_ast_context); @@ -1471,3 +1464,19 @@ context.AddTypeDecl(copied_type); } + +void * +ClangExpressionDeclMap::GuardedCopyType (ASTContext *dest_context, + ASTContext *source_context, + void *clang_type) +{ + m_ignore_lookups = true; + + void *ret = ClangASTContext::CopyType (dest_context, + source_context, + clang_type); + + m_ignore_lookups = false; + + return ret; +} Modified: lldb/trunk/source/Expression/ClangExpressionParser.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Expression/ClangExpressionParser.cpp?rev=119835&r1=119834&r2=119835&view=diff ============================================================================== --- lldb/trunk/source/Expression/ClangExpressionParser.cpp (original) +++ lldb/trunk/source/Expression/ClangExpressionParser.cpp Fri Nov 19 14:20:02 2010 @@ -254,14 +254,14 @@ // 6. Most of this we get from the CompilerInstance, but we // also want to give the context an ExternalASTSource. - SelectorTable selector_table; + m_selector_table.reset(new SelectorTable()); m_builtin_context.reset(new Builtin::Context(m_compiler->getTarget())); std::auto_ptr ast_context(new ASTContext(m_compiler->getLangOpts(), m_compiler->getSourceManager(), m_compiler->getTarget(), m_compiler->getPreprocessor().getIdentifierTable(), - selector_table, + *m_selector_table.get(), *m_builtin_context.get(), 0)); From johnny.chen at apple.com Fri Nov 19 14:35:15 2010 From: johnny.chen at apple.com (Johnny Chen) Date: Fri, 19 Nov 2010 20:35:15 -0000 Subject: [Lldb-commits] [lldb] r119836 - in /lldb/trunk/test/signed_types: Makefile TestSignedTypes.py main.cpp Message-ID: <20101119203516.0866A2A6C12C@llvm.org> Author: johnny Date: Fri Nov 19 14:35:15 2010 New Revision: 119836 URL: http://llvm.org/viewvc/llvm-project?rev=119836&view=rev Log: Add TestSignedTypes.py to test that variables with signed types display correctly. Added: lldb/trunk/test/signed_types/TestSignedTypes.py Modified: lldb/trunk/test/signed_types/Makefile lldb/trunk/test/signed_types/main.cpp Modified: lldb/trunk/test/signed_types/Makefile URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/signed_types/Makefile?rev=119836&r1=119835&r2=119836&view=diff ============================================================================== --- lldb/trunk/test/signed_types/Makefile (original) +++ lldb/trunk/test/signed_types/Makefile Fri Nov 19 14:35:15 2010 @@ -1,125 +1,5 @@ -#---------------------------------------------------------------------- -# Fill in the source files to build -#---------------------------------------------------------------------- -C_SOURCES := -CXX_SOURCES :=main.cpp -OBJC_SOURCES := -OBJCXX_SOURCES := - -# Uncomment line below for debugging shell commands -# SHELL = /bin/sh -x - -#---------------------------------------------------------------------- -# Change any build/tool options needed -#---------------------------------------------------------------------- -DS := /usr/bin/dsymutil -DSFLAGS = -CFLAGS ?=-arch x86_64 -gdwarf-2 -O0 -CPLUSPLUSFLAGS +=$(CFLAGS) -CPPFLAGS +=$(CFLAGS) -LD = gcc -LDFLAGS = $(CFLAGS) -OBJECTS = -EXE=a.out -DSYM=$(EXE).dSYM - -#---------------------------------------------------------------------- -# Check if we have any C source files -#---------------------------------------------------------------------- -ifneq "$(strip $(C_SOURCES))" "" - OBJECTS +=$(strip $(C_SOURCES:.c=.o)) -endif - -#---------------------------------------------------------------------- -# Check if we have any C++ source files -#---------------------------------------------------------------------- -ifneq "$(strip $(CXX_SOURCES))" "" - OBJECTS +=$(strip $(CXX_SOURCES:.cpp=.o)) - LD = g++ -endif - -#---------------------------------------------------------------------- -# Check if we have any ObjC source files -#---------------------------------------------------------------------- -ifneq "$(strip $(OBJC_SOURCES))" "" - OBJECTS +=$(strip $(OBJC_SOURCES:.m=.o)) - LDFLAGS +=-lobjc -endif - -#---------------------------------------------------------------------- -# Check if we have any ObjC++ source files -#---------------------------------------------------------------------- -ifneq "$(strip $(OBJCXX_SOURCES))" "" - OBJECTS +=$(strip $(OBJCXX_SOURCES:.mm=.o)) - LD = g++ - ifeq $(findstring lobjc,$(LDFLAGS)) "" - LDFLAGS +=-lobjc - endif -endif - - -#---------------------------------------------------------------------- -# Make the dSYM file from the executable -#---------------------------------------------------------------------- -$(DSYM) : $(EXE) - $(DS) $(DSFLAGS) -o "$(DSYM)" "$(EXE)" - -#---------------------------------------------------------------------- -# Compile the executable from all the objects (default rule) with no -# dsym file. -#---------------------------------------------------------------------- -$(EXE) : $(OBJECTS) - $(LD) $(LDFLAGS) $(OBJECTS) -o "$(EXE)" - - -#---------------------------------------------------------------------- -# Automatic variables based on items already entered. Below we create -# an objects lists from the list of sources by replacing all entries -# that end with .c with .o, and we also create a list of prerequisite -# files by replacing all .c files with .d. -#---------------------------------------------------------------------- -PREREQS := $(OBJECTS:.o=.d) - -#---------------------------------------------------------------------- -# Rule for Generating Prerequisites Automatically using .d files and -# the compiler -MM option. The -M option will list all system headers, -# and the -MM option will list all non-system dependencies. -#---------------------------------------------------------------------- -%.d: %.c - @set -e; rm -f $@; \ - $(CC) -M $(CPPFLAGS) $< > $@.$$$$; \ - sed 's,\($*\)\.o[ :]*,\1.o $@ : ,g' < $@.$$$$ > $@; \ - rm -f $@.$$$$ - -%.d: %.cpp - @set -e; rm -f $@; \ - $(CC) -M $(CPPFLAGS) $< > $@.$$$$; \ - sed 's,\($*\)\.o[ :]*,\1.o $@ : ,g' < $@.$$$$ > $@; \ - rm -f $@.$$$$ - -%.d: %.m - @set -e; rm -f $@; \ - $(CC) -M $(CPPFLAGS) $< > $@.$$$$; \ - sed 's,\($*\)\.o[ :]*,\1.o $@ : ,g' < $@.$$$$ > $@; \ - rm -f $@.$$$$ - -%.d: %.mm - @set -e; rm -f $@; \ - $(CC) -M $(CPPFLAGS) $< > $@.$$$$; \ - sed 's,\($*\)\.o[ :]*,\1.o $@ : ,g' < $@.$$$$ > $@; \ - rm -f $@.$$$$ - -#---------------------------------------------------------------------- -# Include all of the makefiles for each source file so we don't have -# to manually track all of the prerequisites for each source file. -#---------------------------------------------------------------------- -sinclude $(PREREQS) - -.PHONY: clean -dsym: $(DSYM) -all: $(EXE) $(DSYM) -clean: - rm -rf "$(EXE)" "$(DSYM)" $(OBJECTS) $(PREREQS) - +LEVEL = ../make +CXX_SOURCES := main.cpp +include $(LEVEL)/Makefile.rules Added: lldb/trunk/test/signed_types/TestSignedTypes.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/signed_types/TestSignedTypes.py?rev=119836&view=auto ============================================================================== --- lldb/trunk/test/signed_types/TestSignedTypes.py (added) +++ lldb/trunk/test/signed_types/TestSignedTypes.py Fri Nov 19 14:35:15 2010 @@ -0,0 +1,69 @@ +""" +Test that variables with signed types display correctly. +""" + +import os, time +import re +import unittest2 +import lldb +from lldbtest import * + +class UnsignedTypesTestCase(TestBase): + + mydir = "signed_types" + + @unittest2.skipUnless(sys.platform.startswith("darwin"), "requires Darwin") + def test_with_dsym(self): + """Test that variables with signed types display correctly.""" + self.buildDsym() + self.signed_types() + + def test_with_dwarf(self): + """Test that variables with signed types display correctly.""" + self.buildDwarf() + self.signed_types() + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break inside main(). + self.line = line_number('main.cpp', '// Set break point at this line.') + + def signed_types(self): + """Test that variables with signed types display correctly.""" + exe = os.path.join(os.getcwd(), "a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Break on line 22 in main() aftre the variables are assigned values. + self.expect("breakpoint set -f main.cpp -l %d" % self.line, + BREAKPOINT_CREATED, + startstr = "Breakpoint created: 1: file ='main.cpp', line = %d, locations = 1" % + self.line) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs = ['state is stopped', 'stop reason = breakpoint']) + + # The breakpoint should have a hit count of 1. + self.expect("breakpoint list", BREAKPOINT_HIT_ONCE, + substrs = [' resolved, hit count = 1']) + + # Execute the assignment statement. + self.runCmd("thread step-over") + + # Test that signed types display correctly. + self.expect("frame variable -t -a", VARIABLES_DISPLAYED_CORRECTLY, + patterns = ["\((short int|short)\) the_signed_short = 99"], + substrs = ["(signed char) the_signed_char = 'c'", + "(int) the_signed_int = 99", + "(long int) the_signed_long = 99", + "(long long int) the_signed_long_long = 99"]) + + +if __name__ == '__main__': + import atexit + lldb.SBDebugger.Initialize() + atexit.register(lambda: lldb.SBDebugger.Terminate()) + unittest2.main() Modified: lldb/trunk/test/signed_types/main.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/signed_types/main.cpp?rev=119836&r1=119835&r2=119836&view=diff ============================================================================== --- lldb/trunk/test/signed_types/main.cpp (original) +++ lldb/trunk/test/signed_types/main.cpp Fri Nov 19 14:35:15 2010 @@ -10,7 +10,7 @@ { char the_char = 'c'; short the_short = 'c'; - wchar_t the_whar_t = 'c'; + wchar_t the_wchar_t = 'c'; int the_int = 'c'; long the_long = 'c'; long long the_long_long = 'c'; @@ -19,7 +19,7 @@ signed short the_signed_short = 'c'; signed int the_signed_int = 'c'; signed long the_signed_long = 'c'; - signed long long the_signed_long_long = 'c'; + signed long long the_signed_long_long = 'c'; // Set break point at this line. return the_char - the_signed_char + the_short - the_signed_short + From ctice at apple.com Fri Nov 19 14:47:55 2010 From: ctice at apple.com (Caroline Tice) Date: Fri, 19 Nov 2010 20:47:55 -0000 Subject: [Lldb-commits] [lldb] r119837 - in /lldb/trunk: include/lldb/ include/lldb/API/ include/lldb/Core/ source/API/ source/Commands/ source/Core/ source/Interpreter/ source/Plugins/Process/gdb-remote/ source/Target/ tools/driver/ Message-ID: <20101119204755.2FA4B2A6C12C@llvm.org> Author: ctice Date: Fri Nov 19 14:47:54 2010 New Revision: 119837 URL: http://llvm.org/viewvc/llvm-project?rev=119837&view=rev Log: Add the ability to catch and do the right thing with Interrupts (often control-c) and end-of-file (often control-d). Modified: lldb/trunk/include/lldb/API/SBDebugger.h lldb/trunk/include/lldb/Core/Communication.h lldb/trunk/include/lldb/Core/Debugger.h lldb/trunk/include/lldb/lldb-enumerations.h lldb/trunk/source/API/SBDebugger.cpp lldb/trunk/source/Commands/CommandObjectBreakpointCommand.cpp lldb/trunk/source/Commands/CommandObjectExpression.cpp lldb/trunk/source/Core/Communication.cpp lldb/trunk/source/Core/ConnectionFileDescriptor.cpp lldb/trunk/source/Core/Debugger.cpp lldb/trunk/source/Core/InputReader.cpp lldb/trunk/source/Interpreter/CommandInterpreter.cpp lldb/trunk/source/Interpreter/ScriptInterpreterPython.cpp lldb/trunk/source/Plugins/Process/gdb-remote/GDBRemoteCommunication.cpp lldb/trunk/source/Plugins/Process/gdb-remote/GDBRemoteCommunication.h lldb/trunk/source/Target/Process.cpp lldb/trunk/tools/driver/Driver.cpp lldb/trunk/tools/driver/IOChannel.cpp Modified: lldb/trunk/include/lldb/API/SBDebugger.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/API/SBDebugger.h?rev=119837&r1=119836&r2=119837&view=diff ============================================================================== --- lldb/trunk/include/lldb/API/SBDebugger.h (original) +++ lldb/trunk/include/lldb/API/SBDebugger.h Fri Nov 19 14:47:54 2010 @@ -150,6 +150,12 @@ DispatchInput (void *baton, const void *data, size_t data_len); void + DispatchInputInterrupt (); + + void + DispatchInputEndOfFile (); + + void PushInputReader (lldb::SBInputReader &reader); const char * @@ -173,6 +179,9 @@ void SetTerminalWidth (uint32_t term_width); + lldb::user_id_t + GetID (); + const char * GetPrompt() const; Modified: lldb/trunk/include/lldb/Core/Communication.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/Core/Communication.h?rev=119837&r1=119836&r2=119837&view=diff ============================================================================== --- lldb/trunk/include/lldb/Core/Communication.h (original) +++ lldb/trunk/include/lldb/Core/Communication.h Fri Nov 19 14:47:54 2010 @@ -376,7 +376,7 @@ /// The number of bytes to append to the cache. //------------------------------------------------------------------ virtual void - AppendBytesToCache (const uint8_t *src, size_t src_len, bool broadcast); + AppendBytesToCache (const uint8_t *src, size_t src_len, bool broadcast, lldb::ConnectionStatus status); //------------------------------------------------------------------ /// Get any available bytes from our data cache. If this call Modified: lldb/trunk/include/lldb/Core/Debugger.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/Core/Debugger.h?rev=119837&r1=119836&r2=119837&view=diff ============================================================================== --- lldb/trunk/include/lldb/Core/Debugger.h (original) +++ lldb/trunk/include/lldb/Core/Debugger.h Fri Nov 19 14:47:54 2010 @@ -331,6 +331,12 @@ GetTargetList (); void + DispatchInputInterrupt (); + + void + DispatchInputEndOfFile (); + + void DispatchInput (const char *bytes, size_t bytes_len); void Modified: lldb/trunk/include/lldb/lldb-enumerations.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/lldb-enumerations.h?rev=119837&r1=119836&r2=119837&view=diff ============================================================================== --- lldb/trunk/include/lldb/lldb-enumerations.h (original) +++ lldb/trunk/include/lldb/lldb-enumerations.h Fri Nov 19 14:47:54 2010 @@ -287,6 +287,7 @@ typedef enum ConnectionStatus { eConnectionStatusSuccess, // Success + eConnectionStatusEndOfFile, // End-of-file encountered eConnectionStatusError, // Check GetError() for details eConnectionStatusTimedOut, // Request timed out eConnectionStatusNoConnection, // No connection @@ -397,6 +398,8 @@ eInputReaderReactivate, // reader is on top of the stack again after another reader was popped off eInputReaderDeactivate, // another reader was pushed on the stack eInputReaderGotToken, // reader got one of its tokens (granularity) + eInputReaderInterrupt, // reader received an interrupt signal (probably from a control-c) + eInputReaderEndOfFile, // reader received an EOF char (probably from a control-d) eInputReaderDone // reader was just popped off the stack and is done } InputReaderAction; Modified: lldb/trunk/source/API/SBDebugger.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/API/SBDebugger.cpp?rev=119837&r1=119836&r2=119837&view=diff ============================================================================== --- lldb/trunk/source/API/SBDebugger.cpp (original) +++ lldb/trunk/source/API/SBDebugger.cpp Fri Nov 19 14:47:54 2010 @@ -659,6 +659,20 @@ } void +SBDebugger::DispatchInputInterrupt () +{ + if (m_opaque_sp) + m_opaque_sp->DispatchInputInterrupt (); +} + +void +SBDebugger::DispatchInputEndOfFile () +{ + if (m_opaque_sp) + m_opaque_sp->DispatchInputEndOfFile (); +} + +void SBDebugger::PushInputReader (SBInputReader &reader) { LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); @@ -837,3 +851,11 @@ return true; } + +lldb::user_id_t +SBDebugger::GetID() +{ + if (m_opaque_sp) + return m_opaque_sp->GetID(); + return LLDB_INVALID_UID; +} Modified: lldb/trunk/source/Commands/CommandObjectBreakpointCommand.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Commands/CommandObjectBreakpointCommand.cpp?rev=119837&r1=119836&r2=119837&view=diff ============================================================================== --- lldb/trunk/source/Commands/CommandObjectBreakpointCommand.cpp (original) +++ lldb/trunk/source/Commands/CommandObjectBreakpointCommand.cpp Fri Nov 19 14:47:54 2010 @@ -468,6 +468,29 @@ } break; + case eInputReaderInterrupt: + { + // Finish, and cancel the breakpoint command. + reader.SetIsDone (true); + BreakpointOptions *bp_options = (BreakpointOptions *) baton; + if (bp_options) + { + Baton *bp_options_baton = bp_options->GetBaton (); + if (bp_options_baton) + { + ((BreakpointOptions::CommandData *) bp_options_baton->m_data)->user_source.Clear(); + ((BreakpointOptions::CommandData *) bp_options_baton->m_data)->script_source.Clear(); + } + } + ::fprintf (out_fh, "Warning: No command attached to breakpoint.\n"); + ::fflush (out_fh); + } + break; + + case eInputReaderEndOfFile: + reader.SetIsDone (true); + break; + case eInputReaderDone: break; } Modified: lldb/trunk/source/Commands/CommandObjectExpression.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Commands/CommandObjectExpression.cpp?rev=119837&r1=119836&r2=119837&view=diff ============================================================================== --- lldb/trunk/source/Commands/CommandObjectExpression.cpp (original) +++ lldb/trunk/source/Commands/CommandObjectExpression.cpp Fri Nov 19 14:47:54 2010 @@ -199,7 +199,18 @@ // ::fprintf (out_fh, "%3u: ", cmd_object_expr->m_expr_line_count); break; + case eInputReaderInterrupt: + cmd_object_expr->m_expr_lines.clear(); + reader.SetIsDone (true); + reader.GetDebugger().GetOutputStream().Printf("%s\n", "Expression evaluation cancelled."); + break; + + case eInputReaderEndOfFile: + reader.SetIsDone (true); + break; + case eInputReaderDone: + if (cmd_object_expr->m_expr_lines.size() > 0) { cmd_object_expr->EvaluateExpression (cmd_object_expr->m_expr_lines.c_str(), reader.GetDebugger().GetOutputStream(), Modified: lldb/trunk/source/Core/Communication.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Core/Communication.cpp?rev=119837&r1=119836&r2=119837&view=diff ============================================================================== --- lldb/trunk/source/Core/Communication.cpp (original) +++ lldb/trunk/source/Core/Communication.cpp Fri Nov 19 14:47:54 2010 @@ -260,12 +260,13 @@ } void -Communication::AppendBytesToCache (const uint8_t * bytes, size_t len, bool broadcast) +Communication::AppendBytesToCache (const uint8_t * bytes, size_t len, bool broadcast, ConnectionStatus status) { lldb_private::LogIfAnyCategoriesSet (LIBLLDB_LOG_COMMUNICATION, "%p Communication::AppendBytesToCache (src = %p, src_len = %zu, broadcast = %i)", this, bytes, len, broadcast); - if (bytes == NULL || len == 0) + if ((bytes == NULL || len == 0) + && (status != eConnectionStatusEndOfFile)) return; if (m_callback) { @@ -319,12 +320,16 @@ { size_t bytes_read = comm->ReadFromConnection (buf, sizeof(buf), status, &error); if (bytes_read > 0) - comm->AppendBytesToCache (buf, bytes_read, true); + comm->AppendBytesToCache (buf, bytes_read, true, status); + else if ((bytes_read == 0) + && status == eConnectionStatusEndOfFile) + comm->AppendBytesToCache (buf, bytes_read, true, status); } switch (status) { case eConnectionStatusSuccess: + case eConnectionStatusEndOfFile: break; case eConnectionStatusNoConnection: // No connection Modified: lldb/trunk/source/Core/ConnectionFileDescriptor.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Core/ConnectionFileDescriptor.cpp?rev=119837&r1=119836&r2=119837&view=diff ============================================================================== --- lldb/trunk/source/Core/ConnectionFileDescriptor.cpp (original) +++ lldb/trunk/source/Core/ConnectionFileDescriptor.cpp Fri Nov 19 14:47:54 2010 @@ -156,8 +156,18 @@ ssize_t bytes_read = ::read (m_fd, dst, dst_len); if (bytes_read == 0) { - error.SetErrorStringWithFormat("End-of-file.\n"); - status = eConnectionStatusLostConnection; + // 'read' did not return an error, but it didn't return any bytes either ==> End-of-File. + // If the file descriptor is still valid, then we don't return an error; otherwise we do. + // This allows whoever called us to act on the end-of-file, with a valid file descriptor, if they wish. + if (fcntl (m_fd, F_GETFL, 0) >= 0) + { + error.Clear(); // End-of-file, but not an error. Pass along for the end-of-file handlers. + } + else + { + error.SetErrorStringWithFormat("End-of-file.\n"); + } + status = eConnectionStatusEndOfFile; } else if (bytes_read < 0) { Modified: lldb/trunk/source/Core/Debugger.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Core/Debugger.cpp?rev=119837&r1=119836&r2=119837&view=diff ============================================================================== --- lldb/trunk/source/Core/Debugger.cpp (original) +++ lldb/trunk/source/Core/Debugger.cpp Fri Nov 19 14:47:54 2010 @@ -338,20 +338,57 @@ void Debugger::DispatchInputCallback (void *baton, const void *bytes, size_t bytes_len) { - ((Debugger *)baton)->DispatchInput ((char *)bytes, bytes_len); -} + if (bytes_len > 0) + ((Debugger *)baton)->DispatchInput ((char *)bytes, bytes_len); + else + ((Debugger *)baton)->DispatchInputEndOfFile (); +} void Debugger::DispatchInput (const char *bytes, size_t bytes_len) { -// if (bytes == NULL || bytes_len == 0) -// return; + if (bytes == NULL || bytes_len == 0) + return; WriteToDefaultReader (bytes, bytes_len); } void +Debugger::DispatchInputInterrupt () +{ + m_input_reader_data.clear(); + + if (!m_input_readers.empty()) + { + while (CheckIfTopInputReaderIsDone ()) ; + + InputReaderSP reader_sp(m_input_readers.top()); + if (reader_sp) + reader_sp->Notify (eInputReaderInterrupt); + + while (CheckIfTopInputReaderIsDone ()) ; + } +} + +void +Debugger::DispatchInputEndOfFile () +{ + m_input_reader_data.clear(); + + if (!m_input_readers.empty()) + { + while (CheckIfTopInputReaderIsDone ()) ; + + InputReaderSP reader_sp(m_input_readers.top()); + if (reader_sp) + reader_sp->Notify (eInputReaderEndOfFile); + + while (CheckIfTopInputReaderIsDone ()) ; + } +} + +void Debugger::WriteToDefaultReader (const char *bytes, size_t bytes_len) { if (bytes && bytes_len) Modified: lldb/trunk/source/Core/InputReader.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Core/InputReader.cpp?rev=119837&r1=119836&r2=119837&view=diff ============================================================================== --- lldb/trunk/source/Core/InputReader.cpp (original) +++ lldb/trunk/source/Core/InputReader.cpp Fri Nov 19 14:47:54 2010 @@ -324,6 +324,10 @@ m_active = false; break; + case eInputReaderInterrupt: + case eInputReaderEndOfFile: + break; + case eInputReaderGotToken: return; // We don't notify the tokens here, it is done in HandleRawBytes } Modified: lldb/trunk/source/Interpreter/CommandInterpreter.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Interpreter/CommandInterpreter.cpp?rev=119837&r1=119836&r2=119837&view=diff ============================================================================== --- lldb/trunk/source/Interpreter/CommandInterpreter.cpp (original) +++ lldb/trunk/source/Interpreter/CommandInterpreter.cpp Fri Nov 19 14:47:54 2010 @@ -860,6 +860,12 @@ } break; + case eInputReaderInterrupt: + case eInputReaderEndOfFile: + *response_ptr = false; // Assume ^C or ^D means cancel the proposed action + reader.SetIsDone (true); + break; + case eInputReaderDone: break; } Modified: lldb/trunk/source/Interpreter/ScriptInterpreterPython.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Interpreter/ScriptInterpreterPython.cpp?rev=119837&r1=119836&r2=119837&view=diff ============================================================================== --- lldb/trunk/source/Interpreter/ScriptInterpreterPython.cpp (original) +++ lldb/trunk/source/Interpreter/ScriptInterpreterPython.cpp Fri Nov 19 14:47:54 2010 @@ -272,11 +272,6 @@ PyRun_SimpleString (run_string.GetData()); PyRun_SimpleString ("sys.stdin = new_stdin"); - PyRun_SimpleString ("new_mode = tcgetattr(new_stdin)"); - PyRun_SimpleString ("new_mode[3] = new_mode[3] | ECHO | ICANON"); - PyRun_SimpleString ("new_mode[6][VEOF] = 255"); - PyRun_SimpleString ("tcsetattr (new_stdin, TCSANOW, new_mode)"); - run_string.Clear(); run_string.Printf ("lldb.debugger_unique_id = %d", interpreter.GetDebugger().GetID()); PyRun_SimpleString (run_string.GetData()); @@ -302,26 +297,10 @@ { int success; - - // Save the current input file handle state before executing the command. - int input_fd; - struct termios tmp_termios; - bool valid_termios = false; - FILE *input_fh = m_interpreter.GetDebugger().GetInputFileHandle(); - if (input_fh != NULL) - { - input_fd = ::fileno (input_fh); - valid_termios = ::tcgetattr (input_fd, &tmp_termios) == 0; - } - success = PyRun_SimpleString (command); if (success == 0) return true; - // Restore the input file handle state after executing the command. - if (valid_termios) - ::tcsetattr (input_fd, TCSANOW, &tmp_termios); - // The one-liner failed. Append the error message. if (result) result->AppendErrorWithFormat ("python failed attempting to evaluate '%s'\n", command); @@ -366,12 +345,6 @@ script_interpreter->m_termios_valid = ::tcgetattr (input_fd, &script_interpreter->m_termios) == 0; - if (script_interpreter->m_termios_valid) - { - struct termios tmp_termios = script_interpreter->m_termios; - tmp_termios.c_cc[VEOF] = _POSIX_VDISABLE; - ::tcsetattr (input_fd, TCSANOW, &tmp_termios); - } char error_str[1024]; if (script_interpreter->m_embedded_python_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, error_str, sizeof(error_str))) @@ -411,6 +384,14 @@ case eInputReaderReactivate: break; + + case eInputReaderInterrupt: + ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "raise KeyboardInterrupt\n", 24); + break; + + case eInputReaderEndOfFile: + ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()\n", 7); + break; case eInputReaderGotToken: if (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor() != -1) @@ -724,6 +705,17 @@ } break; + case eInputReaderEndOfFile: + case eInputReaderInterrupt: + // Control-c (SIGINT) & control-d both mean finish & exit. + reader.SetIsDone(true); + + // Control-c (SIGINT) ALSO means cancel; do NOT create a breakpoint command. + if (notification == eInputReaderInterrupt) + commands_in_progress.Clear(); + + // Fall through here... + case eInputReaderDone: { BreakpointOptions *bp_options = (BreakpointOptions *)baton; @@ -843,6 +835,10 @@ int num_lines = user_input.GetSize (); StreamString sstr; + // Check to see if we have any data; if not, just return. + if (user_input.GetSize() == 0) + return false; + // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the // frame and breakpoint location as parameters to the function. @@ -933,10 +929,6 @@ PyRun_SimpleString ("save_stdin = sys.stdin"); run_string.Printf ("sys.stdin = open ('%s', 'r')", pty_slave_name); PyRun_SimpleString (run_string.GetData()); - PyRun_SimpleString ("new_mode = tcgetattr(sys.stdin)"); - PyRun_SimpleString ("new_mode[3] = new_mode[3] | ECHO | ICANON"); - PyRun_SimpleString ("new_mode[6][VEOF] = 255"); - PyRun_SimpleString ("tcsetattr (sys.stdin, TCSANOW, new_mode)"); // The following call drops into the embedded interpreter loop and stays there until the // user chooses to exit from the Python interpreter. Modified: lldb/trunk/source/Plugins/Process/gdb-remote/GDBRemoteCommunication.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Plugins/Process/gdb-remote/GDBRemoteCommunication.cpp?rev=119837&r1=119836&r2=119837&view=diff ============================================================================== --- lldb/trunk/source/Plugins/Process/gdb-remote/GDBRemoteCommunication.cpp (original) +++ lldb/trunk/source/Plugins/Process/gdb-remote/GDBRemoteCommunication.cpp Fri Nov 19 14:47:54 2010 @@ -551,7 +551,8 @@ } void -GDBRemoteCommunication::AppendBytesToCache (const uint8_t *src, size_t src_len, bool broadcast) +GDBRemoteCommunication::AppendBytesToCache (const uint8_t *src, size_t src_len, bool broadcast, + ConnectionStatus status) { // Put the packet data into the buffer in a thread safe fashion Mutex::Locker locker(m_bytes_mutex); Modified: lldb/trunk/source/Plugins/Process/gdb-remote/GDBRemoteCommunication.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Plugins/Process/gdb-remote/GDBRemoteCommunication.h?rev=119837&r1=119836&r2=119837&view=diff ============================================================================== --- lldb/trunk/source/Plugins/Process/gdb-remote/GDBRemoteCommunication.h (original) +++ lldb/trunk/source/Plugins/Process/gdb-remote/GDBRemoteCommunication.h Fri Nov 19 14:47:54 2010 @@ -110,7 +110,7 @@ // Communication overrides //------------------------------------------------------------------ virtual void - AppendBytesToCache (const uint8_t *src, size_t src_len, bool broadcast); + AppendBytesToCache (const uint8_t *src, size_t src_len, bool broadcast, lldb::ConnectionStatus status); lldb::pid_t Modified: lldb/trunk/source/Target/Process.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Target/Process.cpp?rev=119837&r1=119836&r2=119837&view=diff ============================================================================== --- lldb/trunk/source/Target/Process.cpp (original) +++ lldb/trunk/source/Target/Process.cpp Fri Nov 19 14:47:54 2010 @@ -1478,10 +1478,6 @@ } else { - // Since we are eating the event, we need to update our state - // otherwise the process state will not match reality... - SetPublicState(state); - if (StateIsStoppedState (state)) { // We caused the process to interrupt itself, so mark this @@ -1508,7 +1504,7 @@ // stopped the process, intercepted the event and set the interrupted // bool in the event. if (event_sp) - BroadcastEvent(event_sp); + m_private_state_broadcaster.BroadcastEvent(event_sp); } return error; @@ -2175,6 +2171,14 @@ } break; + case eInputReaderInterrupt: + process->Halt (); + break; + + case eInputReaderEndOfFile: + process->AppendSTDOUT ("^D", 2); + break; + case eInputReaderDone: break; Modified: lldb/trunk/tools/driver/Driver.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/driver/Driver.cpp?rev=119837&r1=119836&r2=119837&view=diff ============================================================================== --- lldb/trunk/tools/driver/Driver.cpp (original) +++ lldb/trunk/tools/driver/Driver.cpp Fri Nov 19 14:47:54 2010 @@ -40,6 +40,7 @@ static struct termios g_old_stdin_termios; static char *g_debugger_name = (char *) ""; +static Driver *g_driver = NULL; // In the Driver::MainLoop, we change the terminal settings. This function is // added as an atexit handler to make sure we clean them up. @@ -98,10 +99,13 @@ g_debugger_name = (char *) m_debugger.GetInstanceName(); if (g_debugger_name == NULL) g_debugger_name = (char *) ""; + g_driver = this; } Driver::~Driver () { + g_driver = NULL; + g_debugger_name = NULL; } void @@ -1091,6 +1095,23 @@ case eInputReaderDeactivate: break; + case eInputReaderInterrupt: + if (driver->m_io_channel_ap.get() != NULL) + { + driver->m_io_channel_ap->OutWrite ("^C\n", 3); + driver->m_io_channel_ap->RefreshPrompt(); + } + break; + + case eInputReaderEndOfFile: + if (driver->m_io_channel_ap.get() != NULL) + { + driver->m_io_channel_ap->OutWrite ("^D\n", 3); + driver->m_io_channel_ap->RefreshPrompt (); + } + write (driver->m_editline_pty.GetMasterFileDescriptor(), "quit\n", 5); + break; + case eInputReaderGotToken: write (driver->m_editline_pty.GetMasterFileDescriptor(), bytes, bytes_len); break; @@ -1370,6 +1391,24 @@ } } +void +sigint_handler (int signo) +{ + static bool g_interrupt_sent = false; + if (g_driver) + { + if (!g_interrupt_sent) + { + g_interrupt_sent = true; + g_driver->GetDebugger().DispatchInputInterrupt(); + g_interrupt_sent = false; + return; + } + } + + exit (signo); +} + int main (int argc, char const *argv[]) { @@ -1379,6 +1418,7 @@ signal (SIGPIPE, SIG_IGN); signal (SIGWINCH, sigwinch_handler); + signal (SIGINT, sigint_handler); // Create a scope for driver so that the driver object will destroy itself // before SBDebugger::Terminate() is called. Modified: lldb/trunk/tools/driver/IOChannel.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/driver/IOChannel.cpp?rev=119837&r1=119836&r2=119837&view=diff ============================================================================== --- lldb/trunk/tools/driver/IOChannel.cpp (original) +++ lldb/trunk/tools/driver/IOChannel.cpp Fri Nov 19 14:47:54 2010 @@ -448,12 +448,12 @@ if (! IsGettingCommand()) return; - // Compare the current time versus the last time el_gets was called. If less than - // 10000 microseconds (10000000 nanoseconds) have elapsed, wait 10000 microseconds, to ensure el_gets had time - // to finish writing the prompt before we start writing here. + // Compare the current time versus the last time el_gets was called. If less than 40 milliseconds + // (40,0000 microseconds or 40,000,0000 nanoseconds) have elapsed, wait 40,0000 microseconds, to ensure el_gets had + // time to finish writing the prompt before we start writing here. - if (ElapsedNanoSecondsSinceEnteringElGets() < 10000000) - usleep (10000); + if (ElapsedNanoSecondsSinceEnteringElGets() < (40 * 1000 * 1000)) + usleep (40 * 1000); // Use the mutex to make sure OutWrite, ErrWrite and Refresh prompt do not interfere with // each other's output. From gclayton at apple.com Fri Nov 19 15:46:54 2010 From: gclayton at apple.com (Greg Clayton) Date: Fri, 19 Nov 2010 21:46:54 -0000 Subject: [Lldb-commits] [lldb] r119847 - in /lldb/trunk: llvm.zip scripts/build-llvm.pl source/Symbol/ClangASTContext.cpp Message-ID: <20101119214654.D7D852A6C12C@llvm.org> Author: gclayton Date: Fri Nov 19 15:46:54 2010 New Revision: 119847 URL: http://llvm.org/viewvc/llvm-project?rev=119847&view=rev Log: Updated to latest and greatest clang for a "print cvr-qualifiers on function declarations" fix. Modified: lldb/trunk/llvm.zip lldb/trunk/scripts/build-llvm.pl lldb/trunk/source/Symbol/ClangASTContext.cpp Modified: lldb/trunk/llvm.zip URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/llvm.zip?rev=119847&r1=119846&r2=119847&view=diff ============================================================================== Binary files - no diff available. Modified: lldb/trunk/scripts/build-llvm.pl URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/scripts/build-llvm.pl?rev=119847&r1=119846&r2=119847&view=diff ============================================================================== --- lldb/trunk/scripts/build-llvm.pl (original) +++ lldb/trunk/scripts/build-llvm.pl Fri Nov 19 15:46:54 2010 @@ -25,7 +25,7 @@ our $llvm_configuration = $ENV{LLVM_CONFIGURATION}; -our $llvm_revision = "'{2010-11-17T15:30}'"; +our $llvm_revision = "'{2010-11-19T13:00}'"; our $llvm_source_dir = "$ENV{SRCROOT}"; our $cc = "$ENV{DEVELOPER_BIN_DIR}/gcc-4.2"; our $cxx = "$ENV{DEVELOPER_BIN_DIR}/g++-4.2"; Modified: lldb/trunk/source/Symbol/ClangASTContext.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Symbol/ClangASTContext.cpp?rev=119847&r1=119846&r2=119847&view=diff ============================================================================== --- lldb/trunk/source/Symbol/ClangASTContext.cpp (original) +++ lldb/trunk/source/Symbol/ClangASTContext.cpp Fri Nov 19 15:46:54 2010 @@ -380,7 +380,10 @@ ClangASTContext::getDiagnostic() { if (m_diagnostic_ap.get() == NULL) - m_diagnostic_ap.reset(new Diagnostic()); + { + llvm::IntrusiveRefCntPtr diag_id_sp(new DiagnosticIDs()); + m_diagnostic_ap.reset(new Diagnostic(diag_id_sp)); + } return m_diagnostic_ap.get(); } @@ -750,12 +753,9 @@ clang_type_t clang_type) { // null_client's ownership is transferred to diagnostics - NullDiagnosticClient *null_client = new NullDiagnosticClient; - Diagnostic diagnostics(null_client); FileManager file_manager; FileSystemOptions file_system_options; - ASTImporter importer(diagnostics, - *dest_context, file_manager, file_system_options, + ASTImporter importer(*dest_context, file_manager, file_system_options, *source_context, file_manager, file_system_options); QualType src = QualType::getFromOpaquePtr(clang_type); @@ -771,12 +771,9 @@ clang::Decl *source_decl) { // null_client's ownership is transferred to diagnostics - NullDiagnosticClient *null_client = new NullDiagnosticClient; - Diagnostic diagnostics(null_client); FileManager file_manager; FileSystemOptions file_system_options; - ASTImporter importer(diagnostics, - *dest_context, file_manager, file_system_options, + ASTImporter importer(*dest_context, file_manager, file_system_options, *source_context, file_manager, file_system_options); return importer.Import(source_decl); @@ -1100,6 +1097,8 @@ QualType method_qual_type (QualType::getFromOpaquePtr (method_opaque_type)); + method_qual_type.dump(); + CXXMethodDecl *cxx_method_decl = NULL; DeclarationName decl_name (&identifier_table->get(name)); From gclayton at apple.com Fri Nov 19 18:17:58 2010 From: gclayton at apple.com (Greg Clayton) Date: Sat, 20 Nov 2010 00:17:58 -0000 Subject: [Lldb-commits] [lldb] r119877 - in /lldb/trunk/source/Core: Communication.cpp ConnectionFileDescriptor.cpp Message-ID: <20101120001758.14C762A6C12C@llvm.org> Author: gclayton Date: Fri Nov 19 18:17:57 2010 New Revision: 119877 URL: http://llvm.org/viewvc/llvm-project?rev=119877&view=rev Log: Revert the End of file stuff that was added as it was causing read threads to hang around and take a ton of CPU time. Caroline will fix this when she gets back from vacation. Modified: lldb/trunk/source/Core/Communication.cpp lldb/trunk/source/Core/ConnectionFileDescriptor.cpp Modified: lldb/trunk/source/Core/Communication.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Core/Communication.cpp?rev=119877&r1=119876&r2=119877&view=diff ============================================================================== --- lldb/trunk/source/Core/Communication.cpp (original) +++ lldb/trunk/source/Core/Communication.cpp Fri Nov 19 18:17:57 2010 @@ -265,8 +265,7 @@ lldb_private::LogIfAnyCategoriesSet (LIBLLDB_LOG_COMMUNICATION, "%p Communication::AppendBytesToCache (src = %p, src_len = %zu, broadcast = %i)", this, bytes, len, broadcast); - if ((bytes == NULL || len == 0) - && (status != eConnectionStatusEndOfFile)) + if (bytes == NULL || len == 0) return; if (m_callback) { @@ -321,17 +320,14 @@ size_t bytes_read = comm->ReadFromConnection (buf, sizeof(buf), status, &error); if (bytes_read > 0) comm->AppendBytesToCache (buf, bytes_read, true, status); - else if ((bytes_read == 0) - && status == eConnectionStatusEndOfFile) - comm->AppendBytesToCache (buf, bytes_read, true, status); } switch (status) { case eConnectionStatusSuccess: - case eConnectionStatusEndOfFile: break; + case eConnectionStatusEndOfFile: case eConnectionStatusNoConnection: // No connection case eConnectionStatusLostConnection: // Lost connection while connected to a valid connection done = true; Modified: lldb/trunk/source/Core/ConnectionFileDescriptor.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Core/ConnectionFileDescriptor.cpp?rev=119877&r1=119876&r2=119877&view=diff ============================================================================== --- lldb/trunk/source/Core/ConnectionFileDescriptor.cpp (original) +++ lldb/trunk/source/Core/ConnectionFileDescriptor.cpp Fri Nov 19 18:17:57 2010 @@ -156,18 +156,8 @@ ssize_t bytes_read = ::read (m_fd, dst, dst_len); if (bytes_read == 0) { - // 'read' did not return an error, but it didn't return any bytes either ==> End-of-File. - // If the file descriptor is still valid, then we don't return an error; otherwise we do. - // This allows whoever called us to act on the end-of-file, with a valid file descriptor, if they wish. - if (fcntl (m_fd, F_GETFL, 0) >= 0) - { - error.Clear(); // End-of-file, but not an error. Pass along for the end-of-file handlers. - } - else - { - error.SetErrorStringWithFormat("End-of-file.\n"); - } - status = eConnectionStatusEndOfFile; + error.SetErrorStringWithFormat("End-of-file.\n"); + status = eConnectionStatusLostConnection; } else if (bytes_read < 0) { From jmolenda at apple.com Fri Nov 19 19:28:30 2010 From: jmolenda at apple.com (Jason Molenda) Date: Sat, 20 Nov 2010 01:28:30 -0000 Subject: [Lldb-commits] [lldb] r119885 - in /lldb/trunk: include/lldb/Expression/DWARFExpression.h include/lldb/Symbol/UnwindPlan.h source/Core/ValueObjectVariable.cpp source/Expression/ClangExpressionDeclMap.cpp source/Expression/DWARFExpression.cpp source/Plugins/Process/Utility/RegisterContextLLDB.cpp source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp source/Target/StackFrame.cpp Message-ID: <20101120012830.C485E2A6C12C@llvm.org> Author: jmolenda Date: Fri Nov 19 19:28:30 2010 New Revision: 119885 URL: http://llvm.org/viewvc/llvm-project?rev=119885&view=rev Log: Change the DWARFExpression::Evaluate methods to take an optional RegisterContext* - normally this is retrieved from the ExecutionContext's StackFrame but when we need to evaluate an expression while creating the stack frame list this can be a little tricky. Add DW_OP_deref_size, needed for the _sigtramp FDE expression. Add support for processing DWARF expressions in RegisterContextLLDB. Update callers to DWARFExpression::Evaluate. Modified: lldb/trunk/include/lldb/Expression/DWARFExpression.h lldb/trunk/include/lldb/Symbol/UnwindPlan.h lldb/trunk/source/Core/ValueObjectVariable.cpp lldb/trunk/source/Expression/ClangExpressionDeclMap.cpp lldb/trunk/source/Expression/DWARFExpression.cpp lldb/trunk/source/Plugins/Process/Utility/RegisterContextLLDB.cpp lldb/trunk/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp lldb/trunk/source/Target/StackFrame.cpp Modified: lldb/trunk/include/lldb/Expression/DWARFExpression.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/Expression/DWARFExpression.h?rev=119885&r1=119884&r2=119885&view=diff ============================================================================== --- lldb/trunk/include/lldb/Expression/DWARFExpression.h (original) +++ lldb/trunk/include/lldb/Expression/DWARFExpression.h Fri Nov 19 19:28:30 2010 @@ -201,6 +201,7 @@ bool Evaluate (ExecutionContext *exe_ctx, clang::ASTContext *ast_context, + RegisterContext *reg_ctx, lldb::addr_t loclist_base_load_addr, const Value* initial_value_ptr, Value& result, @@ -234,6 +235,13 @@ /// expression. Can be NULL if the location expression uses no /// external variables. /// + /// @param[in] reg_ctx + /// An optional parameter which provides a RegisterContext for use + /// when evaluating the expression (i.e. for fetching register values). + /// Normally this will come from the ExecutionContext's StackFrame but + /// in the case where an expression needs to be evaluated while building + /// the stack frame list, this short-cut is available. + /// /// @param[in] offset /// The offset of the location expression in the data extractor. /// @@ -264,6 +272,7 @@ const DataExtractor& opcodes, ClangExpressionVariableList *expr_locals, ClangExpressionDeclMap *decl_map, + RegisterContext *reg_ctx, const uint32_t offset, const uint32_t length, const uint32_t reg_set, Modified: lldb/trunk/include/lldb/Symbol/UnwindPlan.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/Symbol/UnwindPlan.h?rev=119885&r1=119884&r2=119885&view=diff ============================================================================== --- lldb/trunk/include/lldb/Symbol/UnwindPlan.h (original) +++ lldb/trunk/include/lldb/Symbol/UnwindPlan.h Fri Nov 19 19:28:30 2010 @@ -104,6 +104,12 @@ void SetIsDWARFExpression (const uint8_t *opcodes, uint32_t len); + const uint8_t * + GetDWARFExpressionBytes () { return m_location.expr.opcodes; } + + int + GetDWARFExpressionLength () { return m_location.expr.length; } + void Dump (Stream &s) const; Modified: lldb/trunk/source/Core/ValueObjectVariable.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Core/ValueObjectVariable.cpp?rev=119885&r1=119884&r2=119885&view=diff ============================================================================== --- lldb/trunk/source/Core/ValueObjectVariable.cpp (original) +++ lldb/trunk/source/Core/ValueObjectVariable.cpp Fri Nov 19 19:28:30 2010 @@ -118,7 +118,7 @@ loclist_base_load_addr = sc.function->GetAddressRange().GetBaseAddress().GetLoadAddress (exe_ctx.target); } Value old_value(m_value); - if (expr.Evaluate (&exe_ctx, GetClangAST(), loclist_base_load_addr, NULL, m_value, &m_error)) + if (expr.Evaluate (&exe_ctx, GetClangAST(), NULL, loclist_base_load_addr, NULL, m_value, &m_error)) { m_value.SetContext(Value::eContextTypeVariable, variable); Modified: lldb/trunk/source/Expression/ClangExpressionDeclMap.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Expression/ClangExpressionDeclMap.cpp?rev=119885&r1=119884&r2=119885&view=diff ============================================================================== --- lldb/trunk/source/Expression/ClangExpressionDeclMap.cpp (original) +++ lldb/trunk/source/Expression/ClangExpressionDeclMap.cpp Fri Nov 19 19:28:30 2010 @@ -1205,7 +1205,7 @@ } Error err; - if (!var_location_expr.Evaluate(&exe_ctx, exe_ast_ctx, loclist_base_load_addr, NULL, *var_location.get(), &err)) + if (!var_location_expr.Evaluate(&exe_ctx, exe_ast_ctx, NULL, loclist_base_load_addr, NULL, *var_location.get(), &err)) { if (log) log->Printf("Error evaluating location: %s", err.AsCString()); Modified: lldb/trunk/source/Expression/DWARFExpression.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Expression/DWARFExpression.cpp?rev=119885&r1=119884&r2=119885&view=diff ============================================================================== --- lldb/trunk/source/Expression/DWARFExpression.cpp (original) +++ lldb/trunk/source/Expression/DWARFExpression.cpp Fri Nov 19 19:28:30 2010 @@ -631,48 +631,38 @@ static bool ReadRegisterValueAsScalar ( - ExecutionContext *exe_ctx, + RegisterContext *reg_context, uint32_t reg_kind, uint32_t reg_num, Error *error_ptr, Value &value ) { - if (exe_ctx && exe_ctx->frame) + if (reg_context == NULL) { - RegisterContext *reg_context = exe_ctx->frame->GetRegisterContext(); - - if (reg_context == NULL) + if (error_ptr) + error_ptr->SetErrorStringWithFormat("No register context in frame.\n"); + } + else + { + uint32_t native_reg = reg_context->ConvertRegisterKindToRegisterNumber(reg_kind, reg_num); + if (native_reg == LLDB_INVALID_REGNUM) { if (error_ptr) - error_ptr->SetErrorStringWithFormat("No register context in frame.\n"); + error_ptr->SetErrorStringWithFormat("Unable to convert register kind=%u reg_num=%u to a native register number.\n", reg_kind, reg_num); } else { - uint32_t native_reg = reg_context->ConvertRegisterKindToRegisterNumber(reg_kind, reg_num); - if (native_reg == LLDB_INVALID_REGNUM) - { - if (error_ptr) - error_ptr->SetErrorStringWithFormat("Unable to convert register kind=%u reg_num=%u to a native register number.\n", reg_kind, reg_num); - } - else - { - value.SetValueType (Value::eValueTypeScalar); - value.SetContext (Value::eContextTypeRegisterInfo, const_cast(reg_context->GetRegisterInfoAtIndex(native_reg))); + value.SetValueType (Value::eValueTypeScalar); + value.SetContext (Value::eContextTypeRegisterInfo, const_cast(reg_context->GetRegisterInfoAtIndex(native_reg))); - if (reg_context->ReadRegisterValue (native_reg, value.GetScalar())) - return true; + if (reg_context->ReadRegisterValue (native_reg, value.GetScalar())) + return true; - if (error_ptr) - error_ptr->SetErrorStringWithFormat("Failed to read register %u.\n", native_reg); - } + if (error_ptr) + error_ptr->SetErrorStringWithFormat("Failed to read register %u.\n", native_reg); } } - else - { - if (error_ptr) - error_ptr->SetErrorStringWithFormat("Invalid frame in execution context.\n"); - } return false; } @@ -766,7 +756,7 @@ ) const { ExecutionContext exe_ctx (exe_scope); - return Evaluate(&exe_ctx, ast_context, loclist_base_load_addr, initial_value_ptr, result, error_ptr); + return Evaluate(&exe_ctx, ast_context, NULL, loclist_base_load_addr, initial_value_ptr, result, error_ptr); } bool @@ -774,6 +764,7 @@ ( ExecutionContext *exe_ctx, clang::ASTContext *ast_context, + RegisterContext *reg_ctx, lldb::addr_t loclist_base_load_addr, const Value* initial_value_ptr, Value& result, @@ -783,7 +774,11 @@ if (IsLocationList()) { uint32_t offset = 0; - addr_t pc = exe_ctx->frame->GetRegisterContext()->GetPC(); + addr_t pc; + if (reg_ctx) + pc = reg_ctx->GetPC(); + else + pc = exe_ctx->frame->GetRegisterContext()->GetPC(); if (loclist_base_load_addr != LLDB_INVALID_ADDRESS) { @@ -814,7 +809,7 @@ if (length > 0 && lo_pc <= pc && pc < hi_pc) { - return DWARFExpression::Evaluate (exe_ctx, ast_context, m_data, m_expr_locals, m_decl_map, offset, length, m_reg_kind, initial_value_ptr, result, error_ptr); + return DWARFExpression::Evaluate (exe_ctx, ast_context, m_data, m_expr_locals, m_decl_map, reg_ctx, offset, length, m_reg_kind, initial_value_ptr, result, error_ptr); } offset += length; } @@ -826,7 +821,7 @@ } // Not a location list, just a single expression. - return DWARFExpression::Evaluate (exe_ctx, ast_context, m_data, m_expr_locals, m_decl_map, 0, m_data.GetByteSize(), m_reg_kind, initial_value_ptr, result, error_ptr); + return DWARFExpression::Evaluate (exe_ctx, ast_context, m_data, m_expr_locals, m_decl_map, reg_ctx, 0, m_data.GetByteSize(), m_reg_kind, initial_value_ptr, result, error_ptr); } @@ -839,6 +834,7 @@ const DataExtractor& opcodes, ClangExpressionVariableList *expr_locals, ClangExpressionDeclMap *decl_map, + RegisterContext *reg_ctx, const uint32_t opcodes_offset, const uint32_t opcodes_length, const uint32_t reg_kind, @@ -849,6 +845,9 @@ { std::vector stack; + if (reg_ctx == NULL && exe_ctx && exe_ctx->frame) + reg_ctx = exe_ctx->frame->GetRegisterContext(); + if (initial_value_ptr) stack.push_back(*initial_value_ptr); @@ -1015,9 +1014,86 @@ // on the expression stack. //---------------------------------------------------------------------- case DW_OP_deref_size: - if (error_ptr) - error_ptr->SetErrorString("Unimplemented opcode: DW_OP_deref_size."); - return false; + { + uint8_t size = opcodes.GetU8(&offset); + Value::ValueType value_type = stack.back().GetValueType(); + switch (value_type) + { + case Value::eValueTypeHostAddress: + { + void *src = (void *)stack.back().GetScalar().ULongLong(); + intptr_t ptr; + ::memcpy (&ptr, src, sizeof(void *)); + // I can't decide whether the size operand should apply to the bytes in their + // lldb-host endianness or the target endianness.. I doubt this'll ever come up + // but I'll opt for assuming big endian regardless. + switch (size) + { + case 1: ptr = ptr & 0xff; break; + case 2: ptr = ptr & 0xffff; break; + case 3: ptr = ptr & 0xffffff; break; + case 4: ptr = ptr & 0xffffffff; break; + case 5: ptr = ptr & 0xffffffffff; break; + case 6: ptr = ptr & 0xffffffffffff; break; + case 7: ptr = ptr & 0xffffffffffffff; break; + default: break; + } + stack.back().GetScalar() = ptr; + stack.back().ClearContext(); + } + break; + case Value::eValueTypeLoadAddress: + if (exe_ctx) + { + if (exe_ctx->process) + { + lldb::addr_t pointer_addr = stack.back().GetScalar().ULongLong(LLDB_INVALID_ADDRESS); + uint8_t addr_bytes[sizeof(lldb::addr_t)]; + Error error; + if (exe_ctx->process->ReadMemory(pointer_addr, &addr_bytes, size, error) == size) + { + DataExtractor addr_data(addr_bytes, sizeof(addr_bytes), exe_ctx->process->GetByteOrder(), size); + uint32_t addr_data_offset = 0; + switch (size) + { + case 1: stack.back().GetScalar() = addr_data.GetU8(&addr_data_offset); break; + case 2: stack.back().GetScalar() = addr_data.GetU16(&addr_data_offset); break; + case 4: stack.back().GetScalar() = addr_data.GetU32(&addr_data_offset); break; + case 8: stack.back().GetScalar() = addr_data.GetU64(&addr_data_offset); break; + default: stack.back().GetScalar() = addr_data.GetPointer(&addr_data_offset); + } + stack.back().ClearContext(); + } + else + { + if (error_ptr) + error_ptr->SetErrorStringWithFormat ("Failed to dereference pointer from 0x%llx for DW_OP_deref: %s\n", + pointer_addr, + error.AsCString()); + return false; + } + } + else + { + if (error_ptr) + error_ptr->SetErrorStringWithFormat ("NULL process for DW_OP_deref.\n"); + return false; + } + } + else + { + if (error_ptr) + error_ptr->SetErrorStringWithFormat ("NULL execution context for DW_OP_deref.\n"); + return false; + } + break; + + default: + break; + } + + } + break; //---------------------------------------------------------------------- // OPCODE: DW_OP_xderef_size @@ -1837,7 +1913,7 @@ { reg_num = op - DW_OP_reg0; - if (ReadRegisterValueAsScalar (exe_ctx, reg_kind, reg_num, error_ptr, tmp)) + if (ReadRegisterValueAsScalar (reg_ctx, reg_kind, reg_num, error_ptr, tmp)) stack.push_back(tmp); else return false; @@ -1852,7 +1928,7 @@ case DW_OP_regx: { reg_num = opcodes.GetULEB128(&offset); - if (ReadRegisterValueAsScalar (exe_ctx, reg_kind, reg_num, error_ptr, tmp)) + if (ReadRegisterValueAsScalar (reg_ctx, reg_kind, reg_num, error_ptr, tmp)) stack.push_back(tmp); else return false; @@ -1901,7 +1977,7 @@ { reg_num = op - DW_OP_breg0; - if (ReadRegisterValueAsScalar (exe_ctx, reg_kind, reg_num, error_ptr, tmp)) + if (ReadRegisterValueAsScalar (reg_ctx, reg_kind, reg_num, error_ptr, tmp)) { int64_t breg_offset = opcodes.GetSLEB128(&offset); tmp.ResolveValue(exe_ctx, ast_context) += (uint64_t)breg_offset; @@ -1924,7 +2000,7 @@ { reg_num = opcodes.GetULEB128(&offset); - if (ReadRegisterValueAsScalar (exe_ctx, reg_kind, reg_num, error_ptr, tmp)) + if (ReadRegisterValueAsScalar (reg_ctx, reg_kind, reg_num, error_ptr, tmp)) { int64_t breg_offset = opcodes.GetSLEB128(&offset); tmp.ResolveValue(exe_ctx, ast_context) += (uint64_t)breg_offset; Modified: lldb/trunk/source/Plugins/Process/Utility/RegisterContextLLDB.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Plugins/Process/Utility/RegisterContextLLDB.cpp?rev=119885&r1=119884&r2=119885&view=diff ============================================================================== --- lldb/trunk/source/Plugins/Process/Utility/RegisterContextLLDB.cpp (original) +++ lldb/trunk/source/Plugins/Process/Utility/RegisterContextLLDB.cpp Fri Nov 19 19:28:30 2010 @@ -22,6 +22,10 @@ #include "lldb/Core/DataBufferHeap.h" #include "lldb/Utility/ArchVolatileRegs.h" #include "lldb/Core/Log.h" +#include "lldb/Expression/DWARFExpression.h" +#include "lldb/Core/Value.h" +#include "lldb/Target/ExecutionContext.h" +#include "lldb/Target/StackFrame.h" using namespace lldb; using namespace lldb_private; @@ -814,7 +818,7 @@ UnwindPlan::Row::RegisterLocation unwindplan_regloc; bool have_unwindplan_regloc = false; - int unwindplan_registerkind; + int unwindplan_registerkind = -1; if (m_fast_unwind_plan) { @@ -995,6 +999,44 @@ return true; } + if (unwindplan_regloc.IsDWARFExpression() || unwindplan_regloc.IsAtDWARFExpression()) + { + DataExtractor dwarfdata (unwindplan_regloc.GetDWARFExpressionBytes(), + unwindplan_regloc.GetDWARFExpressionLength(), + m_thread.GetProcess().GetByteOrder(), m_thread.GetProcess().GetAddressByteSize()); + DWARFExpression dwarfexpr (dwarfdata, 0, unwindplan_regloc.GetDWARFExpressionLength()); + dwarfexpr.SetRegisterKind (unwindplan_registerkind); + ExecutionContext exe_ctx (&m_thread.GetProcess(), &m_thread, NULL); + Value result; + Error error; + if (dwarfexpr.Evaluate (&exe_ctx, NULL, this, 0, NULL, result, &error)) + { + addr_t val; + val = result.GetScalar().ULongLong(); + if (unwindplan_regloc.IsDWARFExpression()) + { + regloc.type = eRegisterValueInferred; + regloc.location.register_value = val; + m_registers[lldb_regnum] = regloc; + return true; + } + else + { + regloc.type = eRegisterSavedAtMemoryLocation; + regloc.location.target_memory_location = val; + m_registers[lldb_regnum] = regloc; + return true; + } + } + if (log) + { + log->Printf("%*sFrame %d tried to use IsDWARFExpression or IsAtDWARFExpression for reg %d but failed", + m_frame_number < 100 ? m_frame_number : 100, "", m_frame_number, + lldb_regnum); + } + return false; + } + if (log) { log->Printf("%*sFrame %d could not supply caller's reg %d location", Modified: lldb/trunk/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp?rev=119885&r1=119884&r2=119885&view=diff ============================================================================== --- lldb/trunk/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp (original) +++ lldb/trunk/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp Fri Nov 19 19:28:30 2010 @@ -1225,6 +1225,7 @@ debug_info_data, NULL, NULL, + NULL, block_offset, block_length, eRegisterKindDWARF, Modified: lldb/trunk/source/Target/StackFrame.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Target/StackFrame.cpp?rev=119885&r1=119884&r2=119885&view=diff ============================================================================== --- lldb/trunk/source/Target/StackFrame.cpp (original) +++ lldb/trunk/source/Target/StackFrame.cpp Fri Nov 19 19:28:30 2010 @@ -496,7 +496,7 @@ if (m_sc.function->GetFrameBaseExpression().IsLocationList()) loclist_base_addr = m_sc.function->GetAddressRange().GetBaseAddress().GetLoadAddress (&m_thread.GetProcess().GetTarget()); - if (m_sc.function->GetFrameBaseExpression().Evaluate(&exe_ctx, NULL, loclist_base_addr, NULL, expr_value, &m_frame_base_error) == false) + if (m_sc.function->GetFrameBaseExpression().Evaluate(&exe_ctx, NULL, NULL, loclist_base_addr, NULL, expr_value, &m_frame_base_error) == false) { // We should really have an error if evaluate returns, but in case // we don't, lets set the error to something at least. From scallanan at apple.com Fri Nov 19 20:06:01 2010 From: scallanan at apple.com (Sean Callanan) Date: Sat, 20 Nov 2010 02:06:01 -0000 Subject: [Lldb-commits] [lldb] r119888 - /lldb/trunk/source/Expression/IRForTarget.cpp Message-ID: <20101120020601.69DBF2A6C12C@llvm.org> Author: spyffe Date: Fri Nov 19 20:06:01 2010 New Revision: 119888 URL: http://llvm.org/viewvc/llvm-project?rev=119888&view=rev Log: Removed a stray dump(). Modified: lldb/trunk/source/Expression/IRForTarget.cpp Modified: lldb/trunk/source/Expression/IRForTarget.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Expression/IRForTarget.cpp?rev=119888&r1=119887&r2=119888&view=diff ============================================================================== --- lldb/trunk/source/Expression/IRForTarget.cpp (original) +++ lldb/trunk/source/Expression/IRForTarget.cpp Fri Nov 19 20:06:01 2010 @@ -476,9 +476,7 @@ { if (log) log->PutCString("NSString initializer's str element is not a GlobalVariable"); - - nsstring_cstr->dump(); - + return false; } From scallanan at apple.com Fri Nov 19 20:19:29 2010 From: scallanan at apple.com (Sean Callanan) Date: Sat, 20 Nov 2010 02:19:29 -0000 Subject: [Lldb-commits] [lldb] r119889 - /lldb/trunk/source/Expression/ClangExpressionDeclMap.cpp Message-ID: <20101120021929.4C6B42A6C12C@llvm.org> Author: spyffe Date: Fri Nov 19 20:19:29 2010 New Revision: 119889 URL: http://llvm.org/viewvc/llvm-project?rev=119889&view=rev Log: Made GetVariableValue() more robust in the face of failures in the AST importer. Also ensured that a variable will not be blindly added if GetVariableValue() returns an error. Modified: lldb/trunk/source/Expression/ClangExpressionDeclMap.cpp Modified: lldb/trunk/source/Expression/ClangExpressionDeclMap.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Expression/ClangExpressionDeclMap.cpp?rev=119889&r1=119888&r2=119889&view=diff ============================================================================== --- lldb/trunk/source/Expression/ClangExpressionDeclMap.cpp (original) +++ lldb/trunk/source/Expression/ClangExpressionDeclMap.cpp Fri Nov 19 20:19:29 2010 @@ -1220,6 +1220,14 @@ { type_to_use = GuardedCopyType(parser_ast_context, var_ast_context, var_opaque_type); + if (!type_to_use) + { + if (log) + log->Printf("Couldn't copy a variable's type into the parser's AST context"); + + return NULL; + } + if (parser_type) *parser_type = TypeFromParser(type_to_use, parser_ast_context); } @@ -1271,6 +1279,9 @@ &ut, &pt); + if (!var_location) + return; + NamedDecl *var_decl = context.AddVarDecl(pt.GetOpaqueQualType()); ClangExpressionVariable &entity(m_found_entities.VariableAtIndex(m_found_entities.CreateVariable())); From scallanan at apple.com Fri Nov 19 20:23:49 2010 From: scallanan at apple.com (Sean Callanan) Date: Sat, 20 Nov 2010 02:23:49 -0000 Subject: [Lldb-commits] [lldb] r119890 - /lldb/trunk/source/Symbol/ClangASTContext.cpp Message-ID: <20101120022349.9B2D82A6C12C@llvm.org> Author: spyffe Date: Fri Nov 19 20:23:49 2010 New Revision: 119890 URL: http://llvm.org/viewvc/llvm-project?rev=119890&view=rev Log: Removed a stray dump() that made it into top-of-tree. Modified: lldb/trunk/source/Symbol/ClangASTContext.cpp Modified: lldb/trunk/source/Symbol/ClangASTContext.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Symbol/ClangASTContext.cpp?rev=119890&r1=119889&r2=119890&view=diff ============================================================================== --- lldb/trunk/source/Symbol/ClangASTContext.cpp (original) +++ lldb/trunk/source/Symbol/ClangASTContext.cpp Fri Nov 19 20:23:49 2010 @@ -1097,8 +1097,6 @@ QualType method_qual_type (QualType::getFromOpaquePtr (method_opaque_type)); - method_qual_type.dump(); - CXXMethodDecl *cxx_method_decl = NULL; DeclarationName decl_name (&identifier_table->get(name)); From gclayton at apple.com Sat Nov 20 13:16:50 2010 From: gclayton at apple.com (Greg Clayton) Date: Sat, 20 Nov 2010 19:16:50 -0000 Subject: [Lldb-commits] [lldb] r119910 - /lldb/trunk/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp Message-ID: <20101120191650.6CD312A6C12C@llvm.org> Author: gclayton Date: Sat Nov 20 13:16:50 2010 New Revision: 119910 URL: http://llvm.org/viewvc/llvm-project?rev=119910&view=rev Log: When we resolve a forward declaration type, be sure to put it into the m_die_to_type map so we don't assert later when someone tries to resolve the type. Modified: lldb/trunk/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp Modified: lldb/trunk/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp?rev=119910&r1=119909&r2=119910&view=diff ============================================================================== --- lldb/trunk/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp (original) +++ lldb/trunk/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp Sat Nov 20 13:16:50 2010 @@ -3035,7 +3035,13 @@ type_sp = m_debug_map_symfile->FindDefinitionTypeForDIE (dwarf_cu, die, type_name_const_str); } if (type_sp) + { + // We found a real definition for this type elsewhere + // so lets use it and cache the fact that we found + // a complete type for this die + m_die_to_type[die] = type_sp.get(); return type_sp; + } } assert (tag_decl_kind != -1); bool clang_type_was_created = false;