[Lldb-commits] [lldb] r143520 - in /lldb/trunk: include/lldb/Expression/IRForTarget.h source/Expression/IRForTarget.cpp test/lang/objc/objc-class-method/ test/lang/objc/objc-class-method/Makefile test/lang/objc/objc-class-method/TestObjCClassMethod.py test/lang/objc/objc-class-method/class.m

Sean Callanan scallanan at apple.com
Tue Nov 1 16:38:03 PDT 2011


Author: spyffe
Date: Tue Nov  1 18:38:03 2011
New Revision: 143520

URL: http://llvm.org/viewvc/llvm-project?rev=143520&view=rev
Log:
Added functionality to call Objective-C class methods
correctly, and added a testcase to check that it works.

The main problem here is that Objective-C class method
selectors are external references stored in a special
data structure in the LLVM IR module for an expression.
I just had to extract them and ensure that the real
class object locations were properly resolved.

Added:
    lldb/trunk/test/lang/objc/objc-class-method/
    lldb/trunk/test/lang/objc/objc-class-method/Makefile
    lldb/trunk/test/lang/objc/objc-class-method/TestObjCClassMethod.py
    lldb/trunk/test/lang/objc/objc-class-method/class.m
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=143520&r1=143519&r2=143520&view=diff
==============================================================================
--- lldb/trunk/include/lldb/Expression/IRForTarget.h (original)
+++ lldb/trunk/include/lldb/Expression/IRForTarget.h Tue Nov  1 18:38:03 2011
@@ -488,6 +488,19 @@
     //------------------------------------------------------------------
     bool
     HandleSymbol (llvm::Value *symbol);
+    
+    //------------------------------------------------------------------
+    /// Handle a single externally-defined Objective-C class
+    ///
+    /// @param[in] classlist_reference
+    ///     The reference, usually "01L_OBJC_CLASSLIST_REFERENCES_$_n"
+    ///     where n (if present) is an index.
+    ///
+    /// @return
+    ///     True on success; false otherwise
+    //------------------------------------------------------------------
+    bool
+    HandleObjCClass(llvm::Value *classlist_reference);
 
     //------------------------------------------------------------------
     /// Handle all the arguments to a function call

Modified: lldb/trunk/source/Expression/IRForTarget.cpp
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Expression/IRForTarget.cpp?rev=143520&r1=143519&r2=143520&view=diff
==============================================================================
--- lldb/trunk/source/Expression/IRForTarget.cpp (original)
+++ lldb/trunk/source/Expression/IRForTarget.cpp Tue Nov  1 18:38:03 2011
@@ -1704,6 +1704,63 @@
 }
 
 bool
+IRForTarget::HandleObjCClass(Value *classlist_reference)
+{
+    lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
+
+    GlobalVariable *global_variable = dyn_cast<GlobalVariable>(classlist_reference);
+    
+    if (!global_variable)
+        return false;
+    
+    Constant *initializer = global_variable->getInitializer();
+    
+    if (!initializer)
+        return false;
+    
+    if (!initializer->hasName())
+        return false;
+    
+    StringRef name(initializer->getName());
+    lldb_private::ConstString name_cstr(name.str().c_str());
+    lldb::addr_t class_ptr = m_decl_map->GetSymbolAddress(name_cstr);
+    
+    if (log)
+        log->Printf("Found reference to Objective-C class %s (0x%llx)", name_cstr.AsCString(), (unsigned long long)class_ptr);
+    
+    if (class_ptr == LLDB_INVALID_ADDRESS)
+        return false;
+    
+    if (global_variable->use_begin() == global_variable->use_end())
+        return false;
+    
+    LoadInst *load_instruction = NULL;
+    
+    for (Value::use_iterator i = global_variable->use_begin(), e = global_variable->use_end();
+         i != e;
+         ++i)
+    {
+        if ((load_instruction = dyn_cast<LoadInst>(*i)))
+            break;
+    }
+    
+    if (!load_instruction)
+        return false;
+    
+    IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
+                                             (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
+    
+    Constant *class_addr = ConstantInt::get(intptr_ty, (uint64_t)class_ptr);
+    Constant *class_bitcast = ConstantExpr::getIntToPtr(class_addr, load_instruction->getType());
+    
+    load_instruction->replaceAllUsesWith(class_bitcast);
+    
+    load_instruction->eraseFromParent();
+    
+    return true;
+}
+
+bool
 IRForTarget::ResolveCalls(BasicBlock &basic_block)
 {        
     /////////////////////////////////////////////////////////////////////////
@@ -1742,7 +1799,9 @@
                         (*global).getName().str().c_str(),
                         DeclForGlobal(global));
     
-        if ((*global).getName().str().find("OBJC_IVAR") == 0)
+        std::string global_name = (*global).getName().str();
+        
+        if (global_name.find("OBJC_IVAR") == 0)
         {
             if (!HandleSymbol(global))
             {
@@ -1752,6 +1811,16 @@
                 return false;
             }
         }
+        else if (global_name.find("OBJC_CLASSLIST_REFERENCES_$") != global_name.npos)
+        {
+            if (!HandleObjCClass(global))
+            {
+                if (m_error_stream)
+                    m_error_stream->Printf("Error [IRForTarget]: Couldn't resolve the class for an Objective-C static method call\n");
+                
+                return false;
+            }
+        }
         else if (DeclForGlobal(global))
         {
             if (!MaybeHandleVariable (global))

Added: lldb/trunk/test/lang/objc/objc-class-method/Makefile
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/lang/objc/objc-class-method/Makefile?rev=143520&view=auto
==============================================================================
--- lldb/trunk/test/lang/objc/objc-class-method/Makefile (added)
+++ lldb/trunk/test/lang/objc/objc-class-method/Makefile Tue Nov  1 18:38:03 2011
@@ -0,0 +1,6 @@
+LEVEL = ../../../make
+
+OBJC_SOURCES := class.m
+LDFLAGS = $(CFLAGS) -lobjc -framework Foundation
+
+include $(LEVEL)/Makefile.rules

Added: lldb/trunk/test/lang/objc/objc-class-method/TestObjCClassMethod.py
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/lang/objc/objc-class-method/TestObjCClassMethod.py?rev=143520&view=auto
==============================================================================
--- lldb/trunk/test/lang/objc/objc-class-method/TestObjCClassMethod.py (added)
+++ lldb/trunk/test/lang/objc/objc-class-method/TestObjCClassMethod.py Tue Nov  1 18:38:03 2011
@@ -0,0 +1,69 @@
+"""Test calling functions in class methods."""
+
+import os, time
+import unittest2
+import lldb
+import lldbutil
+from lldbtest import *
+
+class TestObjCStaticMethod(TestBase):
+
+    mydir = os.path.join("lang", "objc", "objc-class-method")
+
+    @unittest2.skipUnless(sys.platform.startswith("darwin"), "requires Darwin")
+    @python_api_test
+
+    def test_with_dsym_and_python_api(self):
+        """Test calling functions in class methods."""
+        self.buildDsym()
+        self.objc_class_method()
+
+    @python_api_test
+    def test_with_dwarf_and_python_api(self):
+        """Test calling functions in class methods."""
+        self.buildDwarf()
+        self.objc_class_method()
+
+    def setUp(self):
+        # Call super's setUp().
+        TestBase.setUp(self)
+        # Find the line numbers to break inside main().
+        self.main_source = "class.m"
+        self.break_line = line_number(self.main_source, '// Set breakpoint here.')
+
+    #rdar://problem/9745789 "expression" can't call functions in class methods
+    def objc_class_method(self):
+        """Test calling class methods."""
+        exe = os.path.join(os.getcwd(), "a.out")
+
+        target = self.dbg.CreateTarget(exe)
+        self.assertTrue(target, VALID_TARGET)
+
+        bpt = target.BreakpointCreateByLocation(self.main_source, self.break_line)
+        self.assertTrue(bpt, VALID_BREAKPOINT)
+
+        # Now launch the process, and do not stop at entry point.
+        process = target.LaunchSimple (None, None, os.getcwd())
+
+        self.assertTrue(process, PROCESS_IS_VALID)
+
+        # The stop reason of the thread should be breakpoint.
+        thread_list = lldbutil.get_threads_stopped_at_breakpoint (process, bpt)
+
+        # Make sure we stopped at the first breakpoint.
+        self.assertTrue (len(thread_list) != 0, "No thread stopped at our breakpoint.")
+        self.assertTrue (len(thread_list) == 1, "More than one thread stopped at our breakpoint.")
+            
+        # Now make sure we can call a function in the class method we've stopped in.
+        frame = thread_list[0].GetFrameAtIndex(0)
+        self.assertTrue (frame, "Got a valid frame 0 frame.")
+
+        cmd_value = frame.EvaluateExpression ("(int)[Foo doSomethingWithString:@\"Hello\"]")
+        self.assertTrue (cmd_value.IsValid())
+	self.assertTrue (cmd_value.GetValueAsUnsigned() == 5)
+
+if __name__ == '__main__':
+    import atexit
+    lldb.SBDebugger.Initialize()
+    atexit.register(lambda: lldb.SBDebugger.Terminate())
+    unittest2.main()

Added: lldb/trunk/test/lang/objc/objc-class-method/class.m
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/lang/objc/objc-class-method/class.m?rev=143520&view=auto
==============================================================================
--- lldb/trunk/test/lang/objc/objc-class-method/class.m (added)
+++ lldb/trunk/test/lang/objc/objc-class-method/class.m Tue Nov  1 18:38:03 2011
@@ -0,0 +1,24 @@
+#import <Foundation/Foundation.h>
+
+ at interface Foo : NSObject
++(int) doSomethingWithString: (NSString *) string;
+-(int) doSomethingInstance: (NSString *) string;
+ at end
+
+ at implementation Foo
++(int) doSomethingWithString: (NSString *) string
+{
+  NSLog (@"String is: %@.", string);
+  return [string length];
+}
+
+-(int) doSomethingInstance: (NSString *)string
+{
+  return [Foo doSomethingWithString:string];
+}
+ at end
+
+int main()
+{
+  return 0; // Set breakpoint here.
+}





More information about the lldb-commits mailing list