From johnny.chen at apple.com Mon Oct 11 11:19:48 2010 From: johnny.chen at apple.com (Johnny Chen) Date: Mon, 11 Oct 2010 16:19:48 -0000 Subject: [Lldb-commits] [lldb] r116206 - /lldb/trunk/test/dotest.py Message-ID: <20101011161948.2F6B72A6C12E@llvm.org> Author: johnny Date: Mon Oct 11 11:19:48 2010 New Revision: 116206 URL: http://llvm.org/viewvc/llvm-project?rev=116206&view=rev Log: Help text modification. 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=116206&r1=116205&r2=116206&view=diff ============================================================================== --- lldb/trunk/test/dotest.py (original) +++ lldb/trunk/test/dotest.py Mon Oct 11 11:19:48 2010 @@ -87,7 +87,8 @@ -c : read a config file specified after this option (see also lldb-trunk/example/test/usage-config) -d : delay startup for 10 seconds (in order for the debugger to attach) --f : specify a filter to admit tests into the test suite +-f : specify a filter, which consists of the test class name, a dot, followed by + the test method, to admit tests into the test suite e.g., -f 'ClassTypesTestCase.test_with_dwarf_and_python_api' -g : if specified, only the modules with the corect filter will be run it has no effect if no '-f' option is present From johnny.chen at apple.com Mon Oct 11 17:25:46 2010 From: johnny.chen at apple.com (Johnny Chen) Date: Mon, 11 Oct 2010 22:25:46 -0000 Subject: [Lldb-commits] [lldb] r116255 - in /lldb/trunk/test: dotest.py lldbtest.py plugins/darwin.py types/Makefile Message-ID: <20101011222546.7466D2A6C12E@llvm.org> Author: johnny Date: Mon Oct 11 17:25:46 2010 New Revision: 116255 URL: http://llvm.org/viewvc/llvm-project?rev=116255&view=rev Log: Added the capability for the test driver to relocate the tests and the intermediate files to a different top level directory than those specified on the command line. When relocated, the test clanups normally performed afterwards after each test method and after each test class will not be exercised at all. This allows for an easier postmortem analysis of test failures. Example: ./dotest.py -v -t -r /tmp/lldbtest types will create a /tmp/lldbtest directory which houses the types directory and its supported files. Files modified: o dotest.py, lldbtest.py: Add logic to process '-r dir' option to support relocating the tests to a different top level directory instead of exected in place. o darwin.py, test/types/Makefile: The 'make clean' should only clean the minimum .o and .d files. Modified: lldb/trunk/test/dotest.py lldb/trunk/test/lldbtest.py lldb/trunk/test/plugins/darwin.py lldb/trunk/test/types/Makefile Modified: lldb/trunk/test/dotest.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/dotest.py?rev=116255&r1=116254&r2=116255&view=diff ============================================================================== --- lldb/trunk/test/dotest.py (original) +++ lldb/trunk/test/dotest.py Mon Oct 11 17:25:46 2010 @@ -63,12 +63,18 @@ # Ignore the build search path relative to this script to locate the lldb.py module. ignore = False -# By default, we skip long running test case. Use "-l" option to override. +# By default, we skip long running test case. Use '-l' option to override. skipLongRunningTest = True # The regular expression pattern to match against eligible filenames as our test cases. regexp = None +# By default, tests are executed in place and cleanups are performed afterwards. +# Use '-r dir' option to relocate the tests and their intermediate files to a +# different directory and to forgo any cleanups. The directory specified must +# not exist yet. +rdir = None + # Default verbosity is 0. verbose = 0 @@ -98,6 +104,9 @@ tree relative to this script; use PYTHONPATH to locate the module -l : don't skip long running test -p : specify a regexp filename pattern for inclusion in the test suite +-r : specify a dir to relocate the tests and their intermediate files to; + the directory must not exist before running this test driver; + no cleanup of intermediate test files is performed in this case -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 @@ -136,6 +145,7 @@ global ignore global skipLongRunningTest global regexp + global rdir global verbose global testdirs @@ -187,6 +197,16 @@ usage() regexp = sys.argv[index] index += 1 + elif sys.argv[index].startswith('-r'): + # Increment by 1 to fetch the relocated directory argument. + index += 1 + if index >= len(sys.argv) or sys.argv[index].startswith('-'): + usage() + rdir = os.path.abspath(sys.argv[index]) + if os.path.exists(rdir): + print "Relocated directory:", rdir, "must not exist!" + usage() + index += 1 elif sys.argv[index].startswith('-t'): os.environ["LLDB_COMMAND_TRACE"] = "YES" index += 1 @@ -204,6 +224,39 @@ if len(sys.argv) > index: testdirs = map(os.path.abspath, sys.argv[index:]) + # If '-r dir' is specified, the tests should be run under the relocated + # directory. Let's copy the testdirs over. + if rdir: + from shutil import copytree, ignore_patterns + + tmpdirs = [] + for srcdir in testdirs: + dstdir = os.path.join(rdir, os.path.basename(srcdir)) + # Don't copy the *.pyc and .svn stuffs. + copytree(srcdir, dstdir, ignore=ignore_patterns('*.pyc', '.svn')) + tmpdirs.append(dstdir) + + # This will be our modified testdirs. + testdirs = tmpdirs + + # With '-r dir' specified, there's no cleanup of intermediate test files. + os.environ["LLDB_DO_CLEANUP"] = 'NO' + + # If testdirs is ['test'], the make directory has already been copied + # recursively and is contained within the rdir/test dir. For anything + # else, we would need to copy over the make directory and its contents, + # so that, os.listdir(rdir) looks like, for example: + # + # array_types conditional_break make + # + # where the make directory contains the Makefile.rules file. + if len(testdirs) != 1 or os.path.basename(testdirs[0]) != 'test': + # Don't copy the .svn stuffs. + copytree('make', os.path.join(rdir, 'make'), + ignore=ignore_patterns('.svn')) + + #print "testdirs:", testdirs + # Source the configFile if specified. # The side effect, if any, will be felt from this point on. An example # config file may be these simple two lines: @@ -227,13 +280,26 @@ def setupSysPath(): """Add LLDB.framework/Resources/Python to the search paths for modules.""" + global rdir + global testdirs + # Get the directory containing the current script. scriptPath = sys.path[0] if not scriptPath.endswith('test'): print "This script expects to reside in lldb's test directory." sys.exit(-1) - os.environ["LLDB_TEST"] = scriptPath + if rdir: + # Set up the LLDB_TEST environment variable appropriately, so that the + # individual tests can be located relatively. + # + # See also lldbtest.TestBase.setUpClass(cls). + if len(testdirs) == 1 and os.path.basename(testdirs[0]) == 'test': + os.environ["LLDB_TEST"] = os.path.join(rdir, 'test') + else: + os.environ["LLDB_TEST"] = rdir + else: + os.environ["LLDB_TEST"] = scriptPath pluginPath = os.path.join(scriptPath, 'plugins') # Append script dir and plugin dir to the sys.path. @@ -316,7 +382,7 @@ # We found a match for our test case. Add it to the suite. if not sys.path.count(dir): - sys.path.append(dir) + sys.path.insert(0, dir) base = os.path.splitext(name)[0] # Thoroughly check the filterspec against the base module and admit Modified: lldb/trunk/test/lldbtest.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/lldbtest.py?rev=116255&r1=116254&r2=116255&view=diff ============================================================================== --- lldb/trunk/test/lldbtest.py (original) +++ lldb/trunk/test/lldbtest.py Mon Oct 11 17:25:46 2010 @@ -104,11 +104,21 @@ import unittest2 import lldb +# See also dotest.parseOptionsAndInitTestdirs(), where the environment variables +# LLDB_COMMAND_TRACE and LLDB_NO_CLEANUP are set from '-t' and '-r dir' options. + +# By default, traceAlways is False. if "LLDB_COMMAND_TRACE" in os.environ and os.environ["LLDB_COMMAND_TRACE"]=="YES": traceAlways = True else: traceAlways = False +# By default, doCleanup is True. +if "LLDB_DO_CLEANUP" in os.environ and os.environ["LLDB_DO_CLEANUP"]=="NO": + doCleanup = False +else: + doCleanup = True + # # Some commonly used assert messages. @@ -284,20 +294,21 @@ Do class-wide cleanup. """ - # First, let's do the platform-specific cleanup. - module = __import__(sys.platform) - if not module.cleanup(): - raise Exception("Don't know how to do cleanup") + if doCleanup: + # First, let's do the platform-specific cleanup. + module = __import__(sys.platform) + if not module.cleanup(): + raise Exception("Don't know how to do cleanup") - # Subclass might have specific cleanup function defined. - if getattr(cls, "classCleanup", None): - if traceAlways: - print >> sys.stderr, "Call class-specific cleanup function for class:", cls - try: - cls.classCleanup() - except: - exc_type, exc_value, exc_tb = sys.exc_info() - traceback.print_exception(exc_type, exc_value, exc_tb) + # Subclass might have specific cleanup function defined. + if getattr(cls, "classCleanup", None): + if traceAlways: + print >> sys.stderr, "Call class-specific cleanup function for class:", cls + try: + cls.classCleanup() + except: + exc_type, exc_value, exc_tb = sys.exc_info() + traceback.print_exception(exc_type, exc_value, exc_tb) # Restore old working directory. if traceAlways: @@ -366,7 +377,7 @@ del self.dbg # Perform registered teardown cleanup. - if self.doTearDownCleanup: + if doCleanup and self.doTearDownCleanup: module = __import__(sys.platform) if not module.cleanup(dictionary=self.dict): raise Exception("Don't know how to do cleanup") Modified: lldb/trunk/test/plugins/darwin.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/plugins/darwin.py?rev=116255&r1=116254&r2=116255&view=diff ============================================================================== --- lldb/trunk/test/plugins/darwin.py (original) +++ lldb/trunk/test/plugins/darwin.py Mon Oct 11 17:25:46 2010 @@ -60,7 +60,7 @@ def buildDefault(architecture=None, compiler=None, dictionary=None): """Build the binaries the default way.""" lldbtest.system(["/bin/sh", "-c", - "make clean; make" + "make clean" + getCmdLine(dictionary) + "; make" + getArchSpec(architecture) + getCCSpec(compiler) + getCmdLine(dictionary)]) @@ -70,7 +70,8 @@ def buildDsym(architecture=None, compiler=None, dictionary=None): """Build the binaries with dsym debug info.""" lldbtest.system(["/bin/sh", "-c", - "make clean; make MAKE_DSYM=YES" + "make clean" + getCmdLine(dictionary) + + "; make MAKE_DSYM=YES" + getArchSpec(architecture) + getCCSpec(compiler) + getCmdLine(dictionary)]) @@ -80,7 +81,8 @@ def buildDwarf(architecture=None, compiler=None, dictionary=None): """Build the binaries with dwarf debug info.""" lldbtest.system(["/bin/sh", "-c", - "make clean; make MAKE_DSYM=NO" + "make clean" + getCmdLine(dictionary) + + "; make MAKE_DSYM=NO" + getArchSpec(architecture) + getCCSpec(compiler) + getCmdLine(dictionary)]) Modified: lldb/trunk/test/types/Makefile URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/types/Makefile?rev=116255&r1=116254&r2=116255&view=diff ============================================================================== --- lldb/trunk/test/types/Makefile (original) +++ lldb/trunk/test/types/Makefile Mon Oct 11 17:25:46 2010 @@ -1,9 +1,5 @@ LEVEL = ../make -CXX_SOURCES := int.cpp +#CXX_SOURCES := int.cpp include $(LEVEL)/Makefile.rules - -clean:: - rm -rf *.o *.d - From johnny.chen at apple.com Mon Oct 11 18:52:19 2010 From: johnny.chen at apple.com (Johnny Chen) Date: Mon, 11 Oct 2010 23:52:19 -0000 Subject: [Lldb-commits] [lldb] r116270 - in /lldb/trunk/test: array_types/TestArrayTypes.py array_types/main.c lldbtest.py Message-ID: <20101011235219.5F7012A6C12E@llvm.org> Author: johnny Date: Mon Oct 11 18:52:19 2010 New Revision: 116270 URL: http://llvm.org/viewvc/llvm-project?rev=116270&view=rev Log: Add a utility function to lldbtest.py to return the line number of a matched string within a file. This is to be used within the test case to avoid hardcoded line number. array_types/TestArrayTypes.py is modified first to use this pattern. Other test modules to follow. rdar://problem/8537816 Testsuite: don't set breakpoints by exact file & line number Modified: lldb/trunk/test/array_types/TestArrayTypes.py lldb/trunk/test/array_types/main.c lldb/trunk/test/lldbtest.py Modified: lldb/trunk/test/array_types/TestArrayTypes.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/array_types/TestArrayTypes.py?rev=116270&r1=116269&r2=116270&view=diff ============================================================================== --- lldb/trunk/test/array_types/TestArrayTypes.py (original) +++ lldb/trunk/test/array_types/TestArrayTypes.py Mon Oct 11 18:52:19 2010 @@ -31,14 +31,20 @@ self.buildDwarf() self.array_types_python() + def setUp(self): + super(ArrayTypesTestCase, self).setUp() + # Find the line number to break inside main(). + self.line = line_number('main.c', '// Set break point at this line.') + def array_types(self): """Test 'frame variable var_name' on some variables with array types.""" exe = os.path.join(os.getcwd(), "a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) - # Break on line 42 inside main(). - self.expect("breakpoint set -f main.c -l 42", BREAKPOINT_CREATED, - startstr = "Breakpoint created: 1: file ='main.c', line = 42, locations = 1") + self.expect("breakpoint set -f main.c -l %d" % self.line, + BREAKPOINT_CREATED, + startstr = "Breakpoint created: 1: file ='main.c', line = %d, locations = 1" % + self.line) self.runCmd("run", RUN_SUCCEEDED) @@ -88,14 +94,14 @@ target = self.dbg.CreateTarget(exe) self.assertTrue(target.IsValid(), VALID_TARGET) - breakpoint = target.BreakpointCreateByLocation("main.c", 42) + breakpoint = target.BreakpointCreateByLocation("main.c", self.line) self.assertTrue(breakpoint.IsValid(), VALID_BREAKPOINT) # Sanity check the print representation of breakpoint. bp = repr(breakpoint) self.expect(bp, msg="Breakpoint looks good", exe=False, substrs = ["file ='main.c'", - "line = 42", + "line = %d" % self.line, "locations = 1"]) self.expect(bp, msg="Breakpoint is not resolved as yet", exe=False, matching=False, substrs = ["resolved = 1"]) @@ -129,7 +135,7 @@ bp = repr(breakpoint) self.expect(bp, "Breakpoint looks good and is resolved", exe=False, substrs = ["file ='main.c'", - "line = 42", + "line = %d" % self.line, "locations = 1"]) # Sanity check the print representation of frame. Modified: lldb/trunk/test/array_types/main.c URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/array_types/main.c?rev=116270&r1=116269&r2=116270&view=diff ============================================================================== --- lldb/trunk/test/array_types/main.c (original) +++ lldb/trunk/test/array_types/main.c Mon Oct 11 18:52:19 2010 @@ -39,7 +39,7 @@ {1,2}, {3,4} }; - struct point_tag points_2_4_matrix[2][4] = { + struct point_tag points_2_4_matrix[2][4] = { // Set break point at this line. {{ 1, 2}, { 3, 4}, { 5, 6}, { 7, 8}}, {{11,22}, {33,44}, {55,66}, {77,88}} }; Modified: lldb/trunk/test/lldbtest.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/lldbtest.py?rev=116270&r1=116269&r2=116270&view=diff ============================================================================== --- lldb/trunk/test/lldbtest.py (original) +++ lldb/trunk/test/lldbtest.py Mon Oct 11 18:52:19 2010 @@ -226,6 +226,15 @@ raise CalledProcessError(retcode, cmd) return output +def line_number(filename, string_to_match): + """Helper function to return the line number of the first matched string.""" + with open(filename, 'r') as f: + for i, line in enumerate(f): + if line.find(string_to_match) != -1: + # Found our match. + return i + return -1 + def pointer_size(): """Return the pointer size of the host system.""" import ctypes From jingham at apple.com Mon Oct 11 18:53:15 2010 From: jingham at apple.com (Jim Ingham) Date: Mon, 11 Oct 2010 23:53:15 -0000 Subject: [Lldb-commits] [lldb] r116271 - in /lldb/trunk: include/lldb/Core/Broadcaster.h include/lldb/Target/Process.h lldb.xcodeproj/project.pbxproj source/Core/Broadcaster.cpp source/Expression/ClangFunction.cpp source/Target/Process.cpp Message-ID: <20101011235315.2C2BF2A6C12E@llvm.org> Author: jingham Date: Mon Oct 11 18:53:14 2010 New Revision: 116271 URL: http://llvm.org/viewvc/llvm-project?rev=116271&view=rev Log: Add a way to temporarily divert events from a broadcaster to a private listener. Modified: lldb/trunk/include/lldb/Core/Broadcaster.h lldb/trunk/include/lldb/Target/Process.h lldb/trunk/lldb.xcodeproj/project.pbxproj lldb/trunk/source/Core/Broadcaster.cpp lldb/trunk/source/Expression/ClangFunction.cpp lldb/trunk/source/Target/Process.cpp Modified: lldb/trunk/include/lldb/Core/Broadcaster.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/Core/Broadcaster.h?rev=116271&r1=116270&r2=116271&view=diff ============================================================================== --- lldb/trunk/include/lldb/Core/Broadcaster.h (original) +++ lldb/trunk/include/lldb/Core/Broadcaster.h Mon Oct 11 18:53:14 2010 @@ -165,10 +165,41 @@ //------------------------------------------------------------------ bool RemoveListener (Listener* listener, uint32_t event_mask = UINT32_MAX); - - + protected: + + //------------------------------------------------------------------ + /// Provides a simple mechanism to temporarily redirect events from + /// broadcaster. When you call this function passing in a listener and + /// event type mask, all events from the broadcaster matching the mask + /// will now go to the hijacking listener. + /// Only one hijack can occur at a time. If we need more than this we + /// will have to implement a Listener stack. + /// + /// @param[in] listener + /// A Listener object. You do not need to call StartListeningForEvents + /// for this broadcaster (that would fail anyway since the event bits + /// would most likely be taken by the listener(s) you are usurping. + /// + /// @param[in] event_mask + /// The event bits \a listener wishes to hijack. + /// + /// @return + /// \b True if the event mask could be hijacked, \b false otherwise. + /// + /// @see uint32_t Broadcaster::AddListener (Listener*, uint32_t) + //------------------------------------------------------------------ + bool + HijackBroadcaster (Listener *listener, uint32_t event_mask = UINT32_MAX); + + //------------------------------------------------------------------ + /// Restore the state of the Broadcaster from a previous hijack attempt. + /// + //------------------------------------------------------------------ + void + RestoreBroadcaster (); + void PrivateBroadcastEvent (lldb::EventSP &event_sp, bool unique); @@ -181,7 +212,9 @@ const ConstString m_broadcaster_name; ///< The name of this broadcaster object. collection m_broadcaster_listeners; ///< A list of Listener / event_mask pairs that are listening to this broadcaster. Mutex m_broadcaster_listeners_mutex; ///< A mutex that protects \a m_broadcaster_listeners. - + Listener *m_hijacking_listener; // A simple mechanism to intercept events in lieu of a real Listener collection stack. + uint32_t m_hijack_mask; + private: //------------------------------------------------------------------ // For Broadcaster only Modified: lldb/trunk/include/lldb/Target/Process.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/Target/Process.h?rev=116271&r1=116270&r2=116271&view=diff ============================================================================== --- lldb/trunk/include/lldb/Target/Process.h (original) +++ lldb/trunk/include/lldb/Target/Process.h Mon Oct 11 18:53:14 2010 @@ -1512,7 +1512,33 @@ Event * PeekAtStateChangedEvents (); + + + //------------------------------------------------------------------ + /// If you need to ensure that you and only you will hear about some public + /// event, then make a new listener, set to listen to process events, and + /// then call this with that listener. Then you will have to wait on that + /// listener explicitly for events (rather than using the GetNextEvent & WaitFor* + /// calls above. Be sure to call RestoreProcessEvents when you are done. + /// + /// @param[in] listener + /// This is the new listener to whom all process events will be delivered. + /// + /// @return + /// Returns \b true if the new listener could be installed, + /// \b false otherwise. + //------------------------------------------------------------------ + bool + HijackProcessEvents (Listener *listener); + + //------------------------------------------------------------------ + /// Restores the process event broadcasting to its normal state. + /// + //------------------------------------------------------------------ + void + RestoreProcessEvents (); +protected: //------------------------------------------------------------------ /// This is the part of the event handling that for a process event. /// It decides what to do with the event and returns true if the @@ -1530,6 +1556,7 @@ bool ShouldBroadcastEvent (Event *event_ptr); +public: //------------------------------------------------------------------ /// Gets the byte order for this process. /// Modified: lldb/trunk/lldb.xcodeproj/project.pbxproj URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/lldb.xcodeproj/project.pbxproj?rev=116271&r1=116270&r2=116271&view=diff ============================================================================== --- lldb/trunk/lldb.xcodeproj/project.pbxproj (original) +++ lldb/trunk/lldb.xcodeproj/project.pbxproj Mon Oct 11 18:53:14 2010 @@ -2438,7 +2438,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/Core/Broadcaster.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Core/Broadcaster.cpp?rev=116271&r1=116270&r2=116271&view=diff ============================================================================== --- lldb/trunk/source/Core/Broadcaster.cpp (original) +++ lldb/trunk/source/Core/Broadcaster.cpp Mon Oct 11 18:53:14 2010 @@ -24,7 +24,9 @@ Broadcaster::Broadcaster (const char *name) : m_broadcaster_name (name), m_broadcaster_listeners (), - m_broadcaster_listeners_mutex (Mutex::eMutexTypeRecursive) + m_broadcaster_listeners_mutex (Mutex::eMutexTypeRecursive), + m_hijacking_listener(NULL), + m_hijack_mask(UINT32_MAX) { Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT); if (log) @@ -116,6 +118,10 @@ Broadcaster::EventTypeHasListeners (uint32_t event_type) { Mutex::Locker locker (m_broadcaster_listeners_mutex); + + if (m_hijacking_listener != NULL && event_type & m_hijack_mask) + return true; + if (m_broadcaster_listeners.empty()) return false; @@ -185,20 +191,29 @@ unique); } - Mutex::Locker event_types_locker(m_broadcaster_listeners_mutex); - collection::iterator pos, end = m_broadcaster_listeners.end(); + if (m_hijacking_listener != NULL && m_hijack_mask & event_type) + { + if (unique && m_hijacking_listener->PeekAtNextEventForBroadcasterWithType (this, event_type)) + return; + m_hijacking_listener->AddEvent (event_sp); + } + else + { + Mutex::Locker event_types_locker(m_broadcaster_listeners_mutex); + collection::iterator pos, end = m_broadcaster_listeners.end(); - // Iterate through all listener/mask pairs - for (pos = m_broadcaster_listeners.begin(); pos != end; ++pos) - { - // If the listener's mask matches any bits that we just set, then - // put the new event on its event queue. - if (event_type & pos->second) + // Iterate through all listener/mask pairs + for (pos = m_broadcaster_listeners.begin(); pos != end; ++pos) { - if (unique && pos->first->PeekAtNextEventForBroadcasterWithType (this, event_type)) - continue; - pos->first->AddEvent (event_sp); + // If the listener's mask matches any bits that we just set, then + // put the new event on its event queue. + if (event_type & pos->second) + { + if (unique && pos->first->PeekAtNextEventForBroadcasterWithType (this, event_type)) + continue; + pos->first->AddEvent (event_sp); + } } } } @@ -217,3 +232,24 @@ PrivateBroadcastEvent (event_sp, true); } +bool +Broadcaster::HijackBroadcaster (Listener *listener, uint32_t event_mask) +{ + Mutex::Locker event_types_locker(m_broadcaster_listeners_mutex); + + if (m_hijacking_listener != NULL) + return false; + + m_hijacking_listener = listener; + m_hijack_mask = event_mask; + return true; +} + +void +Broadcaster::RestoreBroadcaster () +{ + Mutex::Locker event_types_locker(m_broadcaster_listeners_mutex); + + m_hijacking_listener = NULL; +} + Modified: lldb/trunk/source/Expression/ClangFunction.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Expression/ClangFunction.cpp?rev=116271&r1=116270&r2=116271&view=diff ============================================================================== --- lldb/trunk/source/Expression/ClangFunction.cpp (original) +++ lldb/trunk/source/Expression/ClangFunction.cpp Mon Oct 11 18:53:14 2010 @@ -513,6 +513,9 @@ 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()) { @@ -525,11 +528,11 @@ while (1) { lldb::EventSP event_sp; - + lldb::StateType stop_state = lldb::eStateInvalid; // Now wait for the process to stop again: - lldb::StateType stop_state = exe_ctx.process->WaitForStateChangedEvents (timeout_ptr, event_sp); + bool got_event = listener.WaitForEvent (timeout_ptr, event_sp); - if (stop_state == lldb::eStateInvalid && timeout_ptr != NULL) + if (!got_event) { // Right now this is the only way to tell we've timed out... // We should interrupt the process here... @@ -544,7 +547,9 @@ { timeout_ptr = NULL; - stop_state = exe_ctx.process->WaitForStateChangedEvents (timeout_ptr, event_sp); + 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."); @@ -572,9 +577,15 @@ continue; } else + { + exe_ctx.process->RestoreProcessEvents (); return eExecutionInterrupted; + } } } + + stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get()); + if (stop_state == lldb::eStateRunning || stop_state == lldb::eStateStepping) continue; @@ -664,6 +675,9 @@ } } + if (exe_ctx.process) + exe_ctx.process->RestoreProcessEvents (); + // Thread we ran the function in may have gone away because we ran the target // Check that it's still there. exe_ctx.thread = exe_ctx.process->GetThreadList().FindThreadByIndexID(tid, true).get(); Modified: lldb/trunk/source/Target/Process.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Target/Process.cpp?rev=116271&r1=116270&r2=116271&view=diff ============================================================================== --- lldb/trunk/source/Target/Process.cpp (original) +++ lldb/trunk/source/Target/Process.cpp Mon Oct 11 18:53:14 2010 @@ -217,6 +217,23 @@ return state; } +bool +Process::HijackProcessEvents (Listener *listener) +{ + if (listener != NULL) + { + return HijackBroadcaster(listener, eBroadcastBitStateChanged); + } + else + return false; +} + +void +Process::RestoreProcessEvents () +{ + RestoreBroadcaster(); +} + StateType Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp) { From johnny.chen at apple.com Mon Oct 11 19:09:25 2010 From: johnny.chen at apple.com (Johnny Chen) Date: Tue, 12 Oct 2010 00:09:25 -0000 Subject: [Lldb-commits] [lldb] r116275 - in /lldb/trunk/test: bitfields/TestBitfields.py bitfields/main.c lldbtest.py Message-ID: <20101012000926.0A9E82A6C12E@llvm.org> Author: johnny Date: Mon Oct 11 19:09:25 2010 New Revision: 116275 URL: http://llvm.org/viewvc/llvm-project?rev=116275&view=rev Log: Avoid using hardcoded line number to break on. Use the line_number() utility function to get the line number to break on during setUp(). Modified: lldb/trunk/test/bitfields/TestBitfields.py lldb/trunk/test/bitfields/main.c lldb/trunk/test/lldbtest.py Modified: lldb/trunk/test/bitfields/TestBitfields.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/bitfields/TestBitfields.py?rev=116275&r1=116274&r2=116275&view=diff ============================================================================== --- lldb/trunk/test/bitfields/TestBitfields.py (original) +++ lldb/trunk/test/bitfields/TestBitfields.py Mon Oct 11 19:09:25 2010 @@ -31,14 +31,21 @@ self.buildDwarf() self.bitfields_variable_python() + def setUp(self): + super(BitfieldsTestCase, self).setUp() + # Find the line number to break inside main(). + self.line = line_number('main.c', '// Set break point at this line.') + def bitfields_variable(self): """Test 'frame variable ...' on a variable with bitfields.""" exe = os.path.join(os.getcwd(), "a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Break inside the main. - self.expect("breakpoint set -f main.c -l 42", BREAKPOINT_CREATED, - startstr = "Breakpoint created: 1: file ='main.c', line = 42, locations = 1") + self.expect("breakpoint set -f main.c -l %d" % self.line, + BREAKPOINT_CREATED, + startstr = "Breakpoint created: 1: file ='main.c', line = %d, locations = 1" % + self.line) self.runCmd("run", RUN_SUCCEEDED) @@ -81,7 +88,7 @@ target = self.dbg.CreateTarget(exe) self.assertTrue(target.IsValid(), VALID_TARGET) - breakpoint = target.BreakpointCreateByLocation("main.c", 42) + breakpoint = target.BreakpointCreateByLocation("main.c", self.line) self.assertTrue(breakpoint.IsValid(), VALID_BREAKPOINT) self.runCmd("run", RUN_SUCCEEDED, setCookie=False) Modified: lldb/trunk/test/bitfields/main.c URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/bitfields/main.c?rev=116275&r1=116274&r2=116275&view=diff ============================================================================== --- lldb/trunk/test/bitfields/main.c (original) +++ lldb/trunk/test/bitfields/main.c Mon Oct 11 19:09:25 2010 @@ -39,6 +39,6 @@ bits.b7 = i; //// break $source:$line for (i=0; i<(1<<4); i++) bits.four = i; //// break $source:$line - return 0; //// continue + return 0; //// Set break point at this line. } Modified: lldb/trunk/test/lldbtest.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/lldbtest.py?rev=116275&r1=116274&r2=116275&view=diff ============================================================================== --- lldb/trunk/test/lldbtest.py (original) +++ lldb/trunk/test/lldbtest.py Mon Oct 11 19:09:25 2010 @@ -232,7 +232,7 @@ for i, line in enumerate(f): if line.find(string_to_match) != -1: # Found our match. - return i + return i+1 return -1 def pointer_size(): From gclayton at apple.com Mon Oct 11 21:24:53 2010 From: gclayton at apple.com (Greg Clayton) Date: Tue, 12 Oct 2010 02:24:53 -0000 Subject: [Lldb-commits] [lldb] r116290 - in /lldb/trunk: lldb.xcodeproj/project.pbxproj source/Plugins/ObjectFile/ELF/ObjectFileELF.cpp source/Plugins/SymbolFile/DWARF/DWARFCompileUnit.cpp source/Plugins/SymbolFile/DWARF/DWARFCompileUnit.h source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.h source/Plugins/SymbolFile/DWARF/SymbolFileDWARFDebugMap.cpp source/Plugins/SymbolFile/DWARF/SymbolFileDWARFDebugMap.h source/Symbol/ClangASTContext.cpp source/Symbol/SymbolVendor.cpp Message-ID: <20101012022453.5E0342A6C12E@llvm.org> Author: gclayton Date: Mon Oct 11 21:24:53 2010 New Revision: 116290 URL: http://llvm.org/viewvc/llvm-project?rev=116290&view=rev Log: Fixed the Objective C method prototypes to be correct (the selectors weren't being chopped up correctly). The DWARF plug-in also keeps a map of the ObjC class names to selectors for easy parsing of all class selectors when we parse the class type. Modified: lldb/trunk/lldb.xcodeproj/project.pbxproj lldb/trunk/source/Plugins/ObjectFile/ELF/ObjectFileELF.cpp lldb/trunk/source/Plugins/SymbolFile/DWARF/DWARFCompileUnit.cpp lldb/trunk/source/Plugins/SymbolFile/DWARF/DWARFCompileUnit.h lldb/trunk/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp lldb/trunk/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.h lldb/trunk/source/Plugins/SymbolFile/DWARF/SymbolFileDWARFDebugMap.cpp lldb/trunk/source/Plugins/SymbolFile/DWARF/SymbolFileDWARFDebugMap.h lldb/trunk/source/Symbol/ClangASTContext.cpp lldb/trunk/source/Symbol/SymbolVendor.cpp Modified: lldb/trunk/lldb.xcodeproj/project.pbxproj URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/lldb.xcodeproj/project.pbxproj?rev=116290&r1=116289&r2=116290&view=diff ============================================================================== --- lldb/trunk/lldb.xcodeproj/project.pbxproj (original) +++ lldb/trunk/lldb.xcodeproj/project.pbxproj Mon Oct 11 21:24:53 2010 @@ -2438,6 +2438,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/Plugins/ObjectFile/ELF/ObjectFileELF.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Plugins/ObjectFile/ELF/ObjectFileELF.cpp?rev=116290&r1=116289&r2=116290&view=diff ============================================================================== --- lldb/trunk/source/Plugins/ObjectFile/ELF/ObjectFileELF.cpp (original) +++ lldb/trunk/source/Plugins/ObjectFile/ELF/ObjectFileELF.cpp Mon Oct 11 21:24:53 2010 @@ -225,13 +225,13 @@ // Locate the dynamic table. user_id_t dynsym_id = 0; user_id_t dynstr_id = 0; - for (SectionHeaderCollIter I = m_section_headers.begin(); - I != m_section_headers.end(); ++I) + for (SectionHeaderCollIter sh_pos = m_section_headers.begin(); + sh_pos != m_section_headers.end(); ++sh_pos) { - if (I->sh_type == SHT_DYNAMIC) + if (sh_pos->sh_type == SHT_DYNAMIC) { - dynsym_id = SectionIndex(I); - dynstr_id = I->sh_link + 1; // Section ID's are 1 based. + dynsym_id = SectionIndex(sh_pos); + dynstr_id = sh_pos->sh_link + 1; // Section ID's are 1 based. break; } } Modified: lldb/trunk/source/Plugins/SymbolFile/DWARF/DWARFCompileUnit.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Plugins/SymbolFile/DWARF/DWARFCompileUnit.cpp?rev=116290&r1=116289&r2=116290&view=diff ============================================================================== --- lldb/trunk/source/Plugins/SymbolFile/DWARF/DWARFCompileUnit.cpp (original) +++ lldb/trunk/source/Plugins/SymbolFile/DWARF/DWARFCompileUnit.cpp Mon Oct 11 21:24:53 2010 @@ -568,6 +568,7 @@ NameToDIE& full_name_to_function_die, NameToDIE& method_name_to_function_die, NameToDIE& selector_name_to_function_die, + NameToDIE& objc_class_selector_dies, NameToDIE& name_to_global_die, NameToDIE& name_to_type_die, const DWARFDebugRanges *debug_ranges, @@ -786,6 +787,12 @@ const char *method_name = strchr (name, ' '); if (method_name) { + ConstString class_name (name + 2, method_name - name - 2); + + // Keep a map of the objective C class name to all selector + // DIEs + objc_class_selector_dies.Insert(class_name, die_info); + // Skip the space ++method_name; // Extract the objective C basename and add it to the Modified: lldb/trunk/source/Plugins/SymbolFile/DWARF/DWARFCompileUnit.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Plugins/SymbolFile/DWARF/DWARFCompileUnit.h?rev=116290&r1=116289&r2=116290&view=diff ============================================================================== --- lldb/trunk/source/Plugins/SymbolFile/DWARF/DWARFCompileUnit.h (original) +++ lldb/trunk/source/Plugins/SymbolFile/DWARF/DWARFCompileUnit.h Mon Oct 11 21:24:53 2010 @@ -138,6 +138,7 @@ NameToDIE& full_name_to_function_die, NameToDIE& method_name_to_function_die, NameToDIE& selector_name_to_function_die, + NameToDIE& objc_class_selector_dies, NameToDIE& name_to_global_die, NameToDIE& name_to_type_die, const DWARFDebugRanges* debug_ranges, 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=116290&r1=116289&r2=116290&view=diff ============================================================================== --- lldb/trunk/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp (original) +++ lldb/trunk/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp Mon Oct 11 21:24:53 2010 @@ -49,6 +49,7 @@ #include "DWARFFormValue.h" #include "DWARFLocationList.h" #include "LogChannelDWARF.h" +#include "SymbolFileDWARFDebugMap.h" #include @@ -141,8 +142,9 @@ } -SymbolFileDWARF::SymbolFileDWARF(ObjectFile* ofile) : - SymbolFile(ofile), +SymbolFileDWARF::SymbolFileDWARF(ObjectFile* objfile) : + SymbolFile (objfile), + m_debug_map_symfile (NULL), m_flags(), m_data_debug_abbrev(), m_data_debug_frame(), @@ -159,6 +161,7 @@ m_function_fullname_index(), m_function_method_index(), m_function_selector_index(), + m_objc_class_selectors_index(), m_global_index(), m_types_index(), m_indexed(false), @@ -906,7 +909,7 @@ std::auto_ptr line_table_ap(new LineTable(sc.comp_unit)); if (line_table_ap.get()) { - ParseDWARFLineTableCallbackInfo info = { line_table_ap.get(), m_obj_file->GetSectionList(), 0, 0, m_flags.IsSet (flagsDWARFIsOSOForDebugMap), false}; + ParseDWARFLineTableCallbackInfo info = { line_table_ap.get(), m_obj_file->GetSectionList(), 0, 0, m_debug_map_symfile != NULL, false}; uint32_t offset = cu_line_offset; DWARFDebugLine::ParseStatementTable(get_debug_line_data(), &offset, ParseDWARFLineTableCallback, &info); sc.comp_unit->SetLineTable(line_table_ap.release()); @@ -1257,7 +1260,9 @@ if (die == NULL) return NULL; - DWARFCompileUnit *cu = DebugInfo()->GetCompileUnitContainingDIE (die->GetOffset()).get(); + DWARFDebugInfo* debug_info = DebugInfo(); + + DWARFCompileUnit *cu = debug_info->GetCompileUnitContainingDIE (die->GetOffset()).get(); Type *type = m_die_to_type.lookup (die); const dw_tag_t tag = die->Tag(); @@ -1277,7 +1282,8 @@ if (die->HasChildren()) { LanguageType class_language = eLanguageTypeUnknown; - if (ClangASTContext::IsObjCClassType (clang_type)) + bool is_objc_class = ClangASTContext::IsObjCClassType (clang_type); + if (is_objc_class) class_language = eLanguageTypeObjC; int tag_decl_kind = -1; @@ -1326,6 +1332,34 @@ } } + if (class_language == eLanguageTypeObjC) + { + std::string class_str (ClangASTContext::GetTypeName (clang_type)); + if (!class_str.empty()) + { + + ConstString class_name (class_str.c_str()); + std::vector method_die_infos; + if (m_objc_class_selectors_index.Find (class_name, method_die_infos)) + { + DWARFCompileUnit* method_cu = NULL; + DWARFCompileUnit* prev_method_cu = NULL; + const size_t num_objc_methods = method_die_infos.size(); + for (size_t i=0;iGetCompileUnitAtIndex(method_die_infos[i].cu_idx); + + if (method_cu != prev_method_cu) + method_cu->ExtractDIEsIfNeeded (false); + + DWARFDebugInfoEntry *method_die = method_cu->GetDIEAtIndexUnchecked(method_die_infos[i].die_idx); + + ResolveType (method_cu, method_die); + } + } + } + } + // If we have a DW_TAG_structure_type instead of a DW_TAG_class_type we // need to tell the clang type it is actually a class. if (class_language != eLanguageTypeObjC) @@ -1412,6 +1446,9 @@ DebugInfo()->GetCompileUnit(cu->GetOffset(), &cu_idx); m_obj_file->GetModule()->GetSymbolVendor()->SetCompileUnitAtIndex(dc_cu, cu_idx); + + if (m_debug_map_symfile) + m_debug_map_symfile->SetCompileUnit(this, dc_cu); } } return (CompileUnit*)cu->GetUserData(); @@ -1673,6 +1710,7 @@ m_function_fullname_index, m_function_method_index, m_function_selector_index, + m_objc_class_selectors_index, m_global_index, m_types_index, DebugRanges(), @@ -1686,13 +1724,14 @@ m_aranges->Sort(); -#if 0 +#if 0 StreamFile s(stdout); s.Printf("DWARF index for '%s':", GetObjectFile()->GetFileSpec().GetFilename().AsCString()); s.Printf("\nFunction basenames:\n"); m_function_basename_index.Dump (&s); s.Printf("\nFunction fullnames:\n"); m_function_fullname_index.Dump (&s); s.Printf("\nFunction methods:\n"); m_function_method_index.Dump (&s); s.Printf("\nFunction selectors:\n"); m_function_selector_index.Dump (&s); + s.Printf("\nObjective C class selectors:\n"); m_objc_class_selectors_index.Dump (&s); s.Printf("\nGlobals and statics:\n"); m_global_index.Dump (&s); s.Printf("\nTypes:\n"); m_types_index.Dump (&s); #endif @@ -2975,9 +3014,10 @@ for (uint32_t i=0; iGetClangType())) + clang_type_t type_clang_forward_type = type->GetClangForwardType(); + if (ClangASTContext::IsObjCClassType (type_clang_forward_type)) { - class_opaque_type = type->GetClangType(); + class_opaque_type = type_clang_forward_type; break; } } @@ -3216,6 +3256,10 @@ { // We are ready to put this type into the uniqued list up at the module level TypeSP uniqued_type_sp(m_obj_file->GetModule()->GetTypeList()->InsertUnique(type_sp)); + + if (m_debug_map_symfile) + m_debug_map_symfile->GetObjectFile()->GetModule()->GetTypeList()->InsertUnique (uniqued_type_sp); + type_sp = uniqued_type_sp; m_die_to_type[die] = type_sp.get(); } 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=116290&r1=116289&r2=116290&view=diff ============================================================================== --- lldb/trunk/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.h (original) +++ lldb/trunk/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.h Mon Oct 11 21:24:53 2010 @@ -49,6 +49,7 @@ class DWARFDebugRanges; class DWARFDIECollection; class DWARFFormValue; +class SymbolFileDWARFDebugMap; class SymbolFileDWARF : public lldb_private::SymbolFile { @@ -196,9 +197,6 @@ flagsGotDebugPubTypesData = (1 << 8), flagsGotDebugRangesData = (1 << 9), flagsGotDebugStrData = (1 << 10), - // True if this is a .o file used when resolving a N_OSO entry with - // debug maps. - flagsDWARFIsOSOForDebugMap = (1 << 16) }; DISALLOW_COPY_AND_ASSIGN (SymbolFileDWARF); @@ -288,6 +286,12 @@ void Index(); + void SetDebugMapSymfile (SymbolFileDWARFDebugMap *debug_map_symfile) + { + m_debug_map_symfile = debug_map_symfile; + } + + SymbolFileDWARFDebugMap* m_debug_map_symfile; lldb_private::Flags m_flags; lldb_private::DataExtractor m_dwarf_data; lldb_private::DataExtractor m_data_debug_abbrev; @@ -308,6 +312,7 @@ NameToDIE m_function_fullname_index; // All concrete functions NameToDIE m_function_method_index; // All inlined functions NameToDIE m_function_selector_index; // All method names for functions of classes + NameToDIE m_objc_class_selectors_index; // Given a class name, find all selectors for the class NameToDIE m_global_index; // Global and static variables NameToDIE m_types_index; // All type DIE offsets bool m_indexed; Modified: lldb/trunk/source/Plugins/SymbolFile/DWARF/SymbolFileDWARFDebugMap.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Plugins/SymbolFile/DWARF/SymbolFileDWARFDebugMap.cpp?rev=116290&r1=116289&r2=116290&view=diff ============================================================================== --- lldb/trunk/source/Plugins/SymbolFile/DWARF/SymbolFileDWARFDebugMap.cpp (original) +++ lldb/trunk/source/Plugins/SymbolFile/DWARF/SymbolFileDWARFDebugMap.cpp Mon Oct 11 21:24:53 2010 @@ -227,10 +227,10 @@ // comp_unit_info->oso_dwarf_sp.reset (oso_dwarf); if (comp_unit_info->oso_symbol_vendor) { - // Set a bit that lets this DWARF file know that it is being - // used along with a debug map and that it will have the - // remapped sections that we do below. - ((SymbolFileDWARF *)comp_unit_info->oso_symbol_vendor->GetSymbolFile())->GetFlags().Set(SymbolFileDWARF::flagsDWARFIsOSOForDebugMap); + // Set a a pointer to this class to set our OSO DWARF file know + // that the DWARF is being used along with a debug map and that + // it will have the remapped sections that we do below. + ((SymbolFileDWARF *)comp_unit_info->oso_symbol_vendor->GetSymbolFile())->SetDebugMapSymfile(this); comp_unit_info->debug_map_sections_sp.reset(new SectionList); Symtab *exe_symtab = m_obj_file->GetSymtab(); @@ -506,6 +506,10 @@ so_symbol->GetMangled().GetName().AsCString(), cu_idx, eLanguageTypeUnknown)); + + // Let our symbol vendor know about this compile unit + m_obj_file->GetModule()->GetSymbolVendor()->SetCompileUnitAtIndex (m_compile_unit_infos[cu_idx].oso_compile_unit_sp, + cu_idx); } } } @@ -966,3 +970,24 @@ } +void +SymbolFileDWARFDebugMap::SetCompileUnit (SymbolFileDWARF *oso_dwarf, const CompUnitSP &cu_sp) +{ + const uint32_t cu_count = GetNumCompileUnits(); + for (uint32_t i=0; iGetSymbolFile() == oso_dwarf) + { + if (m_compile_unit_infos[i].oso_compile_unit_sp) + { + assert (m_compile_unit_infos[i].oso_compile_unit_sp.get() == cu_sp.get()); + } + else + { + m_compile_unit_infos[i].oso_compile_unit_sp = cu_sp; + } + } + } +} + Modified: lldb/trunk/source/Plugins/SymbolFile/DWARF/SymbolFileDWARFDebugMap.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Plugins/SymbolFile/DWARF/SymbolFileDWARFDebugMap.h?rev=116290&r1=116289&r2=116290&view=diff ============================================================================== --- lldb/trunk/source/Plugins/SymbolFile/DWARF/SymbolFileDWARFDebugMap.h (original) +++ lldb/trunk/source/Plugins/SymbolFile/DWARF/SymbolFileDWARFDebugMap.h Mon Oct 11 21:24:53 2010 @@ -98,6 +98,8 @@ kNumFlags }; + friend class SymbolFileDWARF; + //------------------------------------------------------------------ // Class specific types //------------------------------------------------------------------ @@ -184,6 +186,10 @@ uint32_t max_matches, lldb_private::VariableList& variables); + + void + SetCompileUnit (SymbolFileDWARF *oso_dwarf, const lldb::CompUnitSP &cu_sp); + //------------------------------------------------------------------ // Member Variables //------------------------------------------------------------------ Modified: lldb/trunk/source/Symbol/ClangASTContext.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Symbol/ClangASTContext.cpp?rev=116290&r1=116289&r2=116290&view=diff ============================================================================== --- lldb/trunk/source/Symbol/ClangASTContext.cpp (original) +++ lldb/trunk/source/Symbol/ClangASTContext.cpp Mon Oct 11 21:24:53 2010 @@ -1559,12 +1559,22 @@ return NULL; llvm::SmallVector selector_idents; - size_t len; + size_t len = 0; const char *start; - for (start = selector_start, len = ::strcspn(start, ":]"); + //printf ("name = '%s'\n", name); + + unsigned num_selectors_with_args = 0; + for (start = selector_start; start && *start != '\0' && *start != ']'; - start += len + 1) + start += len) { + len = ::strcspn(start, ":]"); + if (start[len] == ':') + { + ++num_selectors_with_args; + len += 1; + } + //printf ("@selector[%zu] = '%.*s'\n", selector_idents.size(), (int)len, start); selector_idents.push_back (&identifier_table->get (StringRef (start, len))); } @@ -1572,7 +1582,7 @@ if (selector_idents.size() == 0) return 0; - clang::Selector method_selector = ast_context->Selectors.getSelector (selector_idents.size(), + clang::Selector method_selector = ast_context->Selectors.getSelector (num_selectors_with_args ? selector_idents.size() : 0, selector_idents.data()); QualType method_qual_type (QualType::getFromOpaquePtr (method_opaque_type)); Modified: lldb/trunk/source/Symbol/SymbolVendor.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Symbol/SymbolVendor.cpp?rev=116290&r1=116289&r2=116290&view=diff ============================================================================== --- lldb/trunk/source/Symbol/SymbolVendor.cpp (original) +++ lldb/trunk/source/Symbol/SymbolVendor.cpp Mon Oct 11 21:24:53 2010 @@ -96,8 +96,7 @@ } bool -SymbolVendor::SetCompileUnitAtIndex -(CompUnitSP& cu, uint32_t idx) +SymbolVendor::SetCompileUnitAtIndex (CompUnitSP& cu, uint32_t idx) { Mutex::Locker locker(m_mutex); const uint32_t num_compile_units = GetNumCompileUnits(); From gclayton at apple.com Mon Oct 11 23:29:14 2010 From: gclayton at apple.com (Greg Clayton) Date: Tue, 12 Oct 2010 04:29:14 -0000 Subject: [Lldb-commits] [lldb] r116293 - in /lldb/trunk: include/lldb/Breakpoint/BreakpointResolverName.h include/lldb/lldb-enumerations.h lldb.xcodeproj/project.pbxproj scripts/build-llvm.pl source/Breakpoint/BreakpointResolverName.cpp source/Commands/CommandObjectBreakpoint.cpp source/Symbol/ClangASTContext.cpp Message-ID: <20101012042914.985C02A6C12E@llvm.org> Author: gclayton Date: Mon Oct 11 23:29:14 2010 New Revision: 116293 URL: http://llvm.org/viewvc/llvm-project?rev=116293&view=rev Log: Modified the "breakpoint set --name NAME" to be the auto breakpoint set function. It will inspect NAME and do the following: - if the name contains '(' or starts with "-[" or "+[" then a full name search will happen to match full function names with args (C++ demangled names) or full objective C method prototypes. - if the name contains "::" and no '(', then it is assumed to be a qualified function name that is in a namespace or class. For "foo::bar::baz" we will search for any functions with the basename or method name of "baz", then filter the results to only those that contain "foo::bar::baz". This allows setting breakpoint on C++ functions and methods without having to fully qualify all of the types that would appear in C++ mangled names. - if the name contains ":" (not "::"), then NAME is assumed to be an ObjC selector. _ otherwise, we assume just a plain function basename. Now that "--name" is our "auto" mode, I introduced the new "--basename" option ("breakpoint set --basename NAME") to allow for function names that aren't methods or selectors, just basenames. This can also be used to ignore C++ namespaces and class hierarchies for class methods. Fixed clang enumeration promotion types to be correct. Modified: lldb/trunk/include/lldb/Breakpoint/BreakpointResolverName.h lldb/trunk/include/lldb/lldb-enumerations.h lldb/trunk/lldb.xcodeproj/project.pbxproj lldb/trunk/scripts/build-llvm.pl lldb/trunk/source/Breakpoint/BreakpointResolverName.cpp lldb/trunk/source/Commands/CommandObjectBreakpoint.cpp lldb/trunk/source/Symbol/ClangASTContext.cpp Modified: lldb/trunk/include/lldb/Breakpoint/BreakpointResolverName.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/Breakpoint/BreakpointResolverName.h?rev=116293&r1=116292&r2=116293&view=diff ============================================================================== --- lldb/trunk/include/lldb/Breakpoint/BreakpointResolverName.h (original) +++ lldb/trunk/include/lldb/Breakpoint/BreakpointResolverName.h Mon Oct 11 23:29:14 2010 @@ -63,6 +63,14 @@ protected: ConstString m_func_name; + // "m_basename_filter" is used to filter results after searching for + // "m_func_name" first. This is used when we are asked to set a breakpoint + // at "foo::bar::baz" (C++ function in namespace or in a class). For + // "foo::bar::baz" we will place "baz" into m_func_name and search for all + // matching basename and methods that match "baz", then we will filter the + // results by checking if the demangled name contains "m_basename_filter" + // which would be set to "foo::bar::baz". + std::string m_basename_filter; uint32_t m_func_name_type_mask; // See FunctionNameType ConstString m_class_name; // FIXME: Not used yet. The idea would be to stop on methods of this class. RegularExpression m_regex; Modified: lldb/trunk/include/lldb/lldb-enumerations.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/lldb-enumerations.h?rev=116293&r1=116292&r2=116293&view=diff ============================================================================== --- lldb/trunk/include/lldb/lldb-enumerations.h (original) +++ lldb/trunk/include/lldb/lldb-enumerations.h Mon Oct 11 23:29:14 2010 @@ -412,15 +412,17 @@ typedef enum FunctionNameType { eFunctionNameTypeNone = 0u, - eFunctionNameTypeFull = (1u << 1),// The function name. - // For C this is the same as just the name of the function - // For C++ this is the demangled version of the mangled name. - // For ObjC this is the full function signature with the + or - // - and the square brackets and the class and selector - eFunctionNameTypeBase = (1u << 2),// The function name only, no namespaces or arguments and no class - // methods or selectors will be searched. - eFunctionNameTypeMethod = (1u << 3),// Find function by method name (C++) with no namespace or arguments - eFunctionNameTypeSelector = (1u << 4) // Find function by selector name (ObjC) names + eFunctionNameTypeAuto = (1u << 1), // Automatically figure out which FunctionNameType + // bits to set based on the function name. + eFunctionNameTypeFull = (1u << 2), // The function name. + // For C this is the same as just the name of the function + // For C++ this is the demangled version of the mangled name. + // For ObjC this is the full function signature with the + or + // - and the square brackets and the class and selector + eFunctionNameTypeBase = (1u << 3), // The function name only, no namespaces or arguments and no class + // methods or selectors will be searched. + eFunctionNameTypeMethod = (1u << 4), // Find function by method name (C++) with no namespace or arguments + eFunctionNameTypeSelector = (1u << 5), // Find function by selector name (ObjC) names } FunctionNameType; Modified: lldb/trunk/lldb.xcodeproj/project.pbxproj URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/lldb.xcodeproj/project.pbxproj?rev=116293&r1=116292&r2=116293&view=diff ============================================================================== --- lldb/trunk/lldb.xcodeproj/project.pbxproj (original) +++ lldb/trunk/lldb.xcodeproj/project.pbxproj Mon Oct 11 23:29:14 2010 @@ -2964,7 +2964,7 @@ "$(LLVM_BUILD_DIR)", ); LLVM_BUILD_DIR = "$(SRCROOT)/llvm"; - LLVM_CONFIGURATION = Release; + LLVM_CONFIGURATION = "Debug+Asserts"; OTHER_CFLAGS = ( "-DFOR_DYLD=0", "-DSUPPORT_REMOTE_UNWINDING", Modified: lldb/trunk/scripts/build-llvm.pl URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/scripts/build-llvm.pl?rev=116293&r1=116292&r2=116293&view=diff ============================================================================== --- lldb/trunk/scripts/build-llvm.pl (original) +++ lldb/trunk/scripts/build-llvm.pl Mon Oct 11 23:29:14 2010 @@ -91,7 +91,7 @@ # LLVM in the "lldb" root is a symlink which indicates we are using a # standard LLVM build directory where everything is built into the # same folder - create_single_llvm_arhive_for_arch ($llvm_dstroot, 0); + create_single_llvm_arhive_for_arch ($llvm_dstroot, 1); my $llvm_dstroot_archive = "$llvm_dstroot/$llvm_clang_basename"; push @llvm_clang_slices, $llvm_dstroot_archive; create_dstroot_file ($llvm_clang_basename, $llvm_clang_dirname, \@llvm_clang_slices, $llvm_clang_basename); Modified: lldb/trunk/source/Breakpoint/BreakpointResolverName.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Breakpoint/BreakpointResolverName.cpp?rev=116293&r1=116292&r2=116293&view=diff ============================================================================== --- lldb/trunk/source/Breakpoint/BreakpointResolverName.cpp (original) +++ lldb/trunk/source/Breakpoint/BreakpointResolverName.cpp Mon Oct 11 23:29:14 2010 @@ -29,12 +29,54 @@ Breakpoint::MatchType type ) : BreakpointResolver (bkpt), - m_func_name (func_name), + m_func_name (), + m_basename_filter (), m_func_name_type_mask (func_name_type_mask), m_class_name (), m_regex (), m_match_type (type) { + if (func_name_type_mask == eFunctionNameTypeAuto) + { + if ((::strchr (func_name, '(' ) != NULL) || + (::strstr (func_name, "-[") == func_name) || + (::strstr (func_name, "+[") == func_name)) + { + // We have a name that contains an open parens, or starts with + // "+[" or "-[", so this looks like a complete function prototype + m_func_name_type_mask = eFunctionNameTypeFull; + } + else + { + // We don't have a full function name, but we might have a partial + // function basename with namespaces or classes + if (::strstr (func_name, "::") != NULL) + { + // Keep the full name in "m_basename_filter" + m_basename_filter = func_name; + // Now set "m_func_name" to just the function basename + m_func_name.SetCString(m_basename_filter.c_str() + m_basename_filter.rfind("::") + 2); + // We have a name with a double colon which means we have a + // function name that is a C++ method or a function in a C++ + // namespace + m_func_name_type_mask = eFunctionNameTypeBase | eFunctionNameTypeMethod; + } + else if (::strstr (func_name, ":") != NULL) + { + // Single colon => selector + m_func_name_type_mask = eFunctionNameTypeSelector; + } + else + { + // just a basename by default + m_func_name_type_mask = eFunctionNameTypeBase; + } + } + } + + if (!m_func_name) + m_func_name.SetCString(func_name); + if (m_match_type == Breakpoint::Regexp) { if (!m_regex.Compile (m_func_name.AsCString())) @@ -137,6 +179,53 @@ break; } + if (!m_basename_filter.empty()) + { + // Filter out any matches whose names don't contain the basename filter + const char *basename_filter = m_basename_filter.c_str(); + if (func_list.GetSize()) + { + bool remove = false; + for (i = 0; i < func_list.GetSize(); remove = false) + { + if (func_list.GetContextAtIndex(i, sc) == false) + remove = true; + else if (sc.function == NULL) + remove = true; + else if (::strstr (sc.function->GetName().AsCString(), basename_filter) == NULL) + remove = true; + + if (remove) + { + func_list.RemoveContextAtIndex(i); + continue; + } + i++; + } + } + + if (sym_list.GetSize()) + { + bool remove = false; + for (i = 0; i < sym_list.GetSize(); remove = false) + { + if (sym_list.GetContextAtIndex(i, sc) == false) + remove = true; + else if (sc.symbol == NULL) + remove = true; + else if (::strstr (sc.symbol->GetName().AsCString(), basename_filter) == NULL) + remove = true; + + if (remove) + { + sym_list.RemoveContextAtIndex(i); + continue; + } + i++; + } + } + } + // Remove any duplicates between the funcion list and the symbol list if (func_list.GetSize()) { @@ -242,8 +331,10 @@ { if (m_match_type == Breakpoint::Regexp) s->Printf("regex = '%s'", m_regex.GetText()); - else + else if (m_basename_filter.empty()) s->Printf("name = '%s'", m_func_name.AsCString()); + else + s->Printf("name = '%s'", m_basename_filter.c_str()); } void Modified: lldb/trunk/source/Commands/CommandObjectBreakpoint.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Commands/CommandObjectBreakpoint.cpp?rev=116293&r1=116292&r2=116293&view=diff ============================================================================== --- lldb/trunk/source/Commands/CommandObjectBreakpoint.cpp (original) +++ lldb/trunk/source/Commands/CommandObjectBreakpoint.cpp Mon Oct 11 23:29:14 2010 @@ -104,7 +104,7 @@ "Set the breakpoint by address, at the specified address."}, { LLDB_OPT_SET_3, true, "name", 'n', required_argument, NULL, CommandCompletions::eSymbolCompletion, eArgTypeFunctionName, - "Set the breakpoint by function name - for C++ this means namespaces and arguments will be ignored." }, + "Set the breakpoint by function name." }, { LLDB_OPT_SET_4, true, "fullname", 'F', required_argument, NULL, CommandCompletions::eSymbolCompletion, eArgTypeFullName, "Set the breakpoint by fully qualified function names. For C++ this means namespaces and all arguemnts, and " @@ -119,6 +119,9 @@ { LLDB_OPT_SET_7, true, "func-regex", 'r', required_argument, NULL, 0, eArgTypeRegularExpression, "Set the breakpoint by function name, evaluating a regular-expression to find the function name(s)." }, + { LLDB_OPT_SET_8, true, "basename", 'b', required_argument, NULL, CommandCompletions::eSymbolCompletion, eArgTypeFunctionName, + "Set the breakpoint by function basename (C++ namespaces and arguments will be ignored)." }, + { 0, false, NULL, 0, 0, NULL, 0, eArgTypeNone, NULL } }; @@ -157,11 +160,16 @@ m_line_num = Args::StringToUInt32 (option_arg, 0); break; - case 'n': + case 'b': m_func_name = option_arg; m_func_name_type_mask |= eFunctionNameTypeBase; break; + case 'n': + m_func_name = option_arg; + m_func_name_type_mask |= eFunctionNameTypeAuto; + break; + case 'F': m_func_name = option_arg; m_func_name_type_mask |= eFunctionNameTypeFull; @@ -391,17 +399,8 @@ uint32_t name_type_mask = m_options.m_func_name_type_mask; if (name_type_mask == 0) - { - - if (m_options.m_func_name.find('(') != std::string::npos || - m_options.m_func_name.find("-[") == 0 || - m_options.m_func_name.find("+[") == 0) - name_type_mask |= eFunctionNameTypeFull; - else - name_type_mask |= eFunctionNameTypeBase; - } - - + name_type_mask = eFunctionNameTypeAuto; + if (use_module) { for (int i = 0; i < num_modules; ++i) Modified: lldb/trunk/source/Symbol/ClangASTContext.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Symbol/ClangASTContext.cpp?rev=116293&r1=116292&r2=116293&view=diff ============================================================================== --- lldb/trunk/source/Symbol/ClangASTContext.cpp (original) +++ lldb/trunk/source/Symbol/ClangASTContext.cpp Mon Oct 11 23:29:14 2010 @@ -3099,7 +3099,22 @@ unsigned NumPositiveBits = 1; unsigned NumNegativeBits = 0; - enum_decl->completeDefinition(enum_decl->getIntegerType(), enum_decl->getIntegerType(), NumPositiveBits, NumNegativeBits); + ASTContext *ast_context = getASTContext(); + + QualType promotion_qual_type; + // If the enum integer type is less than an integer in bit width, + // then we must promote it to an integer size. + if (ast_context->getTypeSize(enum_decl->getIntegerType()) < ast_context->getTypeSize(ast_context->IntTy)) + { + if (enum_decl->getIntegerType()->isSignedIntegerType()) + promotion_qual_type = ast_context->IntTy; + else + promotion_qual_type = ast_context->UnsignedIntTy; + } + else + promotion_qual_type = enum_decl->getIntegerType(); + + enum_decl->completeDefinition(enum_decl->getIntegerType(), promotion_qual_type, NumPositiveBits, NumNegativeBits); return true; } } @@ -3117,12 +3132,17 @@ // like maybe filling in the SourceLocation with it... ASTContext *ast_context = getASTContext(); assert (ast_context != NULL); - EnumDecl *enum_decl = EnumDecl::Create(*ast_context, - ast_context->getTranslationUnitDecl(), - SourceLocation(), - name && name[0] ? &ast_context->Idents.get(name) : NULL, - SourceLocation(), - NULL); + + // TODO: ask about these... +// const bool IsScoped = false; +// const bool IsFixed = false; + + EnumDecl *enum_decl = EnumDecl::Create (*ast_context, + ast_context->getTranslationUnitDecl(), + SourceLocation(), + name && name[0] ? &ast_context->Idents.get(name) : NULL, + SourceLocation(), + NULL); //IsScoped, IsFixed); if (enum_decl) { // TODO: check if we should be setting the promotion type too? From johnny.chen at apple.com Tue Oct 12 10:53:22 2010 From: johnny.chen at apple.com (Johnny Chen) Date: Tue, 12 Oct 2010 15:53:22 -0000 Subject: [Lldb-commits] [lldb] r116309 - /lldb/trunk/test/dotest.py Message-ID: <20101012155322.372DA2A6C12C@llvm.org> Author: johnny Date: Tue Oct 12 10:53:22 2010 New Revision: 116309 URL: http://llvm.org/viewvc/llvm-project?rev=116309&view=rev Log: Update comments. 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=116309&r1=116308&r2=116309&view=diff ============================================================================== --- lldb/trunk/test/dotest.py (original) +++ lldb/trunk/test/dotest.py Tue Oct 12 10:53:22 2010 @@ -381,6 +381,8 @@ continue # We found a match for our test case. Add it to the suite. + + # Update the sys.path first. if not sys.path.count(dir): sys.path.insert(0, dir) base = os.path.splitext(name)[0] @@ -473,7 +475,7 @@ os.environ["LLDB_SKIP_LONG_RUNNING_TEST"] = "NO" # -# Walk through the testdirs while collecting test cases. +# Walk through the testdirs while collecting tests. # for testdir in testdirs: os.path.walk(testdir, visit, 'Test') From gclayton at apple.com Tue Oct 12 12:33:06 2010 From: gclayton at apple.com (Greg Clayton) Date: Tue, 12 Oct 2010 17:33:06 -0000 Subject: [Lldb-commits] [lldb] r116315 - in /lldb/trunk/source/Plugins/Process: MacOSX-User/source/ThreadMacOSX.cpp gdb-remote/ProcessGDBRemote.cpp Message-ID: <20101012173306.3B68E2A6C12C@llvm.org> Author: gclayton Date: Tue Oct 12 12:33:06 2010 New Revision: 116315 URL: http://llvm.org/viewvc/llvm-project?rev=116315&view=rev Log: Fixed the dispatch queue name retrieval for threads by looking in an extra shlib. Modified: lldb/trunk/source/Plugins/Process/MacOSX-User/source/ThreadMacOSX.cpp lldb/trunk/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp 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=116315&r1=116314&r2=116315&view=diff ============================================================================== --- lldb/trunk/source/Plugins/Process/MacOSX-User/source/ThreadMacOSX.cpp (original) +++ lldb/trunk/source/Plugins/Process/MacOSX-User/source/ThreadMacOSX.cpp Tue Oct 12 12:33:06 2010 @@ -107,13 +107,20 @@ return NULL; uint8_t memory_buffer[8]; + addr_t dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS; DataExtractor data(memory_buffer, sizeof(memory_buffer), m_process.GetByteOrder(), m_process.GetAddressByteSize()); + static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets"); + const Symbol *dispatch_queue_offsets_symbol = NULL; ModuleSP module_sp(m_process.GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libSystem.B.dylib"))); - if (module_sp.get() == NULL) - return NULL; - - lldb::addr_t dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS; - const Symbol *dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (ConstString("dispatch_queue_offsets"), eSymbolTypeData); + if (module_sp) + dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData); + + if (dispatch_queue_offsets_symbol == NULL) + { + module_sp = m_process.GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libdispatch.dylib")); + if (module_sp) + dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData); + } if (dispatch_queue_offsets_symbol) dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetValue().GetLoadAddress(&m_process.GetTarget()); 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=116315&r1=116314&r2=116315&view=diff ============================================================================== --- lldb/trunk/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp (original) +++ lldb/trunk/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp Tue Oct 12 12:33:06 2010 @@ -2243,11 +2243,18 @@ // to look it up if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS) { + static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets"); + const Symbol *dispatch_queue_offsets_symbol = NULL; ModuleSP module_sp(GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libSystem.B.dylib"))); - if (module_sp.get() == NULL) - return NULL; - - const Symbol *dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (ConstString("dispatch_queue_offsets"), eSymbolTypeData); + if (module_sp) + dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData); + + if (dispatch_queue_offsets_symbol == NULL) + { + module_sp = GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libdispatch.dylib")); + if (module_sp) + dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData); + } if (dispatch_queue_offsets_symbol) m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetValue().GetLoadAddress(&m_target); From ctice at apple.com Tue Oct 12 12:45:19 2010 From: ctice at apple.com (Caroline Tice) Date: Tue, 12 Oct 2010 17:45:19 -0000 Subject: [Lldb-commits] [lldb] r116316 - in /lldb/trunk/source: Commands/CommandObjectCommands.cpp Interpreter/Args.cpp Message-ID: <20101012174519.461042A6C12C@llvm.org> Author: ctice Date: Tue Oct 12 12:45:19 2010 New Revision: 116316 URL: http://llvm.org/viewvc/llvm-project?rev=116316&view=rev Log: Fix bug where alias command options were being duplicated as command arguments as well. Modified: lldb/trunk/source/Commands/CommandObjectCommands.cpp lldb/trunk/source/Interpreter/Args.cpp Modified: lldb/trunk/source/Commands/CommandObjectCommands.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Commands/CommandObjectCommands.cpp?rev=116316&r1=116315&r2=116316&view=diff ============================================================================== --- lldb/trunk/source/Commands/CommandObjectCommands.cpp (original) +++ lldb/trunk/source/Commands/CommandObjectCommands.cpp Tue Oct 12 12:45:19 2010 @@ -346,8 +346,9 @@ argc = args.GetArgumentCount(); for (size_t i = 0; i < argc; ++i) - option_arg_vector->push_back (OptionArgPair ("", - std::string (args.GetArgumentAtIndex (i)))); + if (strcmp (args.GetArgumentAtIndex (i), "") != 0) + option_arg_vector->push_back (OptionArgPair ("", + std::string (args.GetArgumentAtIndex (i)))); } // Create the alias. Modified: lldb/trunk/source/Interpreter/Args.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Interpreter/Args.cpp?rev=116316&r1=116315&r2=116316&view=diff ============================================================================== --- lldb/trunk/source/Interpreter/Args.cpp (original) +++ lldb/trunk/source/Interpreter/Args.cpp Tue Oct 12 12:45:19 2010 @@ -802,12 +802,9 @@ } void -Args::ParseAliasOptions -( - Options &options, - CommandReturnObject &result, - OptionArgVector *option_arg_vector -) +Args::ParseAliasOptions (Options &options, + CommandReturnObject &result, + OptionArgVector *option_arg_vector) { StreamString sstr; int i; @@ -936,6 +933,31 @@ result.AppendErrorWithFormat ("Invalid option with value '%c'.\n", (char) val); result.SetStatus (eReturnStatusFailed); } + + if (long_options_index >= 0) + { + // Find option in the argument list; also see if it was supposed to take an argument and if one was + // supplied. Remove option (and argument, if given) from the argument list. + StreamString short_opt_str; + StreamString long_opt_str; + short_opt_str.Printf ("-%c", (char) long_options[long_options_index].val); + long_opt_str.Printf ("-%s", long_options[long_options_index].name); + bool found = false; + size_t end = GetArgumentCount(); + for (size_t i = 0; i < end && !found; ++i) + if ((strcmp (GetArgumentAtIndex (i), short_opt_str.GetData()) == 0) + || (strcmp (GetArgumentAtIndex (i), long_opt_str.GetData()) == 0)) + { + found = true; + ReplaceArgumentAtIndex (i, ""); + if ((long_options[long_options_index].has_arg != no_argument) + && (optarg != NULL) + && (i+1 < end) + && (strcmp (optarg, GetArgumentAtIndex(i+1)) == 0)) + ReplaceArgumentAtIndex (i+1, ""); + } + } + if (!result.Succeeded()) break; } From gclayton at apple.com Tue Oct 12 13:04:53 2010 From: gclayton at apple.com (Greg Clayton) Date: Tue, 12 Oct 2010 18:04:53 -0000 Subject: [Lldb-commits] [lldb] r116320 - /lldb/trunk/source/Interpreter/CommandObjectRegexCommand.cpp Message-ID: <20101012180453.92A2D2A6C12D@llvm.org> Author: gclayton Date: Tue Oct 12 13:04:53 2010 New Revision: 116320 URL: http://llvm.org/viewvc/llvm-project?rev=116320&view=rev Log: Regular expression commands now print the command that results from expanding the regular expression command. Modified: lldb/trunk/source/Interpreter/CommandObjectRegexCommand.cpp Modified: lldb/trunk/source/Interpreter/CommandObjectRegexCommand.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Interpreter/CommandObjectRegexCommand.cpp?rev=116320&r1=116319&r2=116320&view=diff ============================================================================== --- lldb/trunk/source/Interpreter/CommandObjectRegexCommand.cpp (original) +++ lldb/trunk/source/Interpreter/CommandObjectRegexCommand.cpp Tue Oct 12 13:04:53 2010 @@ -87,15 +87,14 @@ } } // Interpret the new command and return this as the result! -// if (m_options.verbose) -// result.GetOutputStream().Printf("%s\n", new_command.c_str()); + result.GetOutputStream().Printf("%s\n", new_command.c_str()); return m_interpreter.HandleCommand(new_command.c_str(), true, result); } } result.SetStatus(eReturnStatusFailed); - result.AppendErrorWithFormat("Command contents '%s' failed to match any regular expression in the '%s' regex command.\n", - command, - m_cmd_name.c_str()); + result.AppendErrorWithFormat ("Command contents '%s' failed to match any regular expression in the '%s' regex command.\n", + command, + m_cmd_name.c_str()); return false; } result.AppendError("empty command passed to regular exression command"); From johnny.chen at apple.com Tue Oct 12 14:29:50 2010 From: johnny.chen at apple.com (Johnny Chen) Date: Tue, 12 Oct 2010 19:29:50 -0000 Subject: [Lldb-commits] [lldb] r116331 - in /lldb/trunk/test/foundation: TestFoundationDisassembly.py TestObjCMethods.py Message-ID: <20101012192950.0BD112A6C12C@llvm.org> Author: johnny Date: Tue Oct 12 14:29:49 2010 New Revision: 116331 URL: http://llvm.org/viewvc/llvm-project?rev=116331&view=rev Log: The 'regexp-break' command now prints out the command that results from expanding the regular expression command. So change the more stringent: self.expect(..., startstr = matching_string) to: self.expect(..., substrs = [matched_string]) to pass the test. Modified: lldb/trunk/test/foundation/TestFoundationDisassembly.py lldb/trunk/test/foundation/TestObjCMethods.py Modified: lldb/trunk/test/foundation/TestFoundationDisassembly.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/foundation/TestFoundationDisassembly.py?rev=116331&r1=116330&r2=116331&view=diff ============================================================================== --- lldb/trunk/test/foundation/TestFoundationDisassembly.py (original) +++ lldb/trunk/test/foundation/TestFoundationDisassembly.py Tue Oct 12 14:29:49 2010 @@ -71,7 +71,7 @@ # Stop at +[NSString stringWithFormat:]. self.expect("regexp-break +[NSString stringWithFormat:]", BREAKPOINT_CREATED, - startstr = "Breakpoint created: 1: name = '+[NSString stringWithFormat:]', locations = 1") + substrs = ["Breakpoint created: 1: name = '+[NSString stringWithFormat:]', locations = 1"]) # Stop at -[MyString initWithNSString:]. self.expect("breakpoint set -n '-[MyString initWithNSString:]'", BREAKPOINT_CREATED, @@ -83,7 +83,7 @@ # Stop at -[NSAutoreleasePool release]. self.expect("regexp-break -[NSAutoreleasePool release]", BREAKPOINT_CREATED, - startstr = "Breakpoint created: 4: name = '-[NSAutoreleasePool release]', locations = 1") + substrs = ["Breakpoint created: 4: name = '-[NSAutoreleasePool release]', locations = 1"]) self.runCmd("run", RUN_SUCCEEDED) Modified: lldb/trunk/test/foundation/TestObjCMethods.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/foundation/TestObjCMethods.py?rev=116331&r1=116330&r2=116331&view=diff ============================================================================== --- lldb/trunk/test/foundation/TestObjCMethods.py (original) +++ lldb/trunk/test/foundation/TestObjCMethods.py Tue Oct 12 14:29:49 2010 @@ -44,7 +44,7 @@ # Stop at +[NSString stringWithFormat:]. self.expect("regexp-break +[NSString stringWithFormat:]", BREAKPOINT_CREATED, - startstr = "Breakpoint created: 1: name = '+[NSString stringWithFormat:]', locations = 1") + substrs = ["Breakpoint created: 1: name = '+[NSString stringWithFormat:]', locations = 1"]) # Stop at -[MyString initWithNSString:]. self.expect("breakpoint set -n '-[MyString initWithNSString:]'", BREAKPOINT_CREATED, @@ -56,7 +56,7 @@ # Stop at -[NSAutoreleasePool release]. self.expect("regexp-break -[NSAutoreleasePool release]", BREAKPOINT_CREATED, - startstr = "Breakpoint created: 4: name = '-[NSAutoreleasePool release]', locations = 1") + substrs = ["Breakpoint created: 4: name = '-[NSAutoreleasePool release]', locations = 1"]) self.runCmd("run", RUN_SUCCEEDED) From johnny.chen at apple.com Tue Oct 12 16:20:11 2010 From: johnny.chen at apple.com (Johnny Chen) Date: Tue, 12 Oct 2010 21:20:11 -0000 Subject: [Lldb-commits] [lldb] r116337 - /lldb/trunk/test/foundation/TestObjCMethods.py Message-ID: <20101012212011.916DE2A6C12C@llvm.org> Author: johnny Date: Tue Oct 12 16:20:11 2010 New Revision: 116337 URL: http://llvm.org/viewvc/llvm-project?rev=116337&view=rev Log: Update the @expectedFailure decorator with additional bug info: rdar://problem/8542091 test/foundation: expr -o -- my not working? Add an additional test for 'frame variable *self' when stopped in '-[MyString initWithNSString:]' and move the 'expr -o -- self' to after MyString has been constructed and change it to 'expr -o -- my'. Modified: lldb/trunk/test/foundation/TestObjCMethods.py Modified: lldb/trunk/test/foundation/TestObjCMethods.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/foundation/TestObjCMethods.py?rev=116337&r1=116336&r2=116337&view=diff ============================================================================== --- lldb/trunk/test/foundation/TestObjCMethods.py (original) +++ lldb/trunk/test/foundation/TestObjCMethods.py Tue Oct 12 16:20:11 2010 @@ -24,6 +24,7 @@ self.break_on_objc_methods() @unittest2.expectedFailure + # rdar://problem/8542091 # rdar://problem/8492646 def test_data_type_and_expr_with_dsym(self): """Lookup objective-c data types and evaluate expressions.""" @@ -31,6 +32,7 @@ self.data_type_and_expr_objc() @unittest2.expectedFailure + # rdar://problem/8542091 # rdar://problem/8492646 def test_data_type_and_expr_with_dwarf(self): """Lookup objective-c data types and evaluate expressions.""" @@ -82,6 +84,11 @@ self.expect("thread backtrace", "Stop at -[NSAutoreleasePool release]", substrs = ["Foundation`-[NSAutoreleasePool release]"]) + def setUp(self): + super(FoundationTestCase, self).setUp() + # Find the line number to break inside main(). + self.line = line_number('main.m', '// Set break point at this line.') + def data_type_and_expr_objc(self): """Lookup objective-c data types and evaluate expressions.""" exe = os.path.join(os.getcwd(), "a.out") @@ -101,26 +108,19 @@ self.expect("image lookup -t NSString", DATA_TYPES_DISPLAYED_CORRECTLY, substrs = ['name = "NSString"', - 'clang_type = "@interface NSString at end"']) + 'clang_type = "@interface NSString']) self.expect("image lookup -t MyString", DATA_TYPES_DISPLAYED_CORRECTLY, substrs = ['name = "MyString"', - 'clang_type = "@interface MyString']) + 'clang_type = "@interface MyString', + 'NSString * str;', + 'NSDate * date;']) self.expect("frame variable -s", VARIABLES_DISPLAYED_CORRECTLY, substrs = ["ARG: (MyString *) self"], patterns = ["ARG: \(.*\) _cmd", "(struct objc_selector *)|(SEL)"]) - # Test new feature with r115115: - # Add "-o" option to "expression" which prints the object description if available. - self.expect("expr -o -- self", "Object description displayed correctly", - startstr = "Hello from ", - substrs = ["a.out", "with timestamp: "]) - - self.expect("expr self->non_existent_member", COMMAND_FAILED_AS_EXPECTED, error=True, - startstr = "error: 'MyString' does not have a member named 'non_existent_member'") - # rdar://problem/8492646 # test/foundation fails after updating to tot r115023 # self->str displays nothing as output @@ -132,18 +132,48 @@ self.expect("frame variable self->date", VARIABLES_DISPLAYED_CORRECTLY, startstr = "(NSDate *) self->date") - # TODO: use expression parser. - # self.runCmd("expr self->str") - # self.runCmd("expr self->date") + # This should display the str and date member fields as well. + self.expect("frame variable *self", VARIABLES_DISPLAYED_CORRECTLY, + substrs = ["(MyString *) self", + "(NSString *) str", + "(NSDate *) date"]) + + # This should fail expectedly. + self.expect("expr self->non_existent_member", COMMAND_FAILED_AS_EXPECTED, error=True, + startstr = "error: 'MyString' does not have a member named 'non_existent_member'") + + # This currently fails. + # rdar://problem/8492646 + # + # Use expression parser. + #self.runCmd("expr self->str") + #self.runCmd("expr self->date") # (lldb) expr self->str - # error: 'MyString' does not have a member named 'str' + # error: instance variable 'str' is protected # error: 1 errors parsing expression - # Couldn't parse the expresssion + # # (lldb) expr self->date - # error: 'MyString' does not have a member named 'date' + # error: instance variable 'date' is protected # error: 1 errors parsing expression - # Couldn't parse the expresssion + # + + self.runCmd("breakpoint delete") + self.expect("breakpoint set -f main.m -l %d" % self.line, + BREAKPOINT_CREATED, + startstr = "Breakpoint created: 2: file ='main.m', line = %d, locations = 1" % + self.line) + self.runCmd("process continue") + + # This currently fails. + # rdar://problem/8542091 + # test/foundation: expr -o -- my not working? + # + # Test new feature with r115115: + # Add "-o" option to "expression" which prints the object description if available. + self.expect("expr -o -- my", "Object description displayed correctly", + startstr = "Hello from ", + substrs = ["a.out", "with timestamp: "]) if __name__ == '__main__': From johnny.chen at apple.com Tue Oct 12 16:24:25 2010 From: johnny.chen at apple.com (Johnny Chen) Date: Tue, 12 Oct 2010 21:24:25 -0000 Subject: [Lldb-commits] [lldb] r116340 - /lldb/trunk/test/foundation/main.m Message-ID: <20101012212425.9BB372A6C12C@llvm.org> Author: johnny Date: Tue Oct 12 16:24:25 2010 New Revision: 116340 URL: http://llvm.org/viewvc/llvm-project?rev=116340&view=rev Log: Forgor to also check in this change with r116337. Modified: lldb/trunk/test/foundation/main.m Modified: lldb/trunk/test/foundation/main.m URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/foundation/main.m?rev=116340&r1=116339&r2=116340&view=diff ============================================================================== --- lldb/trunk/test/foundation/main.m (original) +++ lldb/trunk/test/foundation/main.m Tue Oct 12 16:24:25 2010 @@ -38,7 +38,7 @@ MyString *my = [[MyString alloc] initWithNSString:str]; NSLog(@"MyString instance: %@", [my description]); - id str_id = str; + id str_id = str; // Set break point at this line. SEL sel = @selector(length); BOOL responds = [str respondsToSelector:sel]; printf("sizeof(id) = %zu\n", sizeof(id)); From johnny.chen at apple.com Tue Oct 12 16:35:54 2010 From: johnny.chen at apple.com (Johnny Chen) Date: Tue, 12 Oct 2010 21:35:54 -0000 Subject: [Lldb-commits] [lldb] r116341 - in /lldb/trunk: examples/test/.lldbtest-config test/dotest.py Message-ID: <20101012213555.08BD22A6C12C@llvm.org> Author: johnny Date: Tue Oct 12 16:35:54 2010 New Revision: 116341 URL: http://llvm.org/viewvc/llvm-project?rev=116341&view=rev Log: Added the capability for the test driver to split the sys.stderr/sys.stdout into different configuration-based files using the config file. For example: sys.stderr = open("/tmp/lldbtest-stderr", "w") sys.stdout = open("/tmp/lldbtest-stdout", "w") compilers = ["gcc", "llvm-gcc"] archs = ["x86_64", "i386"] split_stderr = True # This will split the stderr into configuration-specific file split_stdout = True # This will split the stdout into configuration-specific file will produce: /tmp/lldbtest-stderr /tmp/lldbtest-stderr.arch=i386-compiler=gcc /tmp/lldbtest-stderr.arch=i386-compiler=llvm-gcc /tmp/lldbtest-stderr.arch=x86_64-compiler=gcc /tmp/lldbtest-stderr.arch=x86_64-compiler=llvm-gcc /tmp/lldbtest-stdout /tmp/lldbtest-stdout.arch=i386-compiler=gcc /tmp/lldbtest-stdout.arch=i386-compiler=llvm-gcc /tmp/lldbtest-stdout.arch=x86_64-compiler=gcc /tmp/lldbtest-stdout.arch=x86_64-compiler=llvm-gcc as a result of splitting stderr and stdout. In addition, each configuration can have its individual top level relocated directory to house the test files as well as the intermediate files by using '-r dir' to relocate the tests into a new relocated directory instead of running the tests in place. Modified: lldb/trunk/examples/test/.lldbtest-config lldb/trunk/test/dotest.py Modified: lldb/trunk/examples/test/.lldbtest-config URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/examples/test/.lldbtest-config?rev=116341&r1=116340&r2=116341&view=diff ============================================================================== --- lldb/trunk/examples/test/.lldbtest-config (original) +++ lldb/trunk/examples/test/.lldbtest-config Tue Oct 12 16:35:54 2010 @@ -2,4 +2,5 @@ sys.stdout = open("/tmp/lldbtest-stdout", "w") compilers = ["gcc", "llvm-gcc"] archs = ["x86_64", "i386"] - +split_stderr = True # This will split the stderr into configuration-specific file +split_stdout = True # This will split the stdout into configuration-specific file Modified: lldb/trunk/test/dotest.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/dotest.py?rev=116341&r1=116340&r2=116341&view=diff ============================================================================== --- lldb/trunk/test/dotest.py (original) +++ lldb/trunk/test/dotest.py Tue Oct 12 16:35:54 2010 @@ -380,7 +380,7 @@ #print "Filename: '%s' does not match pattern: '%s'" % (name, regexp) continue - # We found a match for our test case. Add it to the suite. + # We found a match for our test. Add it to the suite. # Update the sys.path first. if not sys.path.count(dir): @@ -407,6 +407,7 @@ if fs4all and not filtered: continue + # Add either the filtered test case or the entire test class. if filterspec and filtered: suite.addTests( unittest2.defaultTestLoader.loadTestsFromName(filterspec, module)) @@ -484,12 +485,6 @@ # Now that we have loaded all the test cases, run the whole test suite. # -# First, write out the number of collected test cases. -sys.stderr.write(separator + "\n") -sys.stderr.write("Collected %d test%s\n\n" - % (suite.countTestCases(), - suite.countTestCases() != 1 and "s" or "")) - # For the time being, let's bracket the test runner within the # lldb.SBDebugger.Initialize()/Terminate() pair. import lldb, atexit @@ -523,6 +518,15 @@ if type(compilers) is ListType and len(compilers) >= 1: iterCompilers = True +# Make a shallow copy of sys.path, we need to manipulate the search paths later. +# This is only necessary if we are relocated and with different configurations. +if rdir and (iterArchs or iterCompilers): + old_sys_path = sys.path[:] + old_stderr = sys.stderr + old_stdout = sys.stdout + new_stderr = None + new_stdout = None + for ia in range(len(archs) if iterArchs else 1): archConfig = "" if iterArchs: @@ -535,9 +539,62 @@ else: configString = archConfig - # Invoke the test runner. if iterArchs or iterCompilers: + # If we specified a relocated directory to run the test suite, do + # the extra housekeeping to copy the testdirs to a configStringified + # directory and to update sys.path before invoking the test runner. + # The purpose is to separate the configuration-specific directories + # from each other. + if rdir: + from string import maketrans + from shutil import copytree, ignore_patterns + + # Translate ' ' to '-' for dir name. + tbl = maketrans(' ', '-') + configPostfix = configString.translate(tbl) + newrdir = "%s.%s" % (rdir, configPostfix) + + # Copy the tree to a new directory with postfix name configPostfix. + copytree(rdir, newrdir, ignore=ignore_patterns('*.pyc', '*.o', '*.d')) + + # Check whether we need to split stderr/stdout into configuration + # specific files. + if old_stderr.name != '' and config.get('split_stderr'): + if new_stderr: + new_stderr.close() + new_stderr = open("%s.%s" % (old_stderr.name, configPostfix), "w") + sys.stderr = new_stderr + if old_stdout.name != '' and config.get('split_stderr'): + if new_stdout: + new_stdout.close() + new_stdout = open("%s.%s" % (old_stdout.name, configPostfix), "w") + sys.stdout = new_stdout + + # Update the LLDB_TEST environment variable to reflect new top + # level test directory. + # + # See also lldbtest.TestBase.setUpClass(cls). + if len(testdirs) == 1 and os.path.basename(testdirs[0]) == 'test': + os.environ["LLDB_TEST"] = os.path.join(newrdir, 'test') + else: + os.environ["LLDB_TEST"] = newrdir + + # And update the Python search paths for modules. + sys.path = [x.replace(rdir, newrdir, 1) for x in old_sys_path] + + # Output the configuration. sys.stderr.write("\nConfiguration: " + configString + "\n") + + #print "sys.stderr name is", sys.stderr.name + #print "sys.stdout name is", sys.stdout.name + + # First, write out the number of collected test cases. + sys.stderr.write(separator + "\n") + sys.stderr.write("Collected %d test%s\n\n" + % (suite.countTestCases(), + suite.countTestCases() != 1 and "s" or "")) + + # Invoke the test runner. result = unittest2.TextTestRunner(stream=sys.stderr, verbosity=verbose).run(suite) From johnny.chen at apple.com Tue Oct 12 16:50:36 2010 From: johnny.chen at apple.com (Johnny Chen) Date: Tue, 12 Oct 2010 21:50:36 -0000 Subject: [Lldb-commits] [lldb] r116343 - /lldb/trunk/test/dotest.py Message-ID: <20101012215036.C7CFF2A6C12C@llvm.org> Author: johnny Date: Tue Oct 12 16:50:36 2010 New Revision: 116343 URL: http://llvm.org/viewvc/llvm-project?rev=116343&view=rev Log: Fix an obvious cut-and-paste error. 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=116343&r1=116342&r2=116343&view=diff ============================================================================== --- lldb/trunk/test/dotest.py (original) +++ lldb/trunk/test/dotest.py Tue Oct 12 16:50:36 2010 @@ -564,7 +564,7 @@ new_stderr.close() new_stderr = open("%s.%s" % (old_stderr.name, configPostfix), "w") sys.stderr = new_stderr - if old_stdout.name != '' and config.get('split_stderr'): + if old_stdout.name != '' and config.get('split_stdout'): if new_stdout: new_stdout.close() new_stdout = open("%s.%s" % (old_stdout.name, configPostfix), "w") From johnny.chen at apple.com Tue Oct 12 16:52:30 2010 From: johnny.chen at apple.com (Johnny Chen) Date: Tue, 12 Oct 2010 21:52:30 -0000 Subject: [Lldb-commits] [lldb] r116344 - in /lldb/trunk/test/breakpoint_command: TestBreakpointCommand.py main.c Message-ID: <20101012215230.229082A6C12C@llvm.org> Author: johnny Date: Tue Oct 12 16:52:29 2010 New Revision: 116344 URL: http://llvm.org/viewvc/llvm-project?rev=116344&view=rev Log: Avoid using hardcoded line number to break on. Use the line_number() utility function to get the line number to break on during setUp(). Modified: lldb/trunk/test/breakpoint_command/TestBreakpointCommand.py lldb/trunk/test/breakpoint_command/main.c Modified: lldb/trunk/test/breakpoint_command/TestBreakpointCommand.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/breakpoint_command/TestBreakpointCommand.py?rev=116344&r1=116343&r2=116344&view=diff ============================================================================== --- lldb/trunk/test/breakpoint_command/TestBreakpointCommand.py (original) +++ lldb/trunk/test/breakpoint_command/TestBreakpointCommand.py Tue Oct 12 16:52:29 2010 @@ -26,16 +26,25 @@ self.buildDwarf() self.breakpoint_command_sequence() + def setUp(self): + super(BreakpointCommandTestCase, self).setUp() + # Find the line number to break inside main(). + self.line = line_number('main.c', '// Set break point at this line.') + def breakpoint_command_sequence(self): """Test a sequence of breakpoint command add, list, and remove.""" exe = os.path.join(os.getcwd(), "a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Add two breakpoints on the same line. - self.expect("breakpoint set -f main.c -l 12", BREAKPOINT_CREATED, - startstr = "Breakpoint created: 1: file ='main.c', line = 12, locations = 1") - self.expect("breakpoint set -f main.c -l 12", BREAKPOINT_CREATED, - startstr = "Breakpoint created: 2: file ='main.c', line = 12, locations = 1") + self.expect("breakpoint set -f main.c -l %d" % self.line, + BREAKPOINT_CREATED, + startstr = "Breakpoint created: 1: file ='main.c', line = %d, locations = 1" % + self.line) + self.expect("breakpoint set -f main.c -l %d" % self.line, + BREAKPOINT_CREATED, + startstr = "Breakpoint created: 2: file ='main.c', line = %d, locations = 1" % + self.line) # Now add callbacks for the breakpoints just created. self.runCmd("breakpoint command add -c -o 'frame variable -s' 1") @@ -45,10 +54,10 @@ # The breakpoint list now only contains breakpoint 1. self.expect("breakpoint list", "Breakpoints 1 & 2 created", - substrs = ["1: file ='main.c', line = 12, locations = 1", - "2: file ='main.c', line = 12, locations = 1"], - patterns = ["1.1: .+at main.c:12, .+unresolved, hit count = 0", - "2.1: .+at main.c:12, .+unresolved, hit count = 0"]) + substrs = ["1: file ='main.c', line = %d, locations = 1" % self.line, + "2: file ='main.c', line = %d, locations = 1" % self.line], + patterns = ["1.1: .+at main.c:%d, .+unresolved, hit count = 0" % self.line, + "2.1: .+at main.c:%d, .+unresolved, hit count = 0" % self.line]) self.expect("breakpoint command list 1", "Breakpoint 1 command ok", substrs = ["Breakpoint commands:", @@ -87,12 +96,14 @@ # The breakpoint list now only contains breakpoint 1. self.expect("breakpoint list", "Breakpoint 1 exists", - substrs = ["1: file ='main.c', line = 12, locations = 1, resolved = 1", + substrs = ["1: file ='main.c', line = %d, locations = 1, resolved = 1" % + self.line, "hit count = 1"]) # Not breakpoint 2. self.expect("breakpoint list", "No more breakpoint 2", matching=False, - substrs = ["2: file ='main.c', line = 12, locations = 1, resolved = 1"]) + substrs = ["2: file ='main.c', line = %d, locations = 1, resolved = 1" % + self.line]) # Run the program again, with breakpoint 1 remaining. self.runCmd("run", RUN_SUCCEEDED) Modified: lldb/trunk/test/breakpoint_command/main.c URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/breakpoint_command/main.c?rev=116344&r1=116343&r2=116344&view=diff ============================================================================== --- lldb/trunk/test/breakpoint_command/main.c (original) +++ lldb/trunk/test/breakpoint_command/main.c Tue Oct 12 16:52:29 2010 @@ -9,5 +9,5 @@ int main (int argc, char const *argv[]) { - return 0; + return 0; // Set break point at this line. } From ctice at apple.com Tue Oct 12 16:57:09 2010 From: ctice at apple.com (Caroline Tice) Date: Tue, 12 Oct 2010 21:57:09 -0000 Subject: [Lldb-commits] [lldb] r116345 - in /lldb/trunk: scripts/Python/append-debugger-id.py source/Breakpoint/BreakpointIDList.cpp source/Interpreter/CommandInterpreter.cpp tools/driver/Driver.cpp Message-ID: <20101012215709.8A0112A6C12C@llvm.org> Author: ctice Date: Tue Oct 12 16:57:09 2010 New Revision: 116345 URL: http://llvm.org/viewvc/llvm-project?rev=116345&view=rev Log: Fix some memory leaks. Add call to lldb.SBDebugger.Initialize() to lldb.py, so it automatically gets called when the lldb Python module gets loaded. Modified: lldb/trunk/scripts/Python/append-debugger-id.py lldb/trunk/source/Breakpoint/BreakpointIDList.cpp lldb/trunk/source/Interpreter/CommandInterpreter.cpp lldb/trunk/tools/driver/Driver.cpp Modified: lldb/trunk/scripts/Python/append-debugger-id.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/scripts/Python/append-debugger-id.py?rev=116345&r1=116344&r2=116345&view=diff ============================================================================== --- lldb/trunk/scripts/Python/append-debugger-id.py (original) +++ lldb/trunk/scripts/Python/append-debugger-id.py Tue Oct 12 16:57:09 2010 @@ -21,6 +21,7 @@ print "Error: Unable to open file for appending: " + output_name else: f_out.write ("debugger_unique_id = 0\n"); + f_out.write ("lldb.SBDebugger.Initialize()\n"); try: f_out.close() except IOError: Modified: lldb/trunk/source/Breakpoint/BreakpointIDList.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Breakpoint/BreakpointIDList.cpp?rev=116345&r1=116344&r2=116345&view=diff ============================================================================== --- lldb/trunk/source/Breakpoint/BreakpointIDList.cpp (original) +++ lldb/trunk/source/Breakpoint/BreakpointIDList.cpp Tue Oct 12 16:57:09 2010 @@ -181,7 +181,6 @@ if (BreakpointIDList::StringContainsIDRangeExpression (current_arg, &range_start_len, &range_end_pos)) { is_range = true; - range_start = (char *) malloc (range_start_len + 1); range_start.assign (current_arg, range_start_len); range_end = current_arg + range_end_pos; } Modified: lldb/trunk/source/Interpreter/CommandInterpreter.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Interpreter/CommandInterpreter.cpp?rev=116345&r1=116344&r2=116345&view=diff ============================================================================== --- lldb/trunk/source/Interpreter/CommandInterpreter.cpp (original) +++ lldb/trunk/source/Interpreter/CommandInterpreter.cpp Tue Oct 12 16:57:09 2010 @@ -8,6 +8,7 @@ //===----------------------------------------------------------------------===// #include +#include #include #include @@ -947,13 +948,10 @@ } void -CommandInterpreter::BuildAliasCommandArgs -( - CommandObject *alias_cmd_obj, - const char *alias_name, - Args &cmd_args, - CommandReturnObject &result -) +CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj, + const char *alias_name, + Args &cmd_args, + CommandReturnObject &result) { OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name); @@ -970,10 +968,9 @@ OptionArgVector *option_arg_vector = option_arg_vector_sp.get(); int old_size = cmd_args.GetArgumentCount(); - int *used = (int *) malloc ((old_size + 1) * sizeof (int)); - - memset (used, 0, (old_size + 1) * sizeof (int)); - used[0] = 1; + std::vector used (old_size + 1, false); + + used[0] = true; for (int i = 0; i < option_arg_vector->size(); ++i) { @@ -1002,7 +999,7 @@ else { new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index)); - used[index] = 1; + used[index] = true; } } } Modified: lldb/trunk/tools/driver/Driver.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/driver/Driver.cpp?rev=116345&r1=116344&r2=116345&view=diff ============================================================================== --- lldb/trunk/tools/driver/Driver.cpp (original) +++ lldb/trunk/tools/driver/Driver.cpp Tue Oct 12 16:57:09 2010 @@ -332,7 +332,8 @@ } void -BuildGetOptTable (lldb::OptionDefinition *expanded_option_table, struct option **getopt_table, uint32_t num_options) +BuildGetOptTable (lldb::OptionDefinition *expanded_option_table, std::vector &getopt_table, + uint32_t num_options) { if (num_options == 0) return; @@ -341,25 +342,27 @@ uint32_t j; std::bitset<256> option_seen; + getopt_table.resize (num_options + 1); + for (i = 0, j = 0; i < num_options; ++i) { char short_opt = expanded_option_table[i].short_option; if (option_seen.test(short_opt) == false) { - (*getopt_table)[j].name = expanded_option_table[i].long_option; - (*getopt_table)[j].has_arg = expanded_option_table[i].option_has_arg; - (*getopt_table)[j].flag = NULL; - (*getopt_table)[j].val = expanded_option_table[i].short_option; + getopt_table[j].name = expanded_option_table[i].long_option; + getopt_table[j].has_arg = expanded_option_table[i].option_has_arg; + getopt_table[j].flag = NULL; + getopt_table[j].val = expanded_option_table[i].short_option; option_seen.set(short_opt); ++j; } } - (*getopt_table)[j].name = NULL; - (*getopt_table)[j].has_arg = 0; - (*getopt_table)[j].flag = NULL; - (*getopt_table)[j].val = 0; + getopt_table[j].name = NULL; + getopt_table[j].has_arg = 0; + getopt_table[j].flag = NULL; + getopt_table[j].val = 0; } @@ -456,6 +459,7 @@ SBError error; std::string option_string; struct option *long_options = NULL; + std::vector long_options_vector; uint32_t num_options; for (num_options = 0; g_options[num_options].long_option != NULL; ++num_options) @@ -468,9 +472,12 @@ return error; } - long_options = (struct option *) malloc ((num_options + 1) * sizeof (struct option)); + BuildGetOptTable (g_options, long_options_vector, num_options); - BuildGetOptTable (g_options, &long_options, num_options); + if (long_options_vector.empty()) + long_options = NULL; + else + long_options = &long_options_vector.front(); if (long_options == NULL) { @@ -625,7 +632,9 @@ error.SetErrorStringWithFormat ("invalid option with value %i", val); } if (error.Fail()) + { return error; + } } } From johnny.chen at apple.com Tue Oct 12 16:57:42 2010 From: johnny.chen at apple.com (Johnny Chen) Date: Tue, 12 Oct 2010 21:57:42 -0000 Subject: [Lldb-commits] [lldb] r116346 - in /lldb/trunk/test/breakpoint_locations: TestBreakpointLocations.py main.c Message-ID: <20101012215742.568932A6C12C@llvm.org> Author: johnny Date: Tue Oct 12 16:57:42 2010 New Revision: 116346 URL: http://llvm.org/viewvc/llvm-project?rev=116346&view=rev Log: Avoid using hardcoded line number to break on. Use the line_number() utility function to get the line number to break on during setUp(). Modified: lldb/trunk/test/breakpoint_locations/TestBreakpointLocations.py lldb/trunk/test/breakpoint_locations/main.c Modified: lldb/trunk/test/breakpoint_locations/TestBreakpointLocations.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/breakpoint_locations/TestBreakpointLocations.py?rev=116346&r1=116345&r2=116346&view=diff ============================================================================== --- lldb/trunk/test/breakpoint_locations/TestBreakpointLocations.py (original) +++ lldb/trunk/test/breakpoint_locations/TestBreakpointLocations.py Tue Oct 12 16:57:42 2010 @@ -22,18 +22,25 @@ self.buildDwarf() self.breakpoint_locations_test() + def setUp(self): + super(BreakpointLocationsTestCase, self).setUp() + # Find the line number to break inside main(). + self.line = line_number('main.c', '// Set break point at this line.') + def breakpoint_locations_test(self): """Test breakpoint enable/disable for a breakpoint ID with multiple locations.""" exe = os.path.join(os.getcwd(), "a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # This should create a breakpoint with 3 locations. - self.expect("breakpoint set -f main.c -l 19", BREAKPOINT_CREATED, - startstr = "Breakpoint created: 1: file ='main.c', line = 19, locations = 3") + self.expect("breakpoint set -f main.c -l %d" % self.line, + BREAKPOINT_CREATED, + startstr = "Breakpoint created: 1: file ='main.c', line = %d, locations = 3" % + self.line) # The breakpoint list should show 3 locations. self.expect("breakpoint list", "Breakpoint locations shown correctly", - substrs = ["1: file ='main.c', line = 19, locations = 3"], + substrs = ["1: file ='main.c', line = %d, locations = 3" % self.line], patterns = ["where = a.out`func_inlined .+unresolved, hit count = 0", "where = a.out`main .+\[inlined\].+unresolved, hit count = 0"]) Modified: lldb/trunk/test/breakpoint_locations/main.c URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/breakpoint_locations/main.c?rev=116346&r1=116345&r2=116346&view=diff ============================================================================== --- lldb/trunk/test/breakpoint_locations/main.c (original) +++ lldb/trunk/test/breakpoint_locations/main.c Tue Oct 12 16:57:42 2010 @@ -16,7 +16,7 @@ printf ("Called func_inlined.\n"); ++func_inline_call_count; printf ("Returning func_inlined call count: %d.\n", func_inline_call_count); - return func_inline_call_count; + return func_inline_call_count; // Set break point at this line. } extern int func_inlined (void); From johnny.chen at apple.com Tue Oct 12 17:09:54 2010 From: johnny.chen at apple.com (Johnny Chen) Date: Tue, 12 Oct 2010 22:09:54 -0000 Subject: [Lldb-commits] [lldb] r116349 - in /lldb/trunk/test/class_types: TestClassTypes.py TestClassTypesDisassembly.py main.cpp Message-ID: <20101012220954.D7F482A6C12C@llvm.org> Author: johnny Date: Tue Oct 12 17:09:54 2010 New Revision: 116349 URL: http://llvm.org/viewvc/llvm-project?rev=116349&view=rev Log: Avoid using hardcoded line number to break on. Use the line_number() utility function to get the line number to break on during setUp(). Modified: lldb/trunk/test/class_types/TestClassTypes.py lldb/trunk/test/class_types/TestClassTypesDisassembly.py lldb/trunk/test/class_types/main.cpp Modified: lldb/trunk/test/class_types/TestClassTypes.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/class_types/TestClassTypes.py?rev=116349&r1=116348&r2=116349&view=diff ============================================================================== --- lldb/trunk/test/class_types/TestClassTypes.py (original) +++ lldb/trunk/test/class_types/TestClassTypes.py Tue Oct 12 17:09:54 2010 @@ -46,14 +46,21 @@ self.buildDwarf() self.class_types_expr_parser() + def setUp(self): + super(ClassTypesTestCase, self).setUp() + # Find the line number to break for main.cpp. + self.line = line_number('main.cpp', '// Set break point at this line.') + def class_types(self): """Test 'frame variable this' when stopped on a class constructor.""" exe = os.path.join(os.getcwd(), "a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Break on the ctor function of class C. - self.expect("breakpoint set -f main.cpp -l 93", BREAKPOINT_CREATED, - startstr = "Breakpoint created: 1: file ='main.cpp', line = 93") + self.expect("breakpoint set -f main.cpp -l %d" % self.line, + BREAKPOINT_CREATED, + startstr = "Breakpoint created: 1: file ='main.cpp', line = %d" % + self.line) self.runCmd("run", RUN_SUCCEEDED) @@ -96,13 +103,13 @@ bpfilespec = lldb.SBFileSpec("main.cpp") - breakpoint = target.BreakpointCreateByLocation(bpfilespec, 93) + breakpoint = target.BreakpointCreateByLocation(bpfilespec, self.line) self.assertTrue(breakpoint.IsValid(), VALID_BREAKPOINT) # Verify the breakpoint just created. self.expect(repr(breakpoint), BREAKPOINT_CREATED, exe=False, substrs = ['main.cpp', - '93']) + str(self.line)]) # Now launch the process, and do not stop at entry point. rc = lldb.SBError() @@ -127,7 +134,7 @@ # should be 93. self.expect("%s:%d" % (lldbutil.GetFilenames(thread)[0], lldbutil.GetLineNumbers(thread)[0]), - "Break correctly at main.cpp:93", exe=False, + "Break correctly at main.cpp:%d" % self.line, exe=False, startstr = "main.cpp:") ### clang compiled code reported main.cpp:94? ### startstr = "main.cpp:93") Modified: lldb/trunk/test/class_types/TestClassTypesDisassembly.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/class_types/TestClassTypesDisassembly.py?rev=116349&r1=116348&r2=116349&view=diff ============================================================================== --- lldb/trunk/test/class_types/TestClassTypesDisassembly.py (original) +++ lldb/trunk/test/class_types/TestClassTypesDisassembly.py Tue Oct 12 17:09:54 2010 @@ -33,14 +33,21 @@ self.buildDwarf() self.disassemble_call_stack_api() + def setUp(self): + super(IterateFrameAndDisassembleTestCase, self).setUp() + # Find the line number to break for main.cpp. + self.line = line_number('main.cpp', '// Set break point at this line.') + def breakOnCtor(self): """Setup/run the program so it stops on C's constructor.""" exe = os.path.join(os.getcwd(), "a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Break on the ctor function of class C. - self.expect("breakpoint set -f main.cpp -l 93", BREAKPOINT_CREATED, - startstr = "Breakpoint created: 1: file ='main.cpp', line = 93") + self.expect("breakpoint set -f main.cpp -l %d" % self.line, + BREAKPOINT_CREATED, + startstr = "Breakpoint created: 1: file ='main.cpp', line = %d" % + self.line) self.runCmd("run", RUN_SUCCEEDED) Modified: lldb/trunk/test/class_types/main.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/class_types/main.cpp?rev=116349&r1=116348&r2=116349&view=diff ============================================================================== --- lldb/trunk/test/class_types/main.cpp (original) +++ lldb/trunk/test/class_types/main.cpp Tue Oct 12 17:09:54 2010 @@ -90,7 +90,7 @@ B(ai, bi), m_c_int(ci) { - printf("Within C::ctor() m_c_int=%d\n", m_c_int); + printf("Within C::ctor() m_c_int=%d\n", m_c_int); // Set break point at this line. } //virtual From johnny.chen at apple.com Tue Oct 12 17:14:43 2010 From: johnny.chen at apple.com (Johnny Chen) Date: Tue, 12 Oct 2010 22:14:43 -0000 Subject: [Lldb-commits] [lldb] r116350 - in /lldb/trunk/test/enum_types: TestEnumTypes.py main.c Message-ID: <20101012221443.8176F2A6C12C@llvm.org> Author: johnny Date: Tue Oct 12 17:14:43 2010 New Revision: 116350 URL: http://llvm.org/viewvc/llvm-project?rev=116350&view=rev Log: Avoid using hardcoded line number to break on. Use the line_number() utility function to get the line number to break on during setUp(). Modified: lldb/trunk/test/enum_types/TestEnumTypes.py lldb/trunk/test/enum_types/main.c Modified: lldb/trunk/test/enum_types/TestEnumTypes.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/enum_types/TestEnumTypes.py?rev=116350&r1=116349&r2=116350&view=diff ============================================================================== --- lldb/trunk/test/enum_types/TestEnumTypes.py (original) +++ lldb/trunk/test/enum_types/TestEnumTypes.py Tue Oct 12 17:14:43 2010 @@ -22,14 +22,21 @@ self.buildDwarf() self.image_lookup_for_enum_type() + def setUp(self): + super(EnumTypesTestCase, self).setUp() + # Find the line number to break inside main(). + self.line = line_number('main.c', '// Set break point at this line.') + def image_lookup_for_enum_type(self): """Test 'image lookup -t days' and check for correct display.""" exe = os.path.join(os.getcwd(), "a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Break inside the main. - self.expect("breakpoint set -f main.c -l 26", BREAKPOINT_CREATED, - startstr = "Breakpoint created: 1: file ='main.c', line = 26, locations = 1") + self.expect("breakpoint set -f main.c -l %d" % self.line, + BREAKPOINT_CREATED, + startstr = "Breakpoint created: 1: file ='main.c', line = %d, locations = 1" % + self.line) self.runCmd("run", RUN_SUCCEEDED) Modified: lldb/trunk/test/enum_types/main.c URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/enum_types/main.c?rev=116350&r1=116349&r2=116350&view=diff ============================================================================== --- lldb/trunk/test/enum_types/main.c (original) +++ lldb/trunk/test/enum_types/main.c Tue Oct 12 17:14:43 2010 @@ -23,7 +23,7 @@ enum days day; for (day = Monday - 1; day <= kNumDays + 1; day++) { - printf("day as int is %i\n", (int)day); + printf("day as int is %i\n", (int)day); // Set break point at this line. } return 0; } From ctice at apple.com Tue Oct 12 17:16:53 2010 From: ctice at apple.com (Caroline Tice) Date: Tue, 12 Oct 2010 22:16:53 -0000 Subject: [Lldb-commits] [lldb] r116351 - /lldb/trunk/source/Interpreter/CommandObject.cpp Message-ID: <20101012221653.4D00F2A6C12C@llvm.org> Author: ctice Date: Tue Oct 12 17:16:53 2010 New Revision: 116351 URL: http://llvm.org/viewvc/llvm-project?rev=116351&view=rev Log: Replace contains_string with 'strcasestr' from libc. Modified: lldb/trunk/source/Interpreter/CommandObject.cpp Modified: lldb/trunk/source/Interpreter/CommandObject.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Interpreter/CommandObject.cpp?rev=116351&r1=116350&r2=116351&view=diff ============================================================================== --- lldb/trunk/source/Interpreter/CommandObject.cpp (original) +++ lldb/trunk/source/Interpreter/CommandObject.cpp Tue Oct 12 17:16:53 2010 @@ -380,35 +380,6 @@ } } -// Case insensitive version of ::strstr() -// Returns true if s2 is contained within s1. - -static bool -contains_string (const char *s1, const char *s2) -{ - char *locase_s1 = (char *) malloc (strlen (s1) + 1); - char *locase_s2 = (char *) malloc (strlen (s2) + 1); - int i; - for (i = 0; s1 && s1[i] != '\0'; i++) - locase_s1[i] = ::tolower (s1[i]); - locase_s1[i] = '\0'; - for (i = 0; s2 && s2[i] != '\0'; i++) - locase_s2[i] = ::tolower (s2[i]); - locase_s2[i] = '\0'; - - const char *result = ::strstr (locase_s1, locase_s2); - free (locase_s1); - free (locase_s2); - // 'result' points into freed memory - but we're not - // deref'ing it so hopefully current/future compilers - // won't complain.. - - if (result == NULL) - return false; - else - return true; -} - bool CommandObject::HelpTextContainsWord (const char *search_word) { @@ -424,11 +395,11 @@ long_help = GetHelpLong(); syntax_help = GetSyntax(); - if (contains_string (short_help, search_word)) + if (strcasestr (short_help, search_word)) found_word = true; - else if (contains_string (long_help, search_word)) + else if (strcasestr (long_help, search_word)) found_word = true; - else if (contains_string (syntax_help, search_word)) + else if (strcasestr (syntax_help, search_word)) found_word = true; if (!found_word @@ -439,7 +410,7 @@ if (usage_help.GetSize() > 0) { const char *usage_text = usage_help.GetData(); - if (contains_string (usage_text, search_word)) + if (strcasestr (usage_text, search_word)) found_word = true; } } From johnny.chen at apple.com Tue Oct 12 17:19:26 2010 From: johnny.chen at apple.com (Johnny Chen) Date: Tue, 12 Oct 2010 22:19:26 -0000 Subject: [Lldb-commits] [lldb] r116352 - in /lldb/trunk/test/function_types: TestFunctionTypes.py main.c Message-ID: <20101012221926.485A02A6C12C@llvm.org> Author: johnny Date: Tue Oct 12 17:19:26 2010 New Revision: 116352 URL: http://llvm.org/viewvc/llvm-project?rev=116352&view=rev Log: Avoid using hardcoded line number to break on. Use the line_number() utility function to get the line number to break on during setUp(). Modified: lldb/trunk/test/function_types/TestFunctionTypes.py lldb/trunk/test/function_types/main.c Modified: lldb/trunk/test/function_types/TestFunctionTypes.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/function_types/TestFunctionTypes.py?rev=116352&r1=116351&r2=116352&view=diff ============================================================================== --- lldb/trunk/test/function_types/TestFunctionTypes.py (original) +++ lldb/trunk/test/function_types/TestFunctionTypes.py Tue Oct 12 17:19:26 2010 @@ -20,14 +20,21 @@ self.buildDwarf() self.function_types() + def setUp(self): + super(FunctionTypesTestCase, self).setUp() + # Find the line number to break inside main(). + self.line = line_number('main.c', '// Set break point at this line.') + def function_types(self): """Test 'callback' has function ptr type, then break on the function.""" exe = os.path.join(os.getcwd(), "a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Break inside the main. - self.expect("breakpoint set -f main.c -l 21", BREAKPOINT_CREATED, - startstr = "Breakpoint created: 1: file ='main.c', line = 21, locations = 1") + self.expect("breakpoint set -f main.c -l %d" % self.line, + BREAKPOINT_CREATED, + startstr = "Breakpoint created: 1: file ='main.c', line = %d, locations = 1" % + self.line) self.runCmd("run", RUN_SUCCEEDED) Modified: lldb/trunk/test/function_types/main.c URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/function_types/main.c?rev=116352&r1=116351&r2=116352&view=diff ============================================================================== --- lldb/trunk/test/function_types/main.c (original) +++ lldb/trunk/test/function_types/main.c Tue Oct 12 17:19:26 2010 @@ -18,5 +18,5 @@ { int (*callback)(const char *) = string_not_empty; - return callback(0); + return callback(0); // Set break point at this line. } From johnny.chen at apple.com Tue Oct 12 17:35:26 2010 From: johnny.chen at apple.com (Johnny Chen) Date: Tue, 12 Oct 2010 22:35:26 -0000 Subject: [Lldb-commits] [lldb] r116355 - in /lldb/trunk/test/global_variables: TestGlobalVariables.py main.c Message-ID: <20101012223526.A08362A6C12C@llvm.org> Author: johnny Date: Tue Oct 12 17:35:26 2010 New Revision: 116355 URL: http://llvm.org/viewvc/llvm-project?rev=116355&view=rev Log: Avoid using hardcoded line number to break on. Use the line_number() utility function to get the line number to break on during setUp(). Also modify main.c to use g_file_static_cstr within main() so clang does not optimize this variable out. Modified: lldb/trunk/test/global_variables/TestGlobalVariables.py lldb/trunk/test/global_variables/main.c Modified: lldb/trunk/test/global_variables/TestGlobalVariables.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/global_variables/TestGlobalVariables.py?rev=116355&r1=116354&r2=116355&view=diff ============================================================================== --- lldb/trunk/test/global_variables/TestGlobalVariables.py (original) +++ lldb/trunk/test/global_variables/TestGlobalVariables.py Tue Oct 12 17:35:26 2010 @@ -20,14 +20,21 @@ self.buildDwarf() self.global_variables() + def setUp(self): + super(GlobalVariablesTestCase, self).setUp() + # Find the line number to break inside main(). + self.line = line_number('main.c', '// Set break point at this line.') + def global_variables(self): """Test 'frame variable -s -a' which omits args and shows scopes.""" exe = os.path.join(os.getcwd(), "a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Break inside the main. - self.expect("breakpoint set -f main.c -l 20", BREAKPOINT_CREATED, - startstr = "Breakpoint created: 1: file ='main.c', line = 20, locations = 1") + self.expect("breakpoint set -f main.c -l %d" % self.line, + BREAKPOINT_CREATED, + startstr = "Breakpoint created: 1: file ='main.c', line = %d, locations = 1" % + self.line) self.runCmd("run", RUN_SUCCEEDED) Modified: lldb/trunk/test/global_variables/main.c URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/global_variables/main.c?rev=116355&r1=116354&r2=116355&view=diff ============================================================================== --- lldb/trunk/test/global_variables/main.c (original) +++ lldb/trunk/test/global_variables/main.c Tue Oct 12 17:35:26 2010 @@ -16,6 +16,6 @@ int main (int argc, char const *argv[]) { static const char *g_func_static_cstr = "g_func_static_cstr"; - printf ("%s\n", g_file_global_cstr); - return g_file_global_int + g_a; //// break $source:$line; continue; var -global g_a -global g_global_int + printf ("%s %s\n", g_file_global_cstr, g_file_static_cstr); + return g_file_global_int + g_a; // Set break point at this line. //// break $source:$line; continue; var -global g_a -global g_global_int } From johnny.chen at apple.com Tue Oct 12 17:39:52 2010 From: johnny.chen at apple.com (Johnny Chen) Date: Tue, 12 Oct 2010 22:39:52 -0000 Subject: [Lldb-commits] [lldb] r116356 - in /lldb/trunk/test/macosx/universal: TestUniversal.py main.c Message-ID: <20101012223952.3E3082A6C12C@llvm.org> Author: johnny Date: Tue Oct 12 17:39:52 2010 New Revision: 116356 URL: http://llvm.org/viewvc/llvm-project?rev=116356&view=rev Log: Avoid using hardcoded line number to break on. Use the line_number() utility function to get the line number to break on during setUp(). Modified: lldb/trunk/test/macosx/universal/TestUniversal.py lldb/trunk/test/macosx/universal/main.c Modified: lldb/trunk/test/macosx/universal/TestUniversal.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/macosx/universal/TestUniversal.py?rev=116356&r1=116355&r2=116356&view=diff ============================================================================== --- lldb/trunk/test/macosx/universal/TestUniversal.py (original) +++ lldb/trunk/test/macosx/universal/TestUniversal.py Tue Oct 12 17:39:52 2010 @@ -9,6 +9,11 @@ mydir = "macosx/universal" + def setUp(self): + super(UniversalTestCase, self).setUp() + # Find the line number to break inside main(). + self.line = line_number('main.c', '// Set break point at this line.') + @unittest2.skipUnless(sys.platform.startswith("darwin") and os.uname()[4]=='i386', "requires Darwin & i386") def test_process_launch_for_universal(self): @@ -26,8 +31,10 @@ substrs = ["testit' (x86_64)."]) # Break inside the main. - self.expect("breakpoint set -f main.c -l 5", BREAKPOINT_CREATED, - startstr = "Breakpoint created: 1: file ='main.c', line = 5, locations = 1") + self.expect("breakpoint set -f main.c -l %d" % self.line, + BREAKPOINT_CREATED, + startstr = "Breakpoint created: 1: file ='main.c', line = %d, locations = 1" % + self.line) # We should be able to launch the x86_64 executable. self.runCmd("run", RUN_SUCCEEDED) @@ -47,8 +54,10 @@ substrs = ["testit' (i386)."]) # Break inside the main. - self.expect("breakpoint set -f main.c -l 5", BREAKPOINT_CREATED, - startstr = "Breakpoint created: 1: file ='main.c', line = 5, locations = 1") + self.expect("breakpoint set -f main.c -l %d" % self.line, + BREAKPOINT_CREATED, + startstr = "Breakpoint created: 1: file ='main.c', line = %d, locations = 1" % + self.line) # We should be able to launch the i386 executable as well. self.runCmd("run", RUN_SUCCEEDED) Modified: lldb/trunk/test/macosx/universal/main.c URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/macosx/universal/main.c?rev=116356&r1=116355&r2=116356&view=diff ============================================================================== --- lldb/trunk/test/macosx/universal/main.c (original) +++ lldb/trunk/test/macosx/universal/main.c Tue Oct 12 17:39:52 2010 @@ -2,6 +2,6 @@ int main (int argc, char **argv) { - printf ("Hello there!\n"); + printf ("Hello there!\n"); // Set break point at this line. return 0; } From ctice at apple.com Tue Oct 12 17:46:01 2010 From: ctice at apple.com (Caroline Tice) Date: Tue, 12 Oct 2010 22:46:01 -0000 Subject: [Lldb-commits] [lldb] r116357 - /lldb/trunk/source/Commands/CommandObjectCommands.cpp Message-ID: <20101012224601.F051D2A6C12C@llvm.org> Author: ctice Date: Tue Oct 12 17:46:01 2010 New Revision: 116357 URL: http://llvm.org/viewvc/llvm-project?rev=116357&view=rev Log: Comment out code that was preventing commands that take raw input strings from being alias-able. Modified: lldb/trunk/source/Commands/CommandObjectCommands.cpp Modified: lldb/trunk/source/Commands/CommandObjectCommands.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Commands/CommandObjectCommands.cpp?rev=116357&r1=116356&r2=116357&view=diff ============================================================================== --- lldb/trunk/source/Commands/CommandObjectCommands.cpp (original) +++ lldb/trunk/source/Commands/CommandObjectCommands.cpp Tue Oct 12 17:46:01 2010 @@ -310,15 +310,15 @@ if (args.GetArgumentCount () > 0) { - if ((!use_subcommand && (cmd_obj->WantsRawCommandString())) - || (use_subcommand && (sub_cmd_obj->WantsRawCommandString()))) - { - result.AppendErrorWithFormat ("'%s' cannot be aliased with any options or arguments.\n", - (use_subcommand ? sub_cmd_obj->GetCommandName() - : cmd_obj->GetCommandName())); - result.SetStatus (eReturnStatusFailed); - return false; - } + //if ((!use_subcommand && (cmd_obj->WantsRawCommandString())) + // || (use_subcommand && (sub_cmd_obj->WantsRawCommandString()))) + //{ + // result.AppendErrorWithFormat ("'%s' cannot be aliased with any options or arguments.\n", + // (use_subcommand ? sub_cmd_obj->GetCommandName() + // : cmd_obj->GetCommandName())); + // result.SetStatus (eReturnStatusFailed); + // return false; + //} // options or arguments have been passed to the alias command, and must be // verified & processed here. From johnny.chen at apple.com Tue Oct 12 17:53:03 2010 From: johnny.chen at apple.com (Johnny Chen) Date: Tue, 12 Oct 2010 22:53:03 -0000 Subject: [Lldb-commits] [lldb] r116358 - in /lldb/trunk/test/stl: TestSTL.py main.cpp Message-ID: <20101012225303.104452A6C12C@llvm.org> Author: johnny Date: Tue Oct 12 17:53:02 2010 New Revision: 116358 URL: http://llvm.org/viewvc/llvm-project?rev=116358&view=rev Log: Avoid using hardcoded line number to break on. Use the line_number() utility function to get the line number to break on during setUp(). Modified: lldb/trunk/test/stl/TestSTL.py lldb/trunk/test/stl/main.cpp Modified: lldb/trunk/test/stl/TestSTL.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/stl/TestSTL.py?rev=116358&r1=116357&r2=116358&view=diff ============================================================================== --- lldb/trunk/test/stl/TestSTL.py (original) +++ lldb/trunk/test/stl/TestSTL.py Tue Oct 12 17:53:02 2010 @@ -22,6 +22,11 @@ self.buildDwarf() self.step_into_stl() + def setUp(self): + super(STLTestCase, self).setUp() + # Find the line number to break inside main(). + self.line = line_number('main.cpp', '// Set break point at this line.') + def step_into_stl(self): """Test that we can successfully step into an STL function.""" exe = os.path.join(os.getcwd(), "a.out") @@ -33,14 +38,16 @@ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Break on line 13 of main.cpp. - self.expect("breakpoint set -f main.cpp -l 13", BREAKPOINT_CREATED, - startstr = "Breakpoint created: 1: file ='main.cpp', line = 13, locations = 1") + self.expect("breakpoint set -f main.cpp -l %d" % self.line, + BREAKPOINT_CREATED, + startstr = "Breakpoint created: 1: file ='main.cpp', line = %d" % + self.line) self.runCmd("run", RUN_SUCCEEDED) # Stop at 'std::string hello_world ("Hello World!");'. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['main.cpp:13', + substrs = ['main.cpp:%d' % self.line, 'stop reason = breakpoint']) # The breakpoint should have a hit count of 1. Modified: lldb/trunk/test/stl/main.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/stl/main.cpp?rev=116358&r1=116357&r2=116358&view=diff ============================================================================== --- lldb/trunk/test/stl/main.cpp (original) +++ lldb/trunk/test/stl/main.cpp Tue Oct 12 17:53:02 2010 @@ -10,6 +10,6 @@ #include int main (int argc, char const *argv[]) { - std::string hello_world ("Hello World!"); + std::string hello_world ("Hello World!"); // Set break point at this line. std::cout << hello_world << std::endl; } From johnny.chen at apple.com Tue Oct 12 18:01:50 2010 From: johnny.chen at apple.com (Johnny Chen) Date: Tue, 12 Oct 2010 23:01:50 -0000 Subject: [Lldb-commits] [lldb] r116361 - /lldb/trunk/test/stl/TestSTL.py Message-ID: <20101012230150.978D92A6C12C@llvm.org> Author: johnny Date: Tue Oct 12 18:01:50 2010 New Revision: 116361 URL: http://llvm.org/viewvc/llvm-project?rev=116361&view=rev Log: Update the comment with reagard to a bug filed against possible clang-generated debug info which results in the breakpoint locations of 3, instead of 1 (as in gcc). Modified: lldb/trunk/test/stl/TestSTL.py Modified: lldb/trunk/test/stl/TestSTL.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/stl/TestSTL.py?rev=116361&r1=116360&r2=116361&view=diff ============================================================================== --- lldb/trunk/test/stl/TestSTL.py (original) +++ lldb/trunk/test/stl/TestSTL.py Tue Oct 12 18:01:50 2010 @@ -37,6 +37,10 @@ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + # rdar://problem/8543077 + # test/stl: clang built binaries results in the breakpoint locations = 3, + # is this a problem with clang generated debug info? + # # Break on line 13 of main.cpp. self.expect("breakpoint set -f main.cpp -l %d" % self.line, BREAKPOINT_CREATED, From johnny.chen at apple.com Tue Oct 12 18:08:18 2010 From: johnny.chen at apple.com (Johnny Chen) Date: Tue, 12 Oct 2010 23:08:18 -0000 Subject: [Lldb-commits] [lldb] r116363 - /lldb/trunk/test/stl/TestStdCXXDisassembly.py Message-ID: <20101012230818.E7F392A6C12C@llvm.org> Author: johnny Date: Tue Oct 12 18:08:18 2010 New Revision: 116363 URL: http://llvm.org/viewvc/llvm-project?rev=116363&view=rev Log: Avoid using hardcoded line number to break on. Use the line_number() utility function to get the line number to break on during setUp(). Modified: lldb/trunk/test/stl/TestStdCXXDisassembly.py Modified: lldb/trunk/test/stl/TestStdCXXDisassembly.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/stl/TestStdCXXDisassembly.py?rev=116363&r1=116362&r2=116363&view=diff ============================================================================== --- lldb/trunk/test/stl/TestStdCXXDisassembly.py (original) +++ lldb/trunk/test/stl/TestStdCXXDisassembly.py Tue Oct 12 18:08:18 2010 @@ -11,6 +11,11 @@ mydir = "stl" + def setUp(self): + super(StdCXXDisassembleTestCase, self).setUp() + # Find the line number to break inside main(). + self.line = line_number('main.cpp', '// Set break point at this line.') + # rdar://problem/8504895 # Crash while doing 'disassemble -n "-[NSNumber descriptionWithLocale:]" @unittest2.skipIf(TestBase.skipLongRunningTest(), "Skip this long running test") @@ -20,9 +25,15 @@ exe = os.path.join(os.getcwd(), "a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + # rdar://problem/8543077 + # test/stl: clang built binaries results in the breakpoint locations = 3, + # is this a problem with clang generated debug info? + # # Break on line 13 of main.cpp. - self.expect("breakpoint set -f main.cpp -l 13", BREAKPOINT_CREATED, - startstr = "Breakpoint created: 1: file ='main.cpp', line = 13, locations = 1") + self.expect("breakpoint set -f main.cpp -l %d" % self.line, + BREAKPOINT_CREATED, + startstr = "Breakpoint created: 1: file ='main.cpp', line = %d" % + self.line) self.runCmd("run", RUN_SUCCEEDED) From johnny.chen at apple.com Tue Oct 12 18:20:04 2010 From: johnny.chen at apple.com (Johnny Chen) Date: Tue, 12 Oct 2010 23:20:04 -0000 Subject: [Lldb-commits] [lldb] r116369 - in /lldb/trunk/test/struct_types: TestStructTypes.py main.c Message-ID: <20101012232004.D96552A6C12C@llvm.org> Author: johnny Date: Tue Oct 12 18:20:04 2010 New Revision: 116369 URL: http://llvm.org/viewvc/llvm-project?rev=116369&view=rev Log: Avoid using hardcoded line number to break on. Use the line_number() utility function to get the line number to break on as well as the line number of the first executable statement during setUp(). Modified: lldb/trunk/test/struct_types/TestStructTypes.py lldb/trunk/test/struct_types/main.c Modified: lldb/trunk/test/struct_types/TestStructTypes.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/struct_types/TestStructTypes.py?rev=116369&r1=116368&r2=116369&view=diff ============================================================================== --- lldb/trunk/test/struct_types/TestStructTypes.py (original) +++ lldb/trunk/test/struct_types/TestStructTypes.py Tue Oct 12 18:20:04 2010 @@ -24,21 +24,30 @@ self.buildDwarf() self.struct_types() + def setUp(self): + super(StructTypesTestCase, self).setUp() + # Find the line number to break for main.c. + self.line = line_number('main.c', '// Set break point at this line.') + self.first_executable_line = line_number('main.c', + '// This is the first executable statement.') + def struct_types(self): """Test that break on a struct declaration has no effect.""" exe = os.path.join(os.getcwd(), "a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) - # Break on the ctor function of class C. - self.expect("breakpoint set -f main.c -l 14", BREAKPOINT_CREATED, - startstr = "Breakpoint created: 1: file ='main.c', line = 14, locations = 1") + # Break on the struct declration statement in main.c. + self.expect("breakpoint set -f main.c -l %d" % self.line, + BREAKPOINT_CREATED, + startstr = "Breakpoint created: 1: file ='main.c', line = %d, locations = 1" % + self.line) self.runCmd("run", RUN_SUCCEEDED) # We should be stopped on the first executable statement within the # function where the original breakpoint was attempted. self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['main.c:20', + substrs = ['main.c:%d' % self.first_executable_line, 'stop reason = breakpoint']) # The breakpoint should have a hit count of 1. Modified: lldb/trunk/test/struct_types/main.c URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/struct_types/main.c?rev=116369&r1=116368&r2=116369&view=diff ============================================================================== --- lldb/trunk/test/struct_types/main.c (original) +++ lldb/trunk/test/struct_types/main.c Tue Oct 12 18:20:04 2010 @@ -11,13 +11,13 @@ struct point_tag { int x; int y; - }; + }; // Set break point at this line. struct rect_tag { struct point_tag bottom_left; struct point_tag top_right; }; - struct point_tag pt = { 2, 3 }; + struct point_tag pt = { 2, 3 }; // This is the first executable statement. struct rect_tag rect = {{1,2}, {3,4}}; return 0; } From johnny.chen at apple.com Tue Oct 12 18:33:57 2010 From: johnny.chen at apple.com (Johnny Chen) Date: Tue, 12 Oct 2010 23:33:57 -0000 Subject: [Lldb-commits] [lldb] r116374 - in /lldb/trunk/test/unsigned_types: TestUnsignedTypes.py main.cpp Message-ID: <20101012233357.99CF62A6C12C@llvm.org> Author: johnny Date: Tue Oct 12 18:33:57 2010 New Revision: 116374 URL: http://llvm.org/viewvc/llvm-project?rev=116374&view=rev Log: Avoid using hardcoded line number to break on. Use the line_number() utility function to get the line number to break on during setUp(). Use a pattern to match the output from both gcc-compiled and clang-compiled binary. Modified: lldb/trunk/test/unsigned_types/TestUnsignedTypes.py lldb/trunk/test/unsigned_types/main.cpp Modified: lldb/trunk/test/unsigned_types/TestUnsignedTypes.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/unsigned_types/TestUnsignedTypes.py?rev=116374&r1=116373&r2=116374&view=diff ============================================================================== --- lldb/trunk/test/unsigned_types/TestUnsignedTypes.py (original) +++ lldb/trunk/test/unsigned_types/TestUnsignedTypes.py Tue Oct 12 18:33:57 2010 @@ -23,14 +23,21 @@ self.buildDwarf() self.unsigned_types() + def setUp(self): + super(UnsignedTypesTestCase, self).setUp() + # Find the line number to break inside main(). + self.line = line_number('main.cpp', '// Set break point at this line.') + def unsigned_types(self): """Test that variables with unsigned types display correctly.""" exe = os.path.join(os.getcwd(), "a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Break on line 19 in main() aftre the variables are assigned values. - self.expect("breakpoint set -f main.cpp -l 19", BREAKPOINT_CREATED, - startstr = "Breakpoint created: 1: file ='main.cpp', line = 19, locations = 1") + 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) @@ -45,8 +52,8 @@ # Test that unsigned types display correctly. self.expect("frame variable -a", VARIABLES_DISPLAYED_CORRECTLY, startstr = "(unsigned char) the_unsigned_char = 'c'", - substrs = ["(short unsigned int) the_unsigned_short = 99", - "(unsigned int) the_unsigned_int = 99", + patterns = ["\((short unsigned int|unsigned short)\) the_unsigned_short = 99"], + substrs = ["(unsigned int) the_unsigned_int = 99", "(long unsigned int) the_unsigned_long = 99", "(long long unsigned int) the_unsigned_long_long = 99", "(uint32_t) the_uint32 = 99"]) Modified: lldb/trunk/test/unsigned_types/main.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/unsigned_types/main.cpp?rev=116374&r1=116373&r2=116374&view=diff ============================================================================== --- lldb/trunk/test/unsigned_types/main.cpp (original) +++ lldb/trunk/test/unsigned_types/main.cpp Tue Oct 12 18:33:57 2010 @@ -16,7 +16,7 @@ unsigned long long the_unsigned_long_long = 'c'; uint32_t the_uint32 = 'c'; - return the_unsigned_char - the_unsigned_short + + return the_unsigned_char - the_unsigned_short + // Set break point at this line. the_unsigned_int - the_unsigned_long + the_unsigned_long_long - the_uint32; } From johnny.chen at apple.com Tue Oct 12 18:53:59 2010 From: johnny.chen at apple.com (Johnny Chen) Date: Tue, 12 Oct 2010 23:53:59 -0000 Subject: [Lldb-commits] [lldb] r116378 - in /lldb/trunk/test/set_values: TestSetValues.py main.c Message-ID: <20101012235359.AA3332A6C12D@llvm.org> Author: johnny Date: Tue Oct 12 18:53:59 2010 New Revision: 116378 URL: http://llvm.org/viewvc/llvm-project?rev=116378&view=rev Log: Avoid using hardcoded line number to break on. Use the line_number() utility function to get the line numbers for breakpoints 1-5 during setUp(). Use a pattern to match the output from both gcc-compiled and clang-compiled binary. This finishes the conversion of the test suite to avoid hardcoded line numbers when setting breakpoints with either the lldb command: breakpoint set -f filename -l lineno or the Python API: target.BreakpointCreateByLocation(filename, lineno) Modified: lldb/trunk/test/set_values/TestSetValues.py lldb/trunk/test/set_values/main.c Modified: lldb/trunk/test/set_values/TestSetValues.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/set_values/TestSetValues.py?rev=116378&r1=116377&r2=116378&view=diff ============================================================================== --- lldb/trunk/test/set_values/TestSetValues.py (original) +++ lldb/trunk/test/set_values/TestSetValues.py Tue Oct 12 18:53:59 2010 @@ -20,26 +20,45 @@ self.buildDwarf() self.set_values() + def setUp(self): + super(SetValuesTestCase, self).setUp() + # Find the line numbers to break inside main(). + self.line1 = line_number('main.c', '// Set break point #1.') + self.line2 = line_number('main.c', '// Set break point #2.') + self.line3 = line_number('main.c', '// Set break point #3.') + self.line4 = line_number('main.c', '// Set break point #4.') + self.line5 = line_number('main.c', '// Set break point #5.') + def set_values(self): """Test settings and readings of program variables.""" exe = os.path.join(os.getcwd(), "a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Set breakpoints on several places to set program variables. - self.expect("breakpoint set -f main.c -l 15", BREAKPOINT_CREATED, - startstr = "Breakpoint created: 1: file ='main.c', line = 15, locations = 1") - - self.expect("breakpoint set -f main.c -l 36", BREAKPOINT_CREATED, - startstr = "Breakpoint created: 2: file ='main.c', line = 36, locations = 1") - - self.expect("breakpoint set -f main.c -l 57", BREAKPOINT_CREATED, - startstr = "Breakpoint created: 3: file ='main.c', line = 57, locations = 1") - - self.expect("breakpoint set -f main.c -l 78", BREAKPOINT_CREATED, - startstr = "Breakpoint created: 4: file ='main.c', line = 78, locations = 1") - - self.expect("breakpoint set -f main.c -l 85", BREAKPOINT_CREATED, - startstr = "Breakpoint created: 5: file ='main.c', line = 85, locations = 1") + self.expect("breakpoint set -f main.c -l %d" % self.line1, + BREAKPOINT_CREATED, + startstr = "Breakpoint created: 1: file ='main.c', line = %d, locations = 1" % + self.line1) + + self.expect("breakpoint set -f main.c -l %d" % self.line2, + BREAKPOINT_CREATED, + startstr = "Breakpoint created: 2: file ='main.c', line = %d, locations = 1" % + self.line2) + + self.expect("breakpoint set -f main.c -l %d" % self.line3, + BREAKPOINT_CREATED, + startstr = "Breakpoint created: 3: file ='main.c', line = %d, locations = 1" % + self.line3) + + self.expect("breakpoint set -f main.c -l %d" % self.line4, + BREAKPOINT_CREATED, + startstr = "Breakpoint created: 4: file ='main.c', line = %d, locations = 1" % + self.line4) + + self.expect("breakpoint set -f main.c -l %d" % self.line5, + BREAKPOINT_CREATED, + startstr = "Breakpoint created: 5: file ='main.c', line = %d, locations = 1" % + self.line5) self.runCmd("run", RUN_SUCCEEDED) @@ -65,7 +84,7 @@ # main.c:36 # Check that 'frame variable' displays the correct data type and value. self.expect("frame variable", VARIABLES_DISPLAYED_CORRECTLY, - startstr = "(short unsigned int) i = 33") + patterns = ["\((short unsigned int|unsigned short)\) i = 33"]) # TODO: # Now set variable 'i' and check that it is correctly displayed. Modified: lldb/trunk/test/set_values/main.c URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/set_values/main.c?rev=116378&r1=116377&r2=116378&view=diff ============================================================================== --- lldb/trunk/test/set_values/main.c (original) +++ lldb/trunk/test/set_values/main.c Tue Oct 12 18:53:59 2010 @@ -12,7 +12,7 @@ { char i = 'a'; printf("before (char) i = %c\n", i); - printf("after (char) i = %c\n", i); //// break $source:$line + printf("after (char) i = %c\n", i); // Set break point #1. //// break $source:$line } void set_uchar(void) @@ -33,7 +33,7 @@ { unsigned short i = 33; printf("before (unsigned short) i = %i\n", i); - printf("after (unsigned short) i = %i\n", i); //// break $source:$line + printf("after (unsigned short) i = %i\n", i); // Set break point #2. //// break $source:$line } void set_int(void) @@ -54,7 +54,7 @@ { long i = 33; printf("before (long) i = %li\n", i); - printf("after (long) i = %li\n", i); //// break $source:$line + printf("after (long) i = %li\n", i); // Set break point #3. //// break $source:$line } void set_ulong(void) @@ -75,14 +75,14 @@ { double i = 3.1415927; printf("before (double) i = %g\n", i); - printf("after (double) i = %g\n", i); //// break $source:$line + printf("after (double) i = %g\n", i); // Set break point #4. //// break $source:$line } void set_long_double(void) { long double i = 3.1415927; printf("before (long double) i = %Lg\n", i); - printf("after (long double) i = %Lg\n", i); //// break $source:$line + printf("after (long double) i = %Lg\n", i); // Set break point #5. //// break $source:$line } void set_point (void) From gclayton at apple.com Tue Oct 12 22:15:28 2010 From: gclayton at apple.com (Greg Clayton) Date: Wed, 13 Oct 2010 03:15:28 -0000 Subject: [Lldb-commits] [lldb] r116392 - in /lldb/trunk: source/Expression/ClangASTSource.cpp source/Plugins/SymbolFile/DWARF/DWARFCompileUnit.cpp source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.h source/Symbol/Variable.cpp test/forward/ test/forward/Makefile test/forward/README.txt test/forward/foo.c test/forward/foo.h test/forward/main.c Message-ID: <20101013031529.1C4A92A6C12C@llvm.org> Author: gclayton Date: Tue Oct 12 22:15:28 2010 New Revision: 116392 URL: http://llvm.org/viewvc/llvm-project?rev=116392&view=rev Log: Fixed C++ class clang type creation and display by making sure we omit artifical members (like the vtable pointer member that shows up in the DWARF). We were adding this to each class which was making all member variables be off by a pointer size. Added a test case so we can track this with "test/forward". Fixed the type name index in DWARF to include all the types after finding some types were being omitted due to the DW_AT_specification having the DW_AT_declaration attribute which was being read into the real type instances when there were forward declarations in the DWARF, causing the type to be omitted. We now check to make sure any DW_AT_declaration values are only respected when parsing types if the attribute is from the current DIE. After fixing the missing types, we ran into some issues with the expression parser finding duplicate entries for __va_list_tag since they are built in types and would result in a "duplicate __va_list_tag definition" error. We are now just ignoring this name during lookup, but we will need to see if we can get the name lookup function to not get called in these cases. Fixed an issue that would cause an assertion where DW_TAG_subroutine_types that had no children, would not properly make a clang function type of: "void (*) (void)". Added: lldb/trunk/test/forward/ lldb/trunk/test/forward/Makefile lldb/trunk/test/forward/README.txt lldb/trunk/test/forward/foo.c lldb/trunk/test/forward/foo.h lldb/trunk/test/forward/main.c Modified: lldb/trunk/source/Expression/ClangASTSource.cpp lldb/trunk/source/Plugins/SymbolFile/DWARF/DWARFCompileUnit.cpp lldb/trunk/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp lldb/trunk/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.h lldb/trunk/source/Symbol/Variable.cpp Modified: lldb/trunk/source/Expression/ClangASTSource.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Expression/ClangASTSource.cpp?rev=116392&r1=116391&r2=116392&view=diff ============================================================================== --- lldb/trunk/source/Expression/ClangASTSource.cpp (original) +++ lldb/trunk/source/Expression/ClangASTSource.cpp Tue Oct 12 22:15:28 2010 @@ -70,7 +70,13 @@ NameSearchContext NSC(*this, Decls, Name, DC); - DeclMap.GetDecls(NSC, Name.getAsString().c_str()); + std::string name (Name.getAsString()); + // TODO: Figure out what to do here, after recent changes to the DWARF + // parser where more types are now in type by name index, we were sometimes + // finding our own version of a builtin? Skip it for now until we figure out + // how to get around this properly. + if (name.compare("__va_list_tag") != 0) + DeclMap.GetDecls(NSC, name.c_str()); return SetExternalVisibleDeclsForName(DC, Name, Decls); } Modified: lldb/trunk/source/Plugins/SymbolFile/DWARF/DWARFCompileUnit.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Plugins/SymbolFile/DWARF/DWARFCompileUnit.cpp?rev=116392&r1=116391&r2=116392&view=diff ============================================================================== --- lldb/trunk/source/Plugins/SymbolFile/DWARF/DWARFCompileUnit.cpp (original) +++ lldb/trunk/source/Plugins/SymbolFile/DWARF/DWARFCompileUnit.cpp Tue Oct 12 22:15:28 2010 @@ -643,8 +643,15 @@ break; case DW_AT_declaration: - if (attributes.ExtractFormValueAtIndex(m_dwarf2Data, i, form_value)) - is_declaration = form_value.Unsigned() != 0; + // Make sure the declaration is from this DIE, and not from + // a DW_AT_specification or DW_AT_abstract_origin by checking + // this die and seeing if its abbreviations have the + // DW_AT_declaration attribute + if (die.GetAbbreviationDeclarationPtr()->FindAttributeIndex (DW_AT_declaration) != DW_INVALID_INDEX) + { + if (attributes.ExtractFormValueAtIndex(m_dwarf2Data, i, form_value)) + is_declaration = form_value.Unsigned() != 0; + } break; case DW_AT_artificial: 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=116392&r1=116391&r2=116392&view=diff ============================================================================== --- lldb/trunk/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp (original) +++ lldb/trunk/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp Tue Oct 12 22:15:28 2010 @@ -1076,6 +1076,7 @@ Declaration decl; DWARFExpression location; const char *name = NULL; + bool is_artificial = false; lldb::user_id_t encoding_uid = LLDB_INVALID_UID; AccessType accessibility = eAccessNone; off_t member_offset = 0; @@ -1083,7 +1084,7 @@ size_t bit_offset = 0; size_t bit_size = 0; uint32_t i; - for (i=0; iGetClangASTContext().AddFieldToRecordType (class_clang_type, name, member_type->GetClangType(), accessibility, bit_size); + type_list->GetClangASTContext().AddFieldToRecordType (class_clang_type, name, member_type->GetClangType(), accessibility, bit_size); + } } } break; @@ -1416,14 +1421,15 @@ } Type* -SymbolFileDWARF::ResolveType (DWARFCompileUnit* cu, const DWARFDebugInfoEntry* type_die) +SymbolFileDWARF::ResolveType (DWARFCompileUnit* cu, const DWARFDebugInfoEntry* type_die, bool assert_not_being_parsed) { if (type_die != NULL) { Type *type = m_die_to_type.lookup (type_die); if (type == NULL) type = GetTypeForDIE (cu, type_die).get(); - assert (type != DIE_IS_BEING_PARSED); + if (assert_not_being_parsed) + assert (type != DIE_IS_BEING_PARSED); return type; } return NULL; @@ -1724,9 +1730,12 @@ m_aranges->Sort(); -#if 0 +#if defined (ENABLE_DEBUG_PRINTF) StreamFile s(stdout); - s.Printf("DWARF index for '%s':", GetObjectFile()->GetFileSpec().GetFilename().AsCString()); + s.Printf ("DWARF index for (%s) '%s/%s':", + GetObjectFile()->GetModule()->GetArchitecture().AsCString(), + GetObjectFile()->GetFileSpec().GetDirectory().AsCString(), + GetObjectFile()->GetFileSpec().GetFilename().AsCString()); s.Printf("\nFunction basenames:\n"); m_function_basename_index.Dump (&s); s.Printf("\nFunction fullnames:\n"); m_function_fullname_index.Dump (&s); s.Printf("\nFunction methods:\n"); m_function_method_index.Dump (&s); @@ -2529,7 +2538,7 @@ bool is_forward_declaration = false; DWARFDebugInfoEntry::Attributes attributes; const char *type_name_cstr = NULL; - ConstString type_name_dbstr; + ConstString type_name_const_str; Type::EncodingDataType encoding_data_type = Type::eEncodingIsUID; clang_type_t clang_type = NULL; @@ -2571,7 +2580,7 @@ case DW_AT_decl_column: decl.SetColumn(form_value.Unsigned()); break; case DW_AT_name: type_name_cstr = form_value.AsCString(&get_debug_str_data()); - type_name_dbstr.SetCString(type_name_cstr); + type_name_const_str.SetCString(type_name_cstr); break; case DW_AT_byte_size: byte_size = form_value.Unsigned(); break; case DW_AT_encoding: encoding = form_value.Unsigned(); break; @@ -2637,21 +2646,21 @@ static ConstString g_objc_type_name_Class("Class"); static ConstString g_objc_type_name_selector("SEL"); - if (type_name_dbstr == g_objc_type_name_id) + if (type_name_const_str == g_objc_type_name_id) { clang_type = type_list->GetClangASTContext().GetBuiltInType_objc_id(); } - else if (type_name_dbstr == g_objc_type_name_Class) + else if (type_name_const_str == g_objc_type_name_Class) { clang_type = type_list->GetClangASTContext().GetBuiltInType_objc_Class(); } - else if (type_name_dbstr == g_objc_type_name_selector) + else if (type_name_const_str == g_objc_type_name_selector) { clang_type = type_list->GetClangASTContext().GetBuiltInType_objc_selector(); } } - type_sp.reset( new Type(die->GetOffset(), this, type_name_dbstr, byte_size, NULL, encoding_uid, encoding_data_type, &decl, clang_type, clang_type == NULL)); + type_sp.reset( new Type(die->GetOffset(), this, type_name_const_str, byte_size, NULL, encoding_uid, encoding_data_type, &decl, clang_type, clang_type == NULL)); m_die_to_type[die] = type_sp.get(); @@ -2703,7 +2712,7 @@ case DW_AT_name: type_name_cstr = form_value.AsCString(&get_debug_str_data()); - type_name_dbstr.SetCString(type_name_cstr); + type_name_const_str.SetCString(type_name_cstr); break; case DW_AT_byte_size: @@ -2756,6 +2765,54 @@ default_accessibility = eAccessPrivate; } + + if (is_forward_declaration) + { + // We have a forward declaration + std::vector die_info_array; + const size_t num_matches = m_types_index.Find (type_name_const_str, die_info_array); + DWARFCompileUnit* type_cu = NULL; + DWARFCompileUnit* curr_cu = dwarf_cu; + DWARFDebugInfo *info = DebugInfo(); + for (size_t i=0; iGetCompileUnitAtIndex (die_info_array[i].cu_idx); + + if (type_cu != curr_cu) + { + type_cu->ExtractDIEsIfNeeded (false); + curr_cu = type_cu; + } + + DWARFDebugInfoEntry *type_die = type_cu->GetDIEAtIndexUnchecked (die_info_array[i].die_idx); + + if (type_die != die && type_die->Tag() == tag) + { + // Hold off on comparing parent DIE tags until + // we know what happens with stuff in namespaces + // for gcc and clang... +// DWARFDebugInfoEntry *parent_die = die->GetParent(); +// DWARFDebugInfoEntry *parent_type_die = type_die->GetParent(); +// if (parent_die->Tag() == parent_type_die->Tag()) + { + Type *resolved_type = ResolveType (type_cu, type_die, false); + if (resolved_type && resolved_type != DIE_IS_BEING_PARSED) + { + DEBUG_PRINTF ("resolved 0x%8.8x (cu 0x%8.8x) from %s to 0x%8.8x (cu 0x%8.8x)\n", + die->GetOffset(), + dwarf_cu->GetOffset(), + m_obj_file->GetFileSpec().GetFilename().AsCString(), + type_die->GetOffset(), + type_cu->GetOffset()); + + m_die_to_type[die] = resolved_type; + type_sp = m_obj_file->GetModule()->GetTypeList()->FindType(resolved_type->GetID()); + return type_sp; + } + } + } + } + } assert (tag_decl_kind != -1); bool clang_type_was_created = false; clang_type = m_forward_decl_die_to_clang_type.lookup (die); @@ -2770,7 +2827,7 @@ // types for function prototypes. m_die_to_decl_ctx[die] = ClangASTContext::GetDeclContextForType (clang_type); const bool is_forward_decl = die->HasChildren(); - type_sp.reset( new Type(die->GetOffset(), this, type_name_dbstr, byte_size, NULL, LLDB_INVALID_UID, Type::eEncodingIsUID, &decl, clang_type, is_forward_decl)); + type_sp.reset (new Type(die->GetOffset(), this, type_name_const_str, byte_size, NULL, LLDB_INVALID_UID, Type::eEncodingIsUID, &decl, clang_type, is_forward_decl)); m_die_to_type[die] = type_sp.get(); @@ -2821,7 +2878,7 @@ case DW_AT_decl_column: decl.SetColumn(form_value.Unsigned()); break; case DW_AT_name: type_name_cstr = form_value.AsCString(&get_debug_str_data()); - type_name_dbstr.SetCString(type_name_cstr); + type_name_const_str.SetCString(type_name_cstr); break; case DW_AT_type: encoding_uid = form_value.Reference(dwarf_cu); break; case DW_AT_byte_size: byte_size = form_value.Unsigned(); break; @@ -2859,7 +2916,7 @@ } m_die_to_decl_ctx[die] = ClangASTContext::GetDeclContextForType (clang_type); - type_sp.reset( new Type(die->GetOffset(), this, type_name_dbstr, byte_size, NULL, encoding_uid, Type::eEncodingIsUID, &decl, clang_type, true)); + type_sp.reset( new Type(die->GetOffset(), this, type_name_const_str, byte_size, NULL, encoding_uid, Type::eEncodingIsUID, &decl, clang_type, true)); m_die_to_type[die] = type_sp.get(); @@ -2912,7 +2969,7 @@ case DW_AT_decl_column: decl.SetColumn(form_value.Unsigned()); break; case DW_AT_name: type_name_cstr = form_value.AsCString(&get_debug_str_data()); - type_name_dbstr.SetCString(type_name_cstr); + type_name_const_str.SetCString(type_name_cstr); break; case DW_AT_MIPS_linkage_name: mangled = form_value.AsCString(&get_debug_str_data()); break; @@ -2964,130 +3021,133 @@ } } } + } - DEBUG_PRINTF ("0x%8.8x: %s (\"%s\")\n", die->GetOffset(), DW_TAG_value_to_name(tag), type_name_cstr); + DEBUG_PRINTF ("0x%8.8x: %s (\"%s\")\n", die->GetOffset(), DW_TAG_value_to_name(tag), type_name_cstr); - clang_type_t return_clang_type = NULL; - Type *func_type = NULL; - - if (type_die_offset != DW_INVALID_OFFSET) - func_type = ResolveTypeUID(type_die_offset); + clang_type_t return_clang_type = NULL; + Type *func_type = NULL; + + if (type_die_offset != DW_INVALID_OFFSET) + func_type = ResolveTypeUID(type_die_offset); - if (func_type) - return_clang_type = func_type->GetClangForwardType(); - else - return_clang_type = type_list->GetClangASTContext().GetBuiltInType_void(); + if (func_type) + return_clang_type = func_type->GetClangForwardType(); + else + return_clang_type = type_list->GetClangASTContext().GetBuiltInType_void(); - std::vector function_param_types; - std::vector function_param_decls; + std::vector function_param_types; + std::vector function_param_decls; - // Parse the function children for the parameters + // Parse the function children for the parameters + if (die->HasChildren()) + { bool skip_artificial = true; ParseChildParameters (sc, type_sp, dwarf_cu, die, skip_artificial, type_list, function_param_types, function_param_decls); + } - // clang_type will get the function prototype clang type after this call - clang_type = type_list->GetClangASTContext().CreateFunctionType (return_clang_type, &function_param_types[0], function_param_types.size(), is_variadic, type_quals); + // clang_type will get the function prototype clang type after this call + clang_type = type_list->GetClangASTContext().CreateFunctionType (return_clang_type, &function_param_types[0], function_param_types.size(), is_variadic, type_quals); - if (type_name_cstr) + if (type_name_cstr) + { + bool type_handled = false; + const DWARFDebugInfoEntry *parent_die = die->GetParent(); + if (tag == DW_TAG_subprogram) { - bool type_handled = false; - const DWARFDebugInfoEntry *parent_die = die->GetParent(); - if (tag == DW_TAG_subprogram) + if (type_name_cstr[1] == '[' && (type_name_cstr[0] == '-' || type_name_cstr[0] == '+')) { - if (type_name_cstr[1] == '[' && (type_name_cstr[0] == '-' || type_name_cstr[0] == '+')) + // We need to find the DW_TAG_class_type or + // DW_TAG_struct_type by name so we can add this + // as a member function of the class. + const char *class_name_start = type_name_cstr + 2; + const char *class_name_end = ::strchr (class_name_start, ' '); + SymbolContext empty_sc; + clang_type_t class_opaque_type = NULL; + if (class_name_start < class_name_end) { - // We need to find the DW_TAG_class_type or - // DW_TAG_struct_type by name so we can add this - // as a member function of the class. - const char *class_name_start = type_name_cstr + 2; - const char *class_name_end = ::strchr (class_name_start, ' '); - SymbolContext empty_sc; - clang_type_t class_opaque_type = NULL; - if (class_name_start < class_name_end) + ConstString class_name (class_name_start, class_name_end - class_name_start); + TypeList types; + const uint32_t match_count = FindTypes (empty_sc, class_name, true, UINT32_MAX, types); + if (match_count > 0) { - ConstString class_name (class_name_start, class_name_end - class_name_start); - TypeList types; - const uint32_t match_count = FindTypes (empty_sc, class_name, true, UINT32_MAX, types); - if (match_count > 0) + for (uint32_t i=0; iGetClangForwardType(); + if (ClangASTContext::IsObjCClassType (type_clang_forward_type)) { - Type *type = types.GetTypeAtIndex (i).get(); - clang_type_t type_clang_forward_type = type->GetClangForwardType(); - if (ClangASTContext::IsObjCClassType (type_clang_forward_type)) - { - class_opaque_type = type_clang_forward_type; - break; - } + class_opaque_type = type_clang_forward_type; + break; } } } + } - if (class_opaque_type) + if (class_opaque_type) + { + // If accessibility isn't set to anything valid, assume public for + // now... + if (accessibility == eAccessNone) + accessibility = eAccessPublic; + + clang::ObjCMethodDecl *objc_method_decl; + objc_method_decl = type_list->GetClangASTContext().AddMethodToObjCObjectType (class_opaque_type, + type_name_cstr, + clang_type, + accessibility); + type_handled = objc_method_decl != NULL; + } + } + else if (parent_die->Tag() == DW_TAG_class_type || + parent_die->Tag() == DW_TAG_structure_type) + { + // Look at the parent of this DIE and see if is is + // a class or struct and see if this is actually a + // C++ method + Type *class_type = ResolveType (dwarf_cu, parent_die); + if (class_type) + { + clang_type_t class_opaque_type = class_type->GetClangForwardType(); + if (ClangASTContext::IsCXXClassType (class_opaque_type)) { - // If accessibility isn't set to anything valid, assume public for - // now... + // Neither GCC 4.2 nor clang++ currently set a valid accessibility + // in the DWARF for C++ methods... Default to public for now... if (accessibility == eAccessNone) accessibility = eAccessPublic; - clang::ObjCMethodDecl *objc_method_decl; - objc_method_decl = type_list->GetClangASTContext().AddMethodToObjCObjectType (class_opaque_type, - type_name_cstr, - clang_type, - accessibility); - type_handled = objc_method_decl != NULL; - } - } - else if (parent_die->Tag() == DW_TAG_class_type || - parent_die->Tag() == DW_TAG_structure_type) - { - // Look at the parent of this DIE and see if is is - // a class or struct and see if this is actually a - // C++ method - Type *class_type = ResolveType (dwarf_cu, parent_die); - if (class_type) - { - clang_type_t class_opaque_type = class_type->GetClangForwardType(); - if (ClangASTContext::IsCXXClassType (class_opaque_type)) - { - // Neither GCC 4.2 nor clang++ currently set a valid accessibility - // in the DWARF for C++ methods... Default to public for now... - if (accessibility == eAccessNone) - accessibility = eAccessPublic; - - clang::CXXMethodDecl *cxx_method_decl; - cxx_method_decl = type_list->GetClangASTContext().AddMethodToCXXRecordType (class_opaque_type, - type_name_cstr, - clang_type, - accessibility, - is_virtual, - is_static, - is_inline, - is_explicit); - type_handled = cxx_method_decl != NULL; - } + clang::CXXMethodDecl *cxx_method_decl; + cxx_method_decl = type_list->GetClangASTContext().AddMethodToCXXRecordType (class_opaque_type, + type_name_cstr, + clang_type, + accessibility, + is_virtual, + is_static, + is_inline, + is_explicit); + type_handled = cxx_method_decl != NULL; } } } - - if (!type_handled) - { - // We just have a function that isn't part of a class - clang::FunctionDecl *function_decl = type_list->GetClangASTContext().CreateFunctionDeclaration (type_name_cstr, clang_type, storage, is_inline); - - // Add the decl to our DIE to decl context map - assert (function_decl); - m_die_to_decl_ctx[die] = function_decl; - if (!function_param_decls.empty()) - type_list->GetClangASTContext().SetFunctionParameters (function_decl, &function_param_decls.front(), function_param_decls.size()); - } } - type_sp.reset( new Type(die->GetOffset(), this, type_name_dbstr, 0, NULL, LLDB_INVALID_UID, Type::eEncodingIsUID, &decl, clang_type, false)); - - m_die_to_type[die] = type_sp.get(); - assert(type_sp.get()); + + if (!type_handled) + { + // We just have a function that isn't part of a class + clang::FunctionDecl *function_decl = type_list->GetClangASTContext().CreateFunctionDeclaration (type_name_cstr, clang_type, storage, is_inline); + + // Add the decl to our DIE to decl context map + assert (function_decl); + m_die_to_decl_ctx[die] = function_decl; + if (!function_param_decls.empty()) + type_list->GetClangASTContext().SetFunctionParameters (function_decl, &function_param_decls.front(), function_param_decls.size()); + } } + type_sp.reset( new Type(die->GetOffset(), this, type_name_const_str, 0, NULL, LLDB_INVALID_UID, Type::eEncodingIsUID, &decl, clang_type, false)); + + m_die_to_type[die] = type_sp.get(); + assert(type_sp.get()); } break; @@ -3120,7 +3180,7 @@ case DW_AT_decl_column: decl.SetColumn(form_value.Unsigned()); break; case DW_AT_name: type_name_cstr = form_value.AsCString(&get_debug_str_data()); - type_name_dbstr.SetCString(type_name_cstr); + type_name_const_str.SetCString(type_name_cstr); break; case DW_AT_type: type_die_offset = form_value.Reference(dwarf_cu); break; @@ -3212,7 +3272,7 @@ size_t byte_size = ClangASTType::GetClangTypeBitWidth (type_list->GetClangASTContext().getASTContext(), clang_type) / 8; - type_sp.reset( new Type(die->GetOffset(), this, type_name_dbstr, byte_size, NULL, LLDB_INVALID_UID, Type::eEncodingIsUID, NULL, clang_type, false)); + type_sp.reset( new Type(die->GetOffset(), this, type_name_const_str, byte_size, NULL, LLDB_INVALID_UID, Type::eEncodingIsUID, NULL, clang_type, false)); m_die_to_type[die] = type_sp.get(); } 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=116392&r1=116391&r2=116392&view=diff ============================================================================== --- lldb/trunk/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.h (original) +++ lldb/trunk/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.h Tue Oct 12 22:15:28 2010 @@ -97,7 +97,7 @@ virtual lldb_private::Type* ResolveTypeUID(lldb::user_id_t type_uid); virtual lldb::clang_type_t ResolveClangOpaqueTypeDefinition (lldb::clang_type_t clang_opaque_type); - virtual lldb_private::Type* ResolveType (DWARFCompileUnit* cu, const DWARFDebugInfoEntry* type_die); + virtual lldb_private::Type* ResolveType (DWARFCompileUnit* cu, const DWARFDebugInfoEntry* type_die, bool assert_not_being_parsed = true); virtual clang::DeclContext* GetClangDeclContextForTypeUID (lldb::user_id_t type_uid); virtual uint32_t ResolveSymbolContext (const lldb_private::Address& so_addr, uint32_t resolve_scope, lldb_private::SymbolContext& sc); Modified: lldb/trunk/source/Symbol/Variable.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Symbol/Variable.cpp?rev=116392&r1=116391&r2=116392&view=diff ============================================================================== --- lldb/trunk/source/Symbol/Variable.cpp (original) +++ lldb/trunk/source/Symbol/Variable.cpp Tue Oct 12 22:15:28 2010 @@ -67,7 +67,7 @@ if (m_type != NULL) { - *s << ", type = " << (void*)m_type << " ("; + *s << ", type = {" << m_type->GetID() << "} " << (void*)m_type << " ("; m_type->DumpTypeName(s); s->PutChar(')'); } Added: lldb/trunk/test/forward/Makefile URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/forward/Makefile?rev=116392&view=auto ============================================================================== --- lldb/trunk/test/forward/Makefile (added) +++ lldb/trunk/test/forward/Makefile Tue Oct 12 22:15:28 2010 @@ -0,0 +1,5 @@ +LEVEL = ../make + +C_SOURCES := main.c foo.c + +include $(LEVEL)/Makefile.rules Added: lldb/trunk/test/forward/README.txt URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/forward/README.txt?rev=116392&view=auto ============================================================================== --- lldb/trunk/test/forward/README.txt (added) +++ lldb/trunk/test/forward/README.txt Tue Oct 12 22:15:28 2010 @@ -0,0 +1,5 @@ +This example has a function call in foo.c named "foo" that takes a forward +declaration to "struct bar" and uses it as a pointer argument. In main.c +we have a real declaration for "struct bar". We want to be able to find the +real definition of "struct bar" when we are stopped in foo in foo.c such that +when we stop in "foo" we see the contents of the "bar_ptr". Added: lldb/trunk/test/forward/foo.c URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/forward/foo.c?rev=116392&view=auto ============================================================================== --- lldb/trunk/test/forward/foo.c (added) +++ lldb/trunk/test/forward/foo.c Tue Oct 12 22:15:28 2010 @@ -0,0 +1,8 @@ +#include +#include "foo.h" + +int +foo (struct bar *bar_ptr) +{ + return printf ("bar_ptr = %p\n", bar_ptr); +} Added: lldb/trunk/test/forward/foo.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/forward/foo.h?rev=116392&view=auto ============================================================================== --- lldb/trunk/test/forward/foo.h (added) +++ lldb/trunk/test/forward/foo.h Tue Oct 12 22:15:28 2010 @@ -0,0 +1,4 @@ + +struct bar; + +int foo (struct bar *bar_ptr); Added: lldb/trunk/test/forward/main.c URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/forward/main.c?rev=116392&view=auto ============================================================================== --- lldb/trunk/test/forward/main.c (added) +++ lldb/trunk/test/forward/main.c Tue Oct 12 22:15:28 2010 @@ -0,0 +1,18 @@ +#include +#include "foo.h" + +struct bar +{ + int a; + int b; +}; + +int +main (int argc, char const *argv[]) +{ + struct bar b= { 1, 2 }; + + foo (&b); + + return 0; +} From johnny.chen at apple.com Wed Oct 13 13:47:36 2010 From: johnny.chen at apple.com (Johnny Chen) Date: Wed, 13 Oct 2010 18:47:36 -0000 Subject: [Lldb-commits] [lldb] r116416 - /lldb/trunk/test/forward/TestForwardDeclaration.py Message-ID: <20101013184736.590F72A6C12C@llvm.org> Author: johnny Date: Wed Oct 13 13:47:36 2010 New Revision: 116416 URL: http://llvm.org/viewvc/llvm-project?rev=116416&view=rev Log: Add a test case for the test/forward directory with @expectedFailure decorator for test_with_dwarf_and_run_command(self). Added: lldb/trunk/test/forward/TestForwardDeclaration.py Added: lldb/trunk/test/forward/TestForwardDeclaration.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/forward/TestForwardDeclaration.py?rev=116416&view=auto ============================================================================== --- lldb/trunk/test/forward/TestForwardDeclaration.py (added) +++ lldb/trunk/test/forward/TestForwardDeclaration.py Wed Oct 13 13:47:36 2010 @@ -0,0 +1,64 @@ +"""Test that forward declaration of a data structure gets resolved correctly.""" + +import os, time +import unittest2 +import lldb +from lldbtest import * + +class ForwardDeclarationTestCase(TestBase): + + mydir = "forward" + + @unittest2.skipUnless(sys.platform.startswith("darwin"), "requires Darwin") + def test_with_dsym_and_run_command(self): + """Display *bar_ptr when stopped on a function with forward declaration of struct bar.""" + self.buildDsym() + self.forward_declaration() + + # rdar://problem/8546815 + # './dotest.py -v -t forward' fails for test_with_dwarf_and_run_command + @unittest2.expectedFailure + def test_with_dwarf_and_run_command(self): + """Display *bar_ptr when stopped on a function with forward declaration of struct bar.""" + self.buildDwarf() + self.forward_declaration() + + def forward_declaration(self): + """Display *bar_ptr when stopped on a function with forward declaration of struct bar.""" + exe = os.path.join(os.getcwd(), "a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Break inside the foo function which takes a bar_ptr argument. + self.expect("breakpoint set -n foo", BREAKPOINT_CREATED, + startstr = "Breakpoint created: 1: name = 'foo', locations = 1") + + 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']) + + # This should display correctly. + # Note that the member fields of a = 1 and b = 2 is by design. + self.expect("frame variable *bar_ptr", VARIABLES_DISPLAYED_CORRECTLY, + substrs = ['(struct bar *) bar_ptr = ', + '(int) a = 1', + '(int) b = 2']) + + # And so should this. + self.expect("expr *bar_ptr", VARIABLES_DISPLAYED_CORRECTLY, + substrs = ['(struct bar)', + '(int) a = 1', + '(int) b = 2']) + + +if __name__ == '__main__': + import atexit + lldb.SBDebugger.Initialize() + atexit.register(lambda: lldb.SBDebugger.Terminate()) + unittest2.main() From gclayton at apple.com Wed Oct 13 13:56:36 2010 From: gclayton at apple.com (Greg Clayton) Date: Wed, 13 Oct 2010 18:56:36 -0000 Subject: [Lldb-commits] [lldb] r116418 - /lldb/trunk/source/Commands/CommandObjectFrame.cpp Message-ID: <20101013185636.CA2032A6C12C@llvm.org> Author: gclayton Date: Wed Oct 13 13:56:36 2010 New Revision: 116418 URL: http://llvm.org/viewvc/llvm-project?rev=116418&view=rev Log: Default "frame variable" to not show types before values by default. You now enable type display with --show-types or -t (instead of disabling it with --no-types or -t). Modified: lldb/trunk/source/Commands/CommandObjectFrame.cpp Modified: lldb/trunk/source/Commands/CommandObjectFrame.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Commands/CommandObjectFrame.cpp?rev=116418&r1=116417&r2=116418&view=diff ============================================================================== --- lldb/trunk/source/Commands/CommandObjectFrame.cpp (original) +++ lldb/trunk/source/Commands/CommandObjectFrame.cpp Wed Oct 13 13:56:36 2010 @@ -313,7 +313,7 @@ case 'a': show_args = false; break; case 'l': show_locals = false; break; case 'g': show_globals = true; break; - case 't': show_types = false; break; + case 't': show_types = true; break; case 'y': show_summary = false; break; case 'L': show_location= true; break; case 'c': show_decl = true; break; @@ -356,7 +356,7 @@ show_args = true; show_locals = true; show_globals = false; - show_types = true; + show_types = false; show_scope = false; show_summary = true; show_location = false; @@ -843,7 +843,7 @@ { LLDB_OPT_SET_1, false, "show-declaration", 'c', no_argument, NULL, 0, eArgTypeNone, "Show variable declaration information (source file and line where the variable was declared)."}, { LLDB_OPT_SET_1, false, "no-args", 'a', no_argument, NULL, 0, eArgTypeNone, "Omit function arguments."}, { LLDB_OPT_SET_1, false, "no-locals", 'l', no_argument, NULL, 0, eArgTypeNone, "Omit local variables."}, -{ LLDB_OPT_SET_1, false, "no-types", 't', no_argument, NULL, 0, eArgTypeNone, "Omit variable type names."}, +{ LLDB_OPT_SET_1, false, "show-types", 't', no_argument, NULL, 0, eArgTypeNone, "Show variable types when dumping values."}, { LLDB_OPT_SET_1, false, "no-summary", 'y', no_argument, NULL, 0, eArgTypeNone, "Omit summary information."}, { LLDB_OPT_SET_1, false, "scope", 's', no_argument, NULL, 0, eArgTypeNone, "Show variable scope (argument, local, global, static)."}, { LLDB_OPT_SET_1, false, "objc", 'o', no_argument, NULL, 0, eArgTypeNone, "When looking up a variable by name (--name), print as an Objective-C object."}, From johnny.chen at apple.com Wed Oct 13 14:22:51 2010 From: johnny.chen at apple.com (Johnny Chen) Date: Wed, 13 Oct 2010 19:22:51 -0000 Subject: [Lldb-commits] [lldb] r116419 - in /lldb/trunk/test: array_types/TestArrayTypes.py bitfields/TestBitfields.py breakpoint_command/TestBreakpointCommand.py class_types/TestClassTypes.py forward/TestForwardDeclaration.py foundation/TestObjCMethods.py function_types/TestFunctionTypes.py global_variables/TestGlobalVariables.py set_values/TestSetValues.py types/AbstractBase.py unsigned_types/TestUnsignedTypes.py Message-ID: <20101013192251.2851C2A6C12C@llvm.org> Author: johnny Date: Wed Oct 13 14:22:50 2010 New Revision: 116419 URL: http://llvm.org/viewvc/llvm-project?rev=116419&view=rev Log: Apply (query-replace "frame variable" "frame variable -t") and fix a comment about 'expr var', not 'frame variable var'. Modified: lldb/trunk/test/array_types/TestArrayTypes.py lldb/trunk/test/bitfields/TestBitfields.py lldb/trunk/test/breakpoint_command/TestBreakpointCommand.py lldb/trunk/test/class_types/TestClassTypes.py lldb/trunk/test/forward/TestForwardDeclaration.py lldb/trunk/test/foundation/TestObjCMethods.py lldb/trunk/test/function_types/TestFunctionTypes.py lldb/trunk/test/global_variables/TestGlobalVariables.py lldb/trunk/test/set_values/TestSetValues.py lldb/trunk/test/types/AbstractBase.py lldb/trunk/test/unsigned_types/TestUnsignedTypes.py Modified: lldb/trunk/test/array_types/TestArrayTypes.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/array_types/TestArrayTypes.py?rev=116419&r1=116418&r2=116419&view=diff ============================================================================== --- lldb/trunk/test/array_types/TestArrayTypes.py (original) +++ lldb/trunk/test/array_types/TestArrayTypes.py Wed Oct 13 14:22:50 2010 @@ -66,7 +66,7 @@ # Issue 'variable list' command on several array-type variables. - self.expect("frame variable strings", VARIABLES_DISPLAYED_CORRECTLY, + self.expect("frame variable -t strings", VARIABLES_DISPLAYED_CORRECTLY, startstr = '(char *[4])', substrs = ['(char *) strings[0]', '(char *) strings[1]', @@ -77,14 +77,14 @@ 'Bonjour', 'Guten Tag']) - self.expect("frame variable char_16", VARIABLES_DISPLAYED_CORRECTLY, + self.expect("frame variable -t char_16", VARIABLES_DISPLAYED_CORRECTLY, substrs = ['(char) char_16[0]', '(char) char_16[15]']) - self.expect("frame variable ushort_matrix", VARIABLES_DISPLAYED_CORRECTLY, + self.expect("frame variable -t ushort_matrix", VARIABLES_DISPLAYED_CORRECTLY, startstr = '(unsigned short [2][3])') - self.expect("frame variable long_6", VARIABLES_DISPLAYED_CORRECTLY, + self.expect("frame variable -t long_6", VARIABLES_DISPLAYED_CORRECTLY, startstr = '(long [6])') def array_types_python(self): Modified: lldb/trunk/test/bitfields/TestBitfields.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/bitfields/TestBitfields.py?rev=116419&r1=116418&r2=116419&view=diff ============================================================================== --- lldb/trunk/test/bitfields/TestBitfields.py (original) +++ lldb/trunk/test/bitfields/TestBitfields.py Wed Oct 13 14:22:50 2010 @@ -59,7 +59,7 @@ substrs = [' resolved, hit count = 1']) # This should display correctly. - self.expect("frame variable bits", VARIABLES_DISPLAYED_CORRECTLY, + self.expect("frame variable -t bits", VARIABLES_DISPLAYED_CORRECTLY, substrs = ['(uint32_t:1) b1 = 1,', '(uint32_t:2) b2 = 3,', '(uint32_t:3) b3 = 7,', @@ -71,7 +71,7 @@ # And so should this. # rdar://problem/8348251 - self.expect("frame variable", VARIABLES_DISPLAYED_CORRECTLY, + self.expect("frame variable -t", VARIABLES_DISPLAYED_CORRECTLY, substrs = ['(uint32_t:1) b1 = 1,', '(uint32_t:2) b2 = 3,', '(uint32_t:3) b3 = 7,', Modified: lldb/trunk/test/breakpoint_command/TestBreakpointCommand.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/breakpoint_command/TestBreakpointCommand.py?rev=116419&r1=116418&r2=116419&view=diff ============================================================================== --- lldb/trunk/test/breakpoint_command/TestBreakpointCommand.py (original) +++ lldb/trunk/test/breakpoint_command/TestBreakpointCommand.py Wed Oct 13 14:22:50 2010 @@ -47,7 +47,7 @@ self.line) # Now add callbacks for the breakpoints just created. - self.runCmd("breakpoint command add -c -o 'frame variable -s' 1") + self.runCmd("breakpoint command add -c -o 'frame variable -t -s' 1") self.runCmd("breakpoint command add -p -o 'here = open(\"output.txt\", \"w\"); print >> here, \"lldb\"; here.close()' 2") # Check that the breakpoint commands are correctly set. @@ -61,7 +61,7 @@ self.expect("breakpoint command list 1", "Breakpoint 1 command ok", substrs = ["Breakpoint commands:", - "frame variable -s"]) + "frame variable -t -s"]) self.expect("breakpoint command list 2", "Breakpoint 2 command ok", substrs = ["Breakpoint commands:", "here = open", Modified: lldb/trunk/test/class_types/TestClassTypes.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/class_types/TestClassTypes.py?rev=116419&r1=116418&r2=116419&view=diff ============================================================================== --- lldb/trunk/test/class_types/TestClassTypes.py (original) +++ lldb/trunk/test/class_types/TestClassTypes.py Wed Oct 13 14:22:50 2010 @@ -81,7 +81,7 @@ substrs = [' resolved, hit count = 1']) # We should be stopped on the ctor function of class C. - self.expect("frame variable this", VARIABLES_DISPLAYED_CORRECTLY, + self.expect("frame variable -t this", VARIABLES_DISPLAYED_CORRECTLY, substrs = ['C *', ' this = ']) @@ -170,8 +170,8 @@ # Continue on inside the ctor() body... self.runCmd("thread step-over") - # Verify that frame variable this->m_c_int behaves correctly. - self.expect("frame variable this->m_c_int", VARIABLES_DISPLAYED_CORRECTLY, + # 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') # rdar://problem/8430916 Modified: lldb/trunk/test/forward/TestForwardDeclaration.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/forward/TestForwardDeclaration.py?rev=116419&r1=116418&r2=116419&view=diff ============================================================================== --- lldb/trunk/test/forward/TestForwardDeclaration.py (original) +++ lldb/trunk/test/forward/TestForwardDeclaration.py Wed Oct 13 14:22:50 2010 @@ -45,7 +45,7 @@ # This should display correctly. # Note that the member fields of a = 1 and b = 2 is by design. - self.expect("frame variable *bar_ptr", VARIABLES_DISPLAYED_CORRECTLY, + self.expect("frame variable -t *bar_ptr", VARIABLES_DISPLAYED_CORRECTLY, substrs = ['(struct bar *) bar_ptr = ', '(int) a = 1', '(int) b = 2']) Modified: lldb/trunk/test/foundation/TestObjCMethods.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/foundation/TestObjCMethods.py?rev=116419&r1=116418&r2=116419&view=diff ============================================================================== --- lldb/trunk/test/foundation/TestObjCMethods.py (original) +++ lldb/trunk/test/foundation/TestObjCMethods.py Wed Oct 13 14:22:50 2010 @@ -116,7 +116,7 @@ 'NSString * str;', 'NSDate * date;']) - self.expect("frame variable -s", VARIABLES_DISPLAYED_CORRECTLY, + self.expect("frame variable -t -s", VARIABLES_DISPLAYED_CORRECTLY, substrs = ["ARG: (MyString *) self"], patterns = ["ARG: \(.*\) _cmd", "(struct objc_selector *)|(SEL)"]) @@ -124,16 +124,16 @@ # rdar://problem/8492646 # test/foundation fails after updating to tot r115023 # self->str displays nothing as output - self.expect("frame variable self->str", VARIABLES_DISPLAYED_CORRECTLY, + self.expect("frame variable -t self->str", VARIABLES_DISPLAYED_CORRECTLY, startstr = "(NSString *) self->str") # rdar://problem/8447030 # 'frame variable self->date' displays the wrong data member - self.expect("frame variable self->date", VARIABLES_DISPLAYED_CORRECTLY, + self.expect("frame variable -t self->date", VARIABLES_DISPLAYED_CORRECTLY, startstr = "(NSDate *) self->date") # This should display the str and date member fields as well. - self.expect("frame variable *self", VARIABLES_DISPLAYED_CORRECTLY, + self.expect("frame variable -t *self", VARIABLES_DISPLAYED_CORRECTLY, substrs = ["(MyString *) self", "(NSString *) str", "(NSDate *) date"]) Modified: lldb/trunk/test/function_types/TestFunctionTypes.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/function_types/TestFunctionTypes.py?rev=116419&r1=116418&r2=116419&view=diff ============================================================================== --- lldb/trunk/test/function_types/TestFunctionTypes.py (original) +++ lldb/trunk/test/function_types/TestFunctionTypes.py Wed Oct 13 14:22:50 2010 @@ -48,7 +48,7 @@ substrs = [' resolved, hit count = 1']) # Check that the 'callback' variable display properly. - self.expect("frame variable callback", VARIABLES_DISPLAYED_CORRECTLY, + self.expect("frame variable -t callback", VARIABLES_DISPLAYED_CORRECTLY, startstr = '(int (*)(const char *)) callback =') # And that we can break on the callback function. Modified: lldb/trunk/test/global_variables/TestGlobalVariables.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/global_variables/TestGlobalVariables.py?rev=116419&r1=116418&r2=116419&view=diff ============================================================================== --- lldb/trunk/test/global_variables/TestGlobalVariables.py (original) +++ lldb/trunk/test/global_variables/TestGlobalVariables.py Wed Oct 13 14:22:50 2010 @@ -48,7 +48,7 @@ substrs = [' resolved, hit count = 1']) # Check that GLOBAL scopes are indicated for the variables. - self.expect("frame variable -s -g -a", VARIABLES_DISPLAYED_CORRECTLY, + self.expect("frame variable -t -s -g -a", VARIABLES_DISPLAYED_CORRECTLY, substrs = ['GLOBAL: (int) g_file_global_int = 42', 'GLOBAL: (const char *) g_file_global_cstr', '"g_file_global_cstr"', Modified: lldb/trunk/test/set_values/TestSetValues.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/set_values/TestSetValues.py?rev=116419&r1=116418&r2=116419&view=diff ============================================================================== --- lldb/trunk/test/set_values/TestSetValues.py (original) +++ lldb/trunk/test/set_values/TestSetValues.py Wed Oct 13 14:22:50 2010 @@ -72,8 +72,8 @@ substrs = [' resolved, hit count = 1']) # main.c:15 - # Check that 'frame variable' displays the correct data type and value. - self.expect("frame variable", VARIABLES_DISPLAYED_CORRECTLY, + # Check that 'frame variable -t' displays the correct data type and value. + self.expect("frame variable -t", VARIABLES_DISPLAYED_CORRECTLY, startstr = "(char) i = 'a'") # TODO: @@ -82,8 +82,8 @@ self.runCmd("continue") # main.c:36 - # Check that 'frame variable' displays the correct data type and value. - self.expect("frame variable", VARIABLES_DISPLAYED_CORRECTLY, + # Check that 'frame variable -t' displays the correct data type and value. + self.expect("frame variable -t", VARIABLES_DISPLAYED_CORRECTLY, patterns = ["\((short unsigned int|unsigned short)\) i = 33"]) # TODO: @@ -92,8 +92,8 @@ self.runCmd("continue") # main.c:57 - # Check that 'frame variable' displays the correct data type and value. - self.expect("frame variable", VARIABLES_DISPLAYED_CORRECTLY, + # Check that 'frame variable -t' displays the correct data type and value. + self.expect("frame variable -t", VARIABLES_DISPLAYED_CORRECTLY, startstr = "(long int) i = 33") # TODO: @@ -102,8 +102,8 @@ self.runCmd("continue") # main.c:78 - # Check that 'frame variable' displays the correct data type and value. - self.expect("frame variable", VARIABLES_DISPLAYED_CORRECTLY, + # Check that 'frame variable -t' displays the correct data type and value. + self.expect("frame variable -t", VARIABLES_DISPLAYED_CORRECTLY, startstr = "(double) i = 3.14159") # TODO: @@ -112,10 +112,10 @@ self.runCmd("continue") # main.c:85 - # Check that 'frame variable' displays the correct data type and value. + # Check that 'frame variable -t' displays the correct data type and value. # rdar://problem/8422727 # set_values test directory: 'frame variable' shows only (long double) i = - self.expect("frame variable", VARIABLES_DISPLAYED_CORRECTLY, + self.expect("frame variable -t", VARIABLES_DISPLAYED_CORRECTLY, startstr = "(long double) i = 3.14159") # TODO: Modified: lldb/trunk/test/types/AbstractBase.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/types/AbstractBase.py?rev=116419&r1=116418&r2=116419&view=diff ============================================================================== --- lldb/trunk/test/types/AbstractBase.py (original) +++ lldb/trunk/test/types/AbstractBase.py Wed Oct 13 14:22:50 2010 @@ -8,7 +8,7 @@ from lldbtest import * def Msg(var, val): - return "'frame variable %s' matches the output (from compiled code): %s" % (var, val) + return "'frame variable -t %s' matches the output (from compiled code): %s" % (var, val) class GenericTester(TestBase): @@ -70,14 +70,14 @@ # Now iterate through the golden list, comparing against the output from # 'frame variable var'. for var, val in gl: - self.runCmd("frame variable %s" % var) + self.runCmd("frame variable -t %s" % var) output = self.res.GetOutput() # The input type is in a canonical form as a set named atoms. # The display type string must conatin each and every element. # # Example: - # runCmd: frame variable a_array_bounded[0] + # runCmd: frame variable -t a_array_bounded[0] # output: (char) a_array_bounded[0] = 'a' # try: @@ -128,7 +128,7 @@ #self.runCmd("frame variable") # Now iterate through the golden list, comparing against the output from - # 'frame variable var'. + # 'expr var'. for var, val in gl: self.runCmd("expr %s" % var) output = self.res.GetOutput() Modified: lldb/trunk/test/unsigned_types/TestUnsignedTypes.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/unsigned_types/TestUnsignedTypes.py?rev=116419&r1=116418&r2=116419&view=diff ============================================================================== --- lldb/trunk/test/unsigned_types/TestUnsignedTypes.py (original) +++ lldb/trunk/test/unsigned_types/TestUnsignedTypes.py Wed Oct 13 14:22:50 2010 @@ -50,7 +50,7 @@ substrs = [' resolved, hit count = 1']) # Test that unsigned types display correctly. - self.expect("frame variable -a", VARIABLES_DISPLAYED_CORRECTLY, + self.expect("frame variable -t -a", VARIABLES_DISPLAYED_CORRECTLY, startstr = "(unsigned char) the_unsigned_char = 'c'", patterns = ["\((short unsigned int|unsigned short)\) the_unsigned_short = 99"], substrs = ["(unsigned int) the_unsigned_int = 99", From johnny.chen at apple.com Wed Oct 13 14:25:42 2010 From: johnny.chen at apple.com (Johnny Chen) Date: Wed, 13 Oct 2010 19:25:42 -0000 Subject: [Lldb-commits] [lldb] r116420 - /lldb/trunk/test/types/AbstractBase.py Message-ID: <20101013192542.4F8932A6C12C@llvm.org> Author: johnny Date: Wed Oct 13 14:25:42 2010 New Revision: 116420 URL: http://llvm.org/viewvc/llvm-project?rev=116420&view=rev Log: Fix these comments and the commented out code about 'frame variable -t', too. Modified: lldb/trunk/test/types/AbstractBase.py Modified: lldb/trunk/test/types/AbstractBase.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/types/AbstractBase.py?rev=116420&r1=116419&r2=116420&view=diff ============================================================================== --- lldb/trunk/test/types/AbstractBase.py (original) +++ lldb/trunk/test/types/AbstractBase.py Wed Oct 13 14:25:42 2010 @@ -59,16 +59,16 @@ #print "golden list:", gl # Bring the program to the point where we can issue a series of - # 'frame variable' command. + # 'frame variable -t' command. self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) self.runCmd("breakpoint set --name Puts") self.runCmd("run", RUN_SUCCEEDED) self.runCmd("thread step-out", STEP_OUT_SUCCEEDED) - #self.runCmd("frame variable") + #self.runCmd("frame variable -t") # Now iterate through the golden list, comparing against the output from - # 'frame variable var'. + # 'frame variable -t var'. for var, val in gl: self.runCmd("frame variable -t %s" % var) output = self.res.GetOutput() @@ -119,13 +119,13 @@ #print "golden list:", gl # Bring the program to the point where we can issue a series of - # 'frame variable' command. + # 'expr' command. self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) self.runCmd("breakpoint set --name Puts") self.runCmd("run", RUN_SUCCEEDED) self.runCmd("thread step-out", STEP_OUT_SUCCEEDED) - #self.runCmd("frame variable") + #self.runCmd("frame variable -t") # Now iterate through the golden list, comparing against the output from # 'expr var'. From ctice at apple.com Wed Oct 13 15:44:39 2010 From: ctice at apple.com (Caroline Tice) Date: Wed, 13 Oct 2010 20:44:39 -0000 Subject: [Lldb-commits] [lldb] r116430 - in /lldb/trunk: include/lldb/lldb-enumerations.h source/Commands/CommandObjectProcess.cpp source/Interpreter/CommandObject.cpp source/Target/Process.cpp Message-ID: <20101013204439.481C72A6C12C@llvm.org> Author: ctice Date: Wed Oct 13 15:44:39 2010 New Revision: 116430 URL: http://llvm.org/viewvc/llvm-project?rev=116430&view=rev Log: Add new argument type, eArgSignalName, Add missing break statment to case statement in Process::ShouldBroadcastEvent. Add new command, "process handle" to allow users to control process behavior on the receipt of various Unix signals (whether the process should stop; whether the process should be passed the signal; whether the debugger user should be notified that the signal came in). Modified: lldb/trunk/include/lldb/lldb-enumerations.h lldb/trunk/source/Commands/CommandObjectProcess.cpp lldb/trunk/source/Interpreter/CommandObject.cpp lldb/trunk/source/Target/Process.cpp Modified: lldb/trunk/include/lldb/lldb-enumerations.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/lldb-enumerations.h?rev=116430&r1=116429&r2=116430&view=diff ============================================================================== --- lldb/trunk/include/lldb/lldb-enumerations.h (original) +++ lldb/trunk/include/lldb/lldb-enumerations.h Wed Oct 13 15:44:39 2010 @@ -558,6 +558,7 @@ eArgTypeSettingKey, eArgTypeSettingPrefix, eArgTypeSettingVariableName, + eArgTypeSignalName, eArgTypeShlibName, eArgTypeSourceFile, eArgTypeSortOrder, Modified: lldb/trunk/source/Commands/CommandObjectProcess.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Commands/CommandObjectProcess.cpp?rev=116430&r1=116429&r2=116430&view=diff ============================================================================== --- lldb/trunk/source/Commands/CommandObjectProcess.cpp (original) +++ lldb/trunk/source/Commands/CommandObjectProcess.cpp Wed Oct 13 15:44:39 2010 @@ -1080,6 +1080,245 @@ }; //------------------------------------------------------------------------- +// CommandObjectProcessHandle +//------------------------------------------------------------------------- + +class CommandObjectProcessHandle : public CommandObject +{ +public: + + class CommandOptions : public Options + { + public: + + CommandOptions () : + Options () + { + ResetOptionValues (); + } + + ~CommandOptions () + { + } + + Error + SetOptionValue (int option_idx, const char *option_arg) + { + Error error; + char short_option = (char) m_getopt_table[option_idx].val; + + switch (short_option) + { + case 's': + stop = option_arg; + break; + case 'n': + notify = option_arg; + break; + case 'p': + pass = option_arg; + break; + default: + error.SetErrorStringWithFormat("Invalid short option character '%c'.\n", short_option); + break; + } + return error; + } + + void + ResetOptionValues () + { + Options::ResetOptionValues(); + stop.clear(); + notify.clear(); + pass.clear(); + } + + const lldb::OptionDefinition* + GetDefinitions () + { + return g_option_table; + } + + // Options table: Required for subclasses of Options. + + static lldb::OptionDefinition g_option_table[]; + + // Instance variables to hold the values for command options. + + std::string stop; + std::string notify; + std::string pass; + }; + + + CommandObjectProcessHandle (CommandInterpreter &interpreter) : + CommandObject (interpreter, + "process handle", + "Update whether the process should or should not stop or notify or suppress various signals it receives from the OS.", + NULL) + { + CommandArgumentEntry arg; + CommandArgumentData signal_name_arg; + + signal_name_arg.arg_type = eArgTypeSignalName; + signal_name_arg.arg_repetition = eArgRepeatPlus; + + arg.push_back (signal_name_arg); + + m_arguments.push_back (arg); + } + + ~CommandObjectProcessHandle () + { + } + + Options * + GetOptions () + { + return &m_options; + } + + bool + VerifyCommandOptionValue (const std::string &option, int *real_value) + { + bool okay = true; + + if (strcasecmp (option.c_str(), "false") == 0) + *real_value = 0; + else if (strcasecmp (option.c_str(), "true") == 0) + *real_value = 1; + else + { + // If the value isn't 'true' or 'false', it had better be 0 or 1. + *real_value = Args::StringToUInt32 (option.c_str(), 3); + if (*real_value != 0 && *real_value != 1) + okay = false; + } + + return okay; + } + + bool + Execute (Args &signal_args, CommandReturnObject &result) + { + TargetSP target_sp = m_interpreter.GetDebugger().GetSelectedTarget(); + + if (!target_sp) + { + result.AppendError ("No current target;" + " cannot handle signals until you have a valid target and process.\n"); + result.SetStatus (eReturnStatusFailed); + return false; + } + + ProcessSP process_sp = target_sp->GetProcessSP(); + + if (!process_sp) + { + result.AppendError ("No current process; cannot handle signals until you have a valid process.\n"); + result.SetStatus (eReturnStatusFailed); + return false; + } + + if (m_options.stop.empty() + && m_options.notify.empty() + && m_options.pass.empty()) + { + result.AppendError ("No action specified (-s or -n or -q); no signal will be updated.\n"); + result.SetStatus (eReturnStatusFailed); + return false; + } + + size_t num_signals = signal_args.GetArgumentCount(); + if (num_signals == 0) + { + result.AppendError ("No signal specified to be updated.\n"); + result.SetStatus (eReturnStatusFailed); + return false; + } + + int stop_action = -1; // -1 means leave the current setting alone + int pass_action = -1; // -1 means leave the current setting alone + int notify_action = -1; // -1 means leave the current setting alone + + if (! m_options.stop.empty() + && ! VerifyCommandOptionValue (m_options.stop, &stop_action)) + { + result.AppendError ("Invalid argument for command option --stop; must be true or false.\n"); + result.SetStatus (eReturnStatusFailed); + return false; + } + + if (! m_options.notify.empty() + && ! VerifyCommandOptionValue (m_options.notify, ¬ify_action)) + { + result.AppendError ("Invalid argument for command option --notify; must be true or false.\n"); + result.SetStatus (eReturnStatusFailed); + return false; + } + + if (! m_options.pass.empty() + && ! VerifyCommandOptionValue (m_options.pass, &pass_action)) + { + result.AppendError ("Invalid argument for command option --pass; must be true or false.\n"); + result.SetStatus (eReturnStatusFailed); + return false; + } + + size_t num_args = signal_args.GetArgumentCount(); + UnixSignals &signals = process_sp->GetUnixSignals(); + int num_signals_set = 0; + + for (size_t i = 0; i < num_args; ++i) + { + int32_t signo = signals.GetSignalNumberFromName (signal_args.GetArgumentAtIndex (i)); + if (signo != LLDB_INVALID_SIGNAL_NUMBER) + { + // Casting the actions as bools here should be okay, because VerifyCommandOptionValue guarantees that + // the value is either 0 or 1. + if (stop_action != -1) + signals.SetShouldStop (signo, (bool) stop_action); + if (pass_action != -1) + { + if (pass_action == 1) // pass it down, so 'suppress' is false + signals.SetShouldSuppress (signo, false); + else if (pass_action == 0) // do not pass it down, so 'suppress' is true + signals.SetShouldSuppress (signo, true); + } + if (notify_action != -1) + signals.SetShouldNotify (signo, (bool) notify_action); + ++num_signals_set; + } + else + { + result.AppendErrorWithFormat ("Invalid signal name '%s'\n", signal_args.GetArgumentAtIndex (i)); + } + } + + if (num_signals_set > 0) + result.SetStatus (eReturnStatusSuccessFinishNoResult); + else + result.SetStatus (eReturnStatusFailed); + + return result.Succeeded(); + } + +protected: + + CommandOptions m_options; +}; + +lldb::OptionDefinition +CommandObjectProcessHandle::CommandOptions::g_option_table[] = +{ +{ LLDB_OPT_SET_1, false, "stop", 's', required_argument, NULL, 0, eArgTypeBoolean, "Whether or not the process should be stopped if the signal is received." }, +{ LLDB_OPT_SET_1, false, "notify", 'n', required_argument, NULL, 0, eArgTypeBoolean, "Whether or not the debugger should notify the user if the signal is received." }, +{ LLDB_OPT_SET_1, false, "pass", 'p', required_argument, NULL, 0, eArgTypeBoolean, "Whether or not the signal should be passed to the process." }, +{ 0, false, NULL, 0, 0, NULL, 0, eArgTypeNone, NULL } +}; + +//------------------------------------------------------------------------- // CommandObjectMultiwordProcess //------------------------------------------------------------------------- @@ -1094,6 +1333,7 @@ LoadSubCommand ("continue", CommandObjectSP (new CommandObjectProcessContinue (interpreter))); LoadSubCommand ("detach", CommandObjectSP (new CommandObjectProcessDetach (interpreter))); LoadSubCommand ("signal", CommandObjectSP (new CommandObjectProcessSignal (interpreter))); + LoadSubCommand ("handle", CommandObjectSP (new CommandObjectProcessHandle (interpreter))); LoadSubCommand ("status", CommandObjectSP (new CommandObjectProcessStatus (interpreter))); LoadSubCommand ("interrupt", CommandObjectSP (new CommandObjectProcessInterrupt (interpreter))); LoadSubCommand ("kill", CommandObjectSP (new CommandObjectProcessKill (interpreter))); Modified: lldb/trunk/source/Interpreter/CommandObject.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Interpreter/CommandObject.cpp?rev=116430&r1=116429&r2=116430&view=diff ============================================================================== --- lldb/trunk/source/Interpreter/CommandObject.cpp (original) +++ lldb/trunk/source/Interpreter/CommandObject.cpp Wed Oct 13 15:44:39 2010 @@ -647,6 +647,7 @@ { eArgTypeSettingKey, "setting-key", CommandCompletions::eNoCompletion, NULL, "A key into a settings variables that is a dictionary (try 'settings list' to see all the possible settings variables and their types)." }, { eArgTypeSettingPrefix, "setting-prefix", CommandCompletions::eNoCompletion, NULL, "The name of a settable internal debugger variable up to a dot ('.'), e.g. 'target.process.'" }, { eArgTypeSettingVariableName, "setting-variable-name", CommandCompletions::eNoCompletion, NULL, "The name of a settable internal debugger variable. Type 'settings list' to see a complete list of such variables." }, + { eArgTypeSignalName, "signal-name", CommandCompletions::eNoCompletion, NULL, "The name of a UNIX signal (e.g. SIGINT or SIGKILL) ." }, { eArgTypeShlibName, "shlib-name", CommandCompletions::eNoCompletion, NULL, "The name of a shared library." }, { eArgTypeSourceFile, "source-file", CommandCompletions::eNoCompletion, NULL, "The name of a source file.." }, { eArgTypeSortOrder, "sort-order", CommandCompletions::eNoCompletion, NULL, "Specify a sort order when dumping lists." }, Modified: lldb/trunk/source/Target/Process.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Target/Process.cpp?rev=116430&r1=116429&r2=116430&view=diff ============================================================================== --- lldb/trunk/source/Target/Process.cpp (original) +++ lldb/trunk/source/Target/Process.cpp Wed Oct 13 15:44:39 2010 @@ -1439,6 +1439,7 @@ { case eVoteYes: Process::ProcessEventData::SetRestartedInEvent (event_ptr, true); + break; case eVoteNoOpinion: case eVoteNo: return_value = false; From johnny.chen at apple.com Wed Oct 13 19:54:32 2010 From: johnny.chen at apple.com (Johnny Chen) Date: Thu, 14 Oct 2010 00:54:32 -0000 Subject: [Lldb-commits] [lldb] r116463 - /lldb/trunk/source/Target/Process.cpp Message-ID: <20101014005432.4DA032A6C12C@llvm.org> Author: johnny Date: Wed Oct 13 19:54:32 2010 New Revision: 116463 URL: http://llvm.org/viewvc/llvm-project?rev=116463&view=rev Log: Fix a regression introduced in r116430 with the added 'break' statement, which broke test/breakpoint_locations. Add a comment about intentional fall-through in the case statement. Modified: lldb/trunk/source/Target/Process.cpp Modified: lldb/trunk/source/Target/Process.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Target/Process.cpp?rev=116463&r1=116462&r2=116463&view=diff ============================================================================== --- lldb/trunk/source/Target/Process.cpp (original) +++ lldb/trunk/source/Target/Process.cpp Wed Oct 13 19:54:32 2010 @@ -1439,7 +1439,7 @@ { case eVoteYes: Process::ProcessEventData::SetRestartedInEvent (event_ptr, true); - break; + // Intentional fall-through here. case eVoteNoOpinion: case eVoteNo: return_value = false; From johnny.chen at apple.com Wed Oct 13 20:22:04 2010 From: johnny.chen at apple.com (Johnny Chen) Date: Thu, 14 Oct 2010 01:22:04 -0000 Subject: [Lldb-commits] [lldb] r116467 - in /lldb/trunk: source/Interpreter/CommandInterpreter.cpp test/lldbtest.py test/signal/TestSendSignal.py Message-ID: <20101014012204.1720C2A6C12C@llvm.org> Author: johnny Date: Wed Oct 13 20:22:03 2010 New Revision: 116467 URL: http://llvm.org/viewvc/llvm-project?rev=116467&view=rev Log: Add an initial version of test that exercise the lldb commands: 'process signal' and 'process handle'. The test suite would like to control the asynch/sync execution of the interpreter during the middle of the test method, so the CommandInterpreter::SetSynchronous(bool value) is modified to allow the mode to be changed more than once. In practice, it would be advisable to control the process and to set the async/sync mode from a single thread, too. Added: lldb/trunk/test/signal/TestSendSignal.py Modified: lldb/trunk/source/Interpreter/CommandInterpreter.cpp lldb/trunk/test/lldbtest.py Modified: lldb/trunk/source/Interpreter/CommandInterpreter.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Interpreter/CommandInterpreter.cpp?rev=116467&r1=116466&r2=116467&view=diff ============================================================================== --- lldb/trunk/source/Interpreter/CommandInterpreter.cpp (original) +++ lldb/trunk/source/Interpreter/CommandInterpreter.cpp Wed Oct 13 20:22:03 2010 @@ -1107,12 +1107,7 @@ void CommandInterpreter::SetSynchronous (bool value) { - static bool value_set_once = false; - if (!value_set_once) - { - value_set_once = true; - m_synchronous_execution = value; - } + m_synchronous_execution = value; } void Modified: lldb/trunk/test/lldbtest.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/lldbtest.py?rev=116467&r1=116466&r2=116467&view=diff ============================================================================== --- lldb/trunk/test/lldbtest.py (original) +++ lldb/trunk/test/lldbtest.py Wed Oct 13 20:22:03 2010 @@ -150,6 +150,8 @@ STOPPED_DUE_TO_BREAKPOINT = "Process state is stopped due to breakpoint" +STOPPED_DUE_TO_SIGNAL = "Process state is stopped due to signal" + STOPPED_DUE_TO_STEP_IN = "Process state is stopped due to step in" DATA_TYPES_DISPLAYED_CORRECTLY = "Data type(s) displayed correctly" Added: lldb/trunk/test/signal/TestSendSignal.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/signal/TestSendSignal.py?rev=116467&view=auto ============================================================================== --- lldb/trunk/test/signal/TestSendSignal.py (added) +++ lldb/trunk/test/signal/TestSendSignal.py Wed Oct 13 20:22:03 2010 @@ -0,0 +1,76 @@ +"""Test that lldb command 'process signal SIGUSR1' to send a signal to the inferior works.""" + +import os, time, signal +import unittest2 +import lldb +from lldbtest import * + +class SendSignalTestCase(TestBase): + + mydir = "signal" + + @unittest2.skipUnless(sys.platform.startswith("darwin"), "requires Darwin") + def test_with_dsym_and_run_command(self): + """Test that lldb command 'process signal SIGUSR1' sends a signal to the inferior process.""" + self.buildDsym() + self.send_signal() + + def test_with_dwarf_and_run_command(self): + """Test that lldb command 'process signal SIGUSR1' sends a signal to the inferior process.""" + self.buildDwarf() + self.send_signal() + + def setUp(self): + super(SendSignalTestCase, self).setUp() + # Find the line number to break inside main(). + self.line = line_number('main.c', 'Put breakpoint here') + + def send_signal(self): + """Test that lldb command 'process signal SIGUSR1' sends a signal to the inferior process.""" + + exe = os.path.join(os.getcwd(), "a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Break inside the main() function and immediately send a signal to the inferior after resuming. + self.expect("breakpoint set -f main.c -l %d" % self.line, + BREAKPOINT_CREATED, + startstr = "Breakpoint created: 1: file ='main.c', line = %d, locations = 1" % + self.line) + + self.runCmd("run", RUN_SUCCEEDED) + self.runCmd("thread backtrac") + + # 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']) + + self.runCmd("process status") + output = self.res.GetOutput() + pid = re.match("Process (.*) Stopped", output).group(1) + + # After resuming the process, immediately send a SIGUSR1 signal. + self.dbg.SetAsync(True) + self.runCmd("process continue") + self.runCmd("process handle -n False -p True -s True SIGUSR1") + #os.kill(int(pid), signal.SIGUSR1) + self.runCmd("process signal SIGUSR1") + + time.sleep(1) + self.dbg.SetAsync(False) + self.expect("process status", STOPPED_DUE_TO_SIGNAL, + startstr = "Process %s Stopped" % pid, + substrs = ['stop reason = signal SIGUSR1']) + self.expect("thread backtrace", STOPPED_DUE_TO_SIGNAL, + substrs = ['stop reason = signal SIGUSR1']) + + +if __name__ == '__main__': + import atexit + lldb.SBDebugger.Initialize() + atexit.register(lambda: lldb.SBDebugger.Terminate()) + unittest2.main() From johnny.chen at apple.com Thu Oct 14 10:58:53 2010 From: johnny.chen at apple.com (Johnny Chen) Date: Thu, 14 Oct 2010 15:58:53 -0000 Subject: [Lldb-commits] [lldb] r116481 - /lldb/trunk/test/signal/TestSendSignal.py Message-ID: <20101014155853.E94812A6C12C@llvm.org> Author: johnny Date: Thu Oct 14 10:58:53 2010 New Revision: 116481 URL: http://llvm.org/viewvc/llvm-project?rev=116481&view=rev Log: Add more comments and wait a little bit after resuming the inferior process before sending it a signal. Modified: lldb/trunk/test/signal/TestSendSignal.py Modified: lldb/trunk/test/signal/TestSendSignal.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/signal/TestSendSignal.py?rev=116481&r1=116480&r2=116481&view=diff ============================================================================== --- lldb/trunk/test/signal/TestSendSignal.py (original) +++ lldb/trunk/test/signal/TestSendSignal.py Thu Oct 14 10:58:53 2010 @@ -53,14 +53,23 @@ output = self.res.GetOutput() pid = re.match("Process (.*) Stopped", output).group(1) - # After resuming the process, immediately send a SIGUSR1 signal. + # After resuming the process, send it a SIGUSR1 signal. + + # It is necessary at this point to make command interpreter interaction + # be asynchronous, because we want to resume the process and to send it + # a signal. self.dbg.SetAsync(True) self.runCmd("process continue") + # Insert a delay of 1 second before doing the signaling stuffs. + time.sleep(1) + self.runCmd("process handle -n False -p True -s True SIGUSR1") #os.kill(int(pid), signal.SIGUSR1) self.runCmd("process signal SIGUSR1") + # Insert a delay of 1 second before checking the process status. time.sleep(1) + # Make the interaction mode be synchronous again. self.dbg.SetAsync(False) self.expect("process status", STOPPED_DUE_TO_SIGNAL, startstr = "Process %s Stopped" % pid, From johnny.chen at apple.com Thu Oct 14 11:36:49 2010 From: johnny.chen at apple.com (Johnny Chen) Date: Thu, 14 Oct 2010 16:36:49 -0000 Subject: [Lldb-commits] [lldb] r116485 - in /lldb/trunk: scripts/Python/append-debugger-id.py test/dotest.py Message-ID: <20101014163649.E4D8D2A6C12E@llvm.org> Author: johnny Date: Thu Oct 14 11:36:49 2010 New Revision: 116485 URL: http://llvm.org/viewvc/llvm-project?rev=116485&view=rev Log: Change the call within lldb.py to 'SBDebugger.Initialize()' from 'lldb.SBDebugger.Initialize()'. Inside the lldb module, there's no need (and as a matter of fact, incorrect) to specify the 'lldb' module name. Comment out the call to lldb.SBDebugger.Initialize() within the test driver itself, since it is already done when we import the lldb.py module. Modified: lldb/trunk/scripts/Python/append-debugger-id.py lldb/trunk/test/dotest.py Modified: lldb/trunk/scripts/Python/append-debugger-id.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/scripts/Python/append-debugger-id.py?rev=116485&r1=116484&r2=116485&view=diff ============================================================================== --- lldb/trunk/scripts/Python/append-debugger-id.py (original) +++ lldb/trunk/scripts/Python/append-debugger-id.py Thu Oct 14 11:36:49 2010 @@ -5,6 +5,9 @@ # module (which was automatically generated via running swig), and # initializes it to 0. # +# It also calls SBDebugger.Initialize() to initialize the lldb debugger +# subsystem. +# import sys @@ -21,7 +24,7 @@ print "Error: Unable to open file for appending: " + output_name else: f_out.write ("debugger_unique_id = 0\n"); - f_out.write ("lldb.SBDebugger.Initialize()\n"); + f_out.write ("SBDebugger.Initialize()\n"); try: f_out.close() except IOError: Modified: lldb/trunk/test/dotest.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/dotest.py?rev=116485&r1=116484&r2=116485&view=diff ============================================================================== --- lldb/trunk/test/dotest.py (original) +++ lldb/trunk/test/dotest.py Thu Oct 14 11:36:49 2010 @@ -488,7 +488,9 @@ # For the time being, let's bracket the test runner within the # lldb.SBDebugger.Initialize()/Terminate() pair. import lldb, atexit -lldb.SBDebugger.Initialize() +# Update: the act of importing lldb now executes lldb.SBDebugger.Initialize(), +# there's no need to call it a second time. +#lldb.SBDebugger.Initialize() atexit.register(lambda: lldb.SBDebugger.Terminate()) # Create a singleton SBDebugger in the lldb namespace. From johnny.chen at apple.com Thu Oct 14 11:57:08 2010 From: johnny.chen at apple.com (Johnny Chen) Date: Thu, 14 Oct 2010 16:57:08 -0000 Subject: [Lldb-commits] [lldb] r116486 - /lldb/trunk/scripts/Python/append-debugger-id.py Message-ID: <20101014165709.02E2C2A6C12C@llvm.org> Author: johnny Date: Thu Oct 14 11:57:08 2010 New Revision: 116486 URL: http://llvm.org/viewvc/llvm-project?rev=116486&view=rev Log: Wrap the file writing operations inside a with statement to simplify code. Modified: lldb/trunk/scripts/Python/append-debugger-id.py Modified: lldb/trunk/scripts/Python/append-debugger-id.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/scripts/Python/append-debugger-id.py?rev=116486&r1=116485&r2=116486&view=diff ============================================================================== --- lldb/trunk/scripts/Python/append-debugger-id.py (original) +++ lldb/trunk/scripts/Python/append-debugger-id.py Thu Oct 14 11:57:08 2010 @@ -18,14 +18,6 @@ # print "output_name is '" + output_name + "'" -try: - f_out = open (output_name, 'a') -except IOError: - print "Error: Unable to open file for appending: " + output_name -else: - f_out.write ("debugger_unique_id = 0\n"); - f_out.write ("SBDebugger.Initialize()\n"); - try: - f_out.close() - except IOError: - print "Error occurred while close file." +with open(output_name, 'a') as f_out: + f_out.write("debugger_unique_id = 0\n") + f_out.write("SBDebugger.Initialize()\n") From johnny.chen at apple.com Thu Oct 14 12:31:24 2010 From: johnny.chen at apple.com (Johnny Chen) Date: Thu, 14 Oct 2010 17:31:24 -0000 Subject: [Lldb-commits] [lldb] r116490 - in /lldb/trunk/test: array_types/ bitfields/ breakpoint_command/ breakpoint_locations/ class_types/ enum_types/ foundation/ function_types/ global_variables/ macosx/universal/ set_values/ signal/ stl/ struct_types/ unsigned_types/ Message-ID: <20101014173124.7DD922A6C12C@llvm.org> Author: johnny Date: Thu Oct 14 12:31:24 2010 New Revision: 116490 URL: http://llvm.org/viewvc/llvm-project?rev=116490&view=rev Log: Make calling the super class's setUp() method less fragile. Modified: lldb/trunk/test/array_types/TestArrayTypes.py lldb/trunk/test/bitfields/TestBitfields.py lldb/trunk/test/breakpoint_command/TestBreakpointCommand.py lldb/trunk/test/breakpoint_locations/TestBreakpointLocations.py lldb/trunk/test/class_types/TestClassTypes.py lldb/trunk/test/class_types/TestClassTypesDisassembly.py lldb/trunk/test/enum_types/TestEnumTypes.py lldb/trunk/test/foundation/TestObjCMethods.py lldb/trunk/test/function_types/TestFunctionTypes.py lldb/trunk/test/global_variables/TestGlobalVariables.py lldb/trunk/test/macosx/universal/TestUniversal.py lldb/trunk/test/set_values/TestSetValues.py lldb/trunk/test/signal/TestSendSignal.py lldb/trunk/test/stl/TestSTL.py lldb/trunk/test/stl/TestStdCXXDisassembly.py lldb/trunk/test/struct_types/TestStructTypes.py lldb/trunk/test/unsigned_types/TestUnsignedTypes.py Modified: lldb/trunk/test/array_types/TestArrayTypes.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/array_types/TestArrayTypes.py?rev=116490&r1=116489&r2=116490&view=diff ============================================================================== --- lldb/trunk/test/array_types/TestArrayTypes.py (original) +++ lldb/trunk/test/array_types/TestArrayTypes.py Thu Oct 14 12:31:24 2010 @@ -32,7 +32,8 @@ self.array_types_python() def setUp(self): - super(ArrayTypesTestCase, self).setUp() + # Call super's setUp(). + TestBase.setUp(self) # Find the line number to break inside main(). self.line = line_number('main.c', '// Set break point at this line.') Modified: lldb/trunk/test/bitfields/TestBitfields.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/bitfields/TestBitfields.py?rev=116490&r1=116489&r2=116490&view=diff ============================================================================== --- lldb/trunk/test/bitfields/TestBitfields.py (original) +++ lldb/trunk/test/bitfields/TestBitfields.py Thu Oct 14 12:31:24 2010 @@ -32,7 +32,8 @@ self.bitfields_variable_python() def setUp(self): - super(BitfieldsTestCase, self).setUp() + # Call super's setUp(). + TestBase.setUp(self) # Find the line number to break inside main(). self.line = line_number('main.c', '// Set break point at this line.') Modified: lldb/trunk/test/breakpoint_command/TestBreakpointCommand.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/breakpoint_command/TestBreakpointCommand.py?rev=116490&r1=116489&r2=116490&view=diff ============================================================================== --- lldb/trunk/test/breakpoint_command/TestBreakpointCommand.py (original) +++ lldb/trunk/test/breakpoint_command/TestBreakpointCommand.py Thu Oct 14 12:31:24 2010 @@ -27,7 +27,8 @@ self.breakpoint_command_sequence() def setUp(self): - super(BreakpointCommandTestCase, self).setUp() + # Call super's setUp(). + TestBase.setUp(self) # Find the line number to break inside main(). self.line = line_number('main.c', '// Set break point at this line.') Modified: lldb/trunk/test/breakpoint_locations/TestBreakpointLocations.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/breakpoint_locations/TestBreakpointLocations.py?rev=116490&r1=116489&r2=116490&view=diff ============================================================================== --- lldb/trunk/test/breakpoint_locations/TestBreakpointLocations.py (original) +++ lldb/trunk/test/breakpoint_locations/TestBreakpointLocations.py Thu Oct 14 12:31:24 2010 @@ -23,7 +23,8 @@ self.breakpoint_locations_test() def setUp(self): - super(BreakpointLocationsTestCase, self).setUp() + # Call super's setUp(). + TestBase.setUp(self) # Find the line number to break inside main(). self.line = line_number('main.c', '// Set break point at this line.') Modified: lldb/trunk/test/class_types/TestClassTypes.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/class_types/TestClassTypes.py?rev=116490&r1=116489&r2=116490&view=diff ============================================================================== --- lldb/trunk/test/class_types/TestClassTypes.py (original) +++ lldb/trunk/test/class_types/TestClassTypes.py Thu Oct 14 12:31:24 2010 @@ -47,7 +47,8 @@ self.class_types_expr_parser() def setUp(self): - super(ClassTypesTestCase, self).setUp() + # Call super's setUp(). + TestBase.setUp(self) # Find the line number to break for main.cpp. self.line = line_number('main.cpp', '// Set break point at this line.') Modified: lldb/trunk/test/class_types/TestClassTypesDisassembly.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/class_types/TestClassTypesDisassembly.py?rev=116490&r1=116489&r2=116490&view=diff ============================================================================== --- lldb/trunk/test/class_types/TestClassTypesDisassembly.py (original) +++ lldb/trunk/test/class_types/TestClassTypesDisassembly.py Thu Oct 14 12:31:24 2010 @@ -34,7 +34,8 @@ self.disassemble_call_stack_api() def setUp(self): - super(IterateFrameAndDisassembleTestCase, self).setUp() + # Call super's setUp(). + TestBase.setUp(self) # Find the line number to break for main.cpp. self.line = line_number('main.cpp', '// Set break point at this line.') Modified: lldb/trunk/test/enum_types/TestEnumTypes.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/enum_types/TestEnumTypes.py?rev=116490&r1=116489&r2=116490&view=diff ============================================================================== --- lldb/trunk/test/enum_types/TestEnumTypes.py (original) +++ lldb/trunk/test/enum_types/TestEnumTypes.py Thu Oct 14 12:31:24 2010 @@ -23,7 +23,8 @@ self.image_lookup_for_enum_type() def setUp(self): - super(EnumTypesTestCase, self).setUp() + # Call super's setUp(). + TestBase.setUp(self) # Find the line number to break inside main(). self.line = line_number('main.c', '// Set break point at this line.') Modified: lldb/trunk/test/foundation/TestObjCMethods.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/foundation/TestObjCMethods.py?rev=116490&r1=116489&r2=116490&view=diff ============================================================================== --- lldb/trunk/test/foundation/TestObjCMethods.py (original) +++ lldb/trunk/test/foundation/TestObjCMethods.py Thu Oct 14 12:31:24 2010 @@ -85,7 +85,8 @@ substrs = ["Foundation`-[NSAutoreleasePool release]"]) def setUp(self): - super(FoundationTestCase, self).setUp() + # Call super's setUp(). + TestBase.setUp(self) # Find the line number to break inside main(). self.line = line_number('main.m', '// Set break point at this line.') Modified: lldb/trunk/test/function_types/TestFunctionTypes.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/function_types/TestFunctionTypes.py?rev=116490&r1=116489&r2=116490&view=diff ============================================================================== --- lldb/trunk/test/function_types/TestFunctionTypes.py (original) +++ lldb/trunk/test/function_types/TestFunctionTypes.py Thu Oct 14 12:31:24 2010 @@ -21,7 +21,8 @@ self.function_types() def setUp(self): - super(FunctionTypesTestCase, self).setUp() + # Call super's setUp(). + TestBase.setUp(self) # Find the line number to break inside main(). self.line = line_number('main.c', '// Set break point at this line.') Modified: lldb/trunk/test/global_variables/TestGlobalVariables.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/global_variables/TestGlobalVariables.py?rev=116490&r1=116489&r2=116490&view=diff ============================================================================== --- lldb/trunk/test/global_variables/TestGlobalVariables.py (original) +++ lldb/trunk/test/global_variables/TestGlobalVariables.py Thu Oct 14 12:31:24 2010 @@ -21,7 +21,8 @@ self.global_variables() def setUp(self): - super(GlobalVariablesTestCase, self).setUp() + # Call super's setUp(). + TestBase.setUp(self) # Find the line number to break inside main(). self.line = line_number('main.c', '// Set break point at this line.') Modified: lldb/trunk/test/macosx/universal/TestUniversal.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/macosx/universal/TestUniversal.py?rev=116490&r1=116489&r2=116490&view=diff ============================================================================== --- lldb/trunk/test/macosx/universal/TestUniversal.py (original) +++ lldb/trunk/test/macosx/universal/TestUniversal.py Thu Oct 14 12:31:24 2010 @@ -10,7 +10,8 @@ mydir = "macosx/universal" def setUp(self): - super(UniversalTestCase, self).setUp() + # Call super's setUp(). + TestBase.setUp(self) # Find the line number to break inside main(). self.line = line_number('main.c', '// Set break point at this line.') Modified: lldb/trunk/test/set_values/TestSetValues.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/set_values/TestSetValues.py?rev=116490&r1=116489&r2=116490&view=diff ============================================================================== --- lldb/trunk/test/set_values/TestSetValues.py (original) +++ lldb/trunk/test/set_values/TestSetValues.py Thu Oct 14 12:31:24 2010 @@ -21,7 +21,8 @@ self.set_values() def setUp(self): - super(SetValuesTestCase, self).setUp() + # Call super's setUp(). + TestBase.setUp(self) # Find the line numbers to break inside main(). self.line1 = line_number('main.c', '// Set break point #1.') self.line2 = line_number('main.c', '// Set break point #2.') Modified: lldb/trunk/test/signal/TestSendSignal.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/signal/TestSendSignal.py?rev=116490&r1=116489&r2=116490&view=diff ============================================================================== --- lldb/trunk/test/signal/TestSendSignal.py (original) +++ lldb/trunk/test/signal/TestSendSignal.py Thu Oct 14 12:31:24 2010 @@ -21,7 +21,8 @@ self.send_signal() def setUp(self): - super(SendSignalTestCase, self).setUp() + # Call super's setUp(). + TestBase.setUp(self) # Find the line number to break inside main(). self.line = line_number('main.c', 'Put breakpoint here') Modified: lldb/trunk/test/stl/TestSTL.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/stl/TestSTL.py?rev=116490&r1=116489&r2=116490&view=diff ============================================================================== --- lldb/trunk/test/stl/TestSTL.py (original) +++ lldb/trunk/test/stl/TestSTL.py Thu Oct 14 12:31:24 2010 @@ -23,7 +23,8 @@ self.step_into_stl() def setUp(self): - super(STLTestCase, self).setUp() + # 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.') Modified: lldb/trunk/test/stl/TestStdCXXDisassembly.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/stl/TestStdCXXDisassembly.py?rev=116490&r1=116489&r2=116490&view=diff ============================================================================== --- lldb/trunk/test/stl/TestStdCXXDisassembly.py (original) +++ lldb/trunk/test/stl/TestStdCXXDisassembly.py Thu Oct 14 12:31:24 2010 @@ -12,7 +12,8 @@ mydir = "stl" def setUp(self): - super(StdCXXDisassembleTestCase, self).setUp() + # 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.') Modified: lldb/trunk/test/struct_types/TestStructTypes.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/struct_types/TestStructTypes.py?rev=116490&r1=116489&r2=116490&view=diff ============================================================================== --- lldb/trunk/test/struct_types/TestStructTypes.py (original) +++ lldb/trunk/test/struct_types/TestStructTypes.py Thu Oct 14 12:31:24 2010 @@ -25,7 +25,8 @@ self.struct_types() def setUp(self): - super(StructTypesTestCase, self).setUp() + # Call super's setUp(). + TestBase.setUp(self) # Find the line number to break for main.c. self.line = line_number('main.c', '// Set break point at this line.') self.first_executable_line = line_number('main.c', Modified: lldb/trunk/test/unsigned_types/TestUnsignedTypes.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/unsigned_types/TestUnsignedTypes.py?rev=116490&r1=116489&r2=116490&view=diff ============================================================================== --- lldb/trunk/test/unsigned_types/TestUnsignedTypes.py (original) +++ lldb/trunk/test/unsigned_types/TestUnsignedTypes.py Thu Oct 14 12:31:24 2010 @@ -24,7 +24,8 @@ self.unsigned_types() def setUp(self): - super(UnsignedTypesTestCase, self).setUp() + # 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.') From ctice at apple.com Thu Oct 14 16:31:13 2010 From: ctice at apple.com (Caroline Tice) Date: Thu, 14 Oct 2010 21:31:13 -0000 Subject: [Lldb-commits] [lldb] r116520 - /lldb/trunk/source/Commands/CommandObjectProcess.cpp Message-ID: <20101014213113.C8A872A6C12C@llvm.org> Author: ctice Date: Thu Oct 14 16:31:13 2010 New Revision: 116520 URL: http://llvm.org/viewvc/llvm-project?rev=116520&view=rev Log: Modify "process handle" so that if no signals are specified it lists/updates them all, if no update commands are specified it just lists the current values, and show that it always shows the new values for a signal after it has been updated. Also updated the help text to match the new functionality. Modified: lldb/trunk/source/Commands/CommandObjectProcess.cpp Modified: lldb/trunk/source/Commands/CommandObjectProcess.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Commands/CommandObjectProcess.cpp?rev=116520&r1=116519&r2=116520&view=diff ============================================================================== --- lldb/trunk/source/Commands/CommandObjectProcess.cpp (original) +++ lldb/trunk/source/Commands/CommandObjectProcess.cpp Thu Oct 14 16:31:13 2010 @@ -1155,14 +1155,15 @@ CommandObjectProcessHandle (CommandInterpreter &interpreter) : CommandObject (interpreter, "process handle", - "Update whether the process should or should not stop or notify or suppress various signals it receives from the OS.", + "Show or update what the process and debugger should do with various signals received from the OS.", NULL) { + SetHelpLong ("If no signals are specified, update them all. If no update option is specified, list the current values.\n"); CommandArgumentEntry arg; CommandArgumentData signal_name_arg; signal_name_arg.arg_type = eArgTypeSignalName; - signal_name_arg.arg_repetition = eArgRepeatPlus; + signal_name_arg.arg_repetition = eArgRepeatStar; arg.push_back (signal_name_arg); @@ -1180,25 +1181,80 @@ } bool - VerifyCommandOptionValue (const std::string &option, int *real_value) + VerifyCommandOptionValue (const std::string &option, int &real_value) { bool okay = true; - if (strcasecmp (option.c_str(), "false") == 0) - *real_value = 0; - else if (strcasecmp (option.c_str(), "true") == 0) - *real_value = 1; + bool success = false; + bool tmp_value = Args::StringToBoolean (option.c_str(), false, &success); + + if (success && tmp_value) + real_value = 1; + else if (success && !tmp_value) + real_value = 0; else { // If the value isn't 'true' or 'false', it had better be 0 or 1. - *real_value = Args::StringToUInt32 (option.c_str(), 3); - if (*real_value != 0 && *real_value != 1) + real_value = Args::StringToUInt32 (option.c_str(), 3); + if (real_value != 0 && real_value != 1) okay = false; } return okay; } + void + PrintSignalHeader (Stream &str) + { + str.Printf ("NAME PASS STOP NOTIFY\n"); + str.Printf ("========== ===== ===== ======\n"); + } + + void + PrintSignal (Stream &str, int32_t signo, const char *sig_name, UnixSignals &signals) + { + bool stop; + bool suppress; + bool notify; + + str.Printf ("%-10s ", sig_name); + if (signals.GetSignalInfo (signo, suppress, stop, notify)) + { + bool pass = !suppress; + str.Printf ("%s %s %s", + (pass ? "true " : "false"), + (stop ? "true " : "false"), + (notify ? "true " : "false")); + } + str.Printf ("\n"); + } + + void + PrintSignalInformation (Stream &str, Args &signal_args, int num_valid_signals, UnixSignals &signals) + { + PrintSignalHeader (str); + + if (num_valid_signals > 0) + { + size_t num_args = signal_args.GetArgumentCount(); + for (size_t i = 0; i < num_args; ++i) + { + int32_t signo = signals.GetSignalNumberFromName (signal_args.GetArgumentAtIndex (i)); + if (signo != LLDB_INVALID_SIGNAL_NUMBER) + PrintSignal (str, signo, signal_args.GetArgumentAtIndex (i), signals); + } + } + else // Print info for ALL signals + { + int32_t signo = signals.GetFirstSignalNumber(); + while (signo != LLDB_INVALID_SIGNAL_NUMBER) + { + PrintSignal (str, signo, signals.GetSignalAsCString (signo), signals); + signo = signals.GetNextSignalNumber (signo); + } + } + } + bool Execute (Args &signal_args, CommandReturnObject &result) { @@ -1221,29 +1277,12 @@ return false; } - if (m_options.stop.empty() - && m_options.notify.empty() - && m_options.pass.empty()) - { - result.AppendError ("No action specified (-s or -n or -q); no signal will be updated.\n"); - result.SetStatus (eReturnStatusFailed); - return false; - } - - size_t num_signals = signal_args.GetArgumentCount(); - if (num_signals == 0) - { - result.AppendError ("No signal specified to be updated.\n"); - result.SetStatus (eReturnStatusFailed); - return false; - } - int stop_action = -1; // -1 means leave the current setting alone - int pass_action = -1; // -1 means leave the current setting alone + int pass_action = -1; // -1 means leave the current setting alone int notify_action = -1; // -1 means leave the current setting alone if (! m_options.stop.empty() - && ! VerifyCommandOptionValue (m_options.stop, &stop_action)) + && ! VerifyCommandOptionValue (m_options.stop, stop_action)) { result.AppendError ("Invalid argument for command option --stop; must be true or false.\n"); result.SetStatus (eReturnStatusFailed); @@ -1251,7 +1290,7 @@ } if (! m_options.notify.empty() - && ! VerifyCommandOptionValue (m_options.notify, ¬ify_action)) + && ! VerifyCommandOptionValue (m_options.notify, notify_action)) { result.AppendError ("Invalid argument for command option --notify; must be true or false.\n"); result.SetStatus (eReturnStatusFailed); @@ -1259,7 +1298,7 @@ } if (! m_options.pass.empty() - && ! VerifyCommandOptionValue (m_options.pass, &pass_action)) + && ! VerifyCommandOptionValue (m_options.pass, pass_action)) { result.AppendError ("Invalid argument for command option --pass; must be true or false.\n"); result.SetStatus (eReturnStatusFailed); @@ -1270,32 +1309,59 @@ UnixSignals &signals = process_sp->GetUnixSignals(); int num_signals_set = 0; - for (size_t i = 0; i < num_args; ++i) + if (num_args > 0) { - int32_t signo = signals.GetSignalNumberFromName (signal_args.GetArgumentAtIndex (i)); - if (signo != LLDB_INVALID_SIGNAL_NUMBER) + for (size_t i = 0; i < num_args; ++i) { - // Casting the actions as bools here should be okay, because VerifyCommandOptionValue guarantees that - // the value is either 0 or 1. - if (stop_action != -1) - signals.SetShouldStop (signo, (bool) stop_action); - if (pass_action != -1) + int32_t signo = signals.GetSignalNumberFromName (signal_args.GetArgumentAtIndex (i)); + if (signo != LLDB_INVALID_SIGNAL_NUMBER) + { + // Casting the actions as bools here should be okay, because VerifyCommandOptionValue guarantees + // the value is either 0 or 1. + if (stop_action != -1) + signals.SetShouldStop (signo, (bool) stop_action); + if (pass_action != -1) + { + bool suppress = ! ((bool) pass_action); + signals.SetShouldSuppress (signo, suppress); + } + if (notify_action != -1) + signals.SetShouldNotify (signo, (bool) notify_action); + ++num_signals_set; + } + else { - if (pass_action == 1) // pass it down, so 'suppress' is false - signals.SetShouldSuppress (signo, false); - else if (pass_action == 0) // do not pass it down, so 'suppress' is true - signals.SetShouldSuppress (signo, true); + result.AppendErrorWithFormat ("Invalid signal name '%s'\n", signal_args.GetArgumentAtIndex (i)); } - if (notify_action != -1) - signals.SetShouldNotify (signo, (bool) notify_action); - ++num_signals_set; } - else + } + else + { + // No signal specified, if any command options were specified, update ALL signals. + if ((notify_action != -1) || (stop_action != -1) || (pass_action != -1)) { - result.AppendErrorWithFormat ("Invalid signal name '%s'\n", signal_args.GetArgumentAtIndex (i)); + if (m_interpreter.Confirm ("Do you really want to update all the signals?", false)) + { + int32_t signo = signals.GetFirstSignalNumber(); + while (signo != LLDB_INVALID_SIGNAL_NUMBER) + { + if (notify_action != -1) + signals.SetShouldNotify (signo, (bool) notify_action); + if (stop_action != -1) + signals.SetShouldStop (signo, (bool) stop_action); + if (pass_action != -1) + { + bool suppress = ! ((bool) pass_action); + signals.SetShouldSuppress (signo, suppress); + } + signo = signals.GetNextSignalNumber (signo); + } + } } } + PrintSignalInformation (result.GetOutputStream(), signal_args, num_signals_set, signals); + if (num_signals_set > 0) result.SetStatus (eReturnStatusSuccessFinishNoResult); else From gclayton at apple.com Thu Oct 14 17:52:14 2010 From: gclayton at apple.com (Greg Clayton) Date: Thu, 14 Oct 2010 22:52:14 -0000 Subject: [Lldb-commits] [lldb] r116532 - in /lldb/trunk: include/lldb/API/ include/lldb/Core/ include/lldb/Symbol/ source/API/ source/Commands/ source/Core/ source/Expression/ source/Symbol/ test/array_types/ test/bitfields/ Message-ID: <20101014225214.8162F2A6C12C@llvm.org> Author: gclayton Date: Thu Oct 14 17:52:14 2010 New Revision: 116532 URL: http://llvm.org/viewvc/llvm-project?rev=116532&view=rev Log: Fixed an expression parsing issue where if you were stopped somewhere without debug information and you evaluated an expression, a crash would occur as a result of an unchecked pointer. Added the ability to get the expression path for a ValueObject. For a rectangle point child "x" the expression path would be something like: "rect.top_left.x". This will allow GUI and command lines to get ahold of the expression path for a value object without having to explicitly know about the hierarchy. This means the ValueObject base class now has a "ValueObject *m_parent;" member. All ValueObject subclasses now correctly track their lineage and are able to provide value expression paths as well. Added a new "--flat" option to the "frame variable" to allow for flat variable output. An example of the current and new outputs: (lldb) frame variable argc = 1 argv = 0x00007fff5fbffe80 pt = { x = 2 y = 3 } rect = { bottom_left = { x = 1 y = 2 } top_right = { x = 3 y = 4 } } (lldb) frame variable --flat argc = 1 argv = 0x00007fff5fbffe80 pt.x = 2 pt.y = 3 rect.bottom_left.x = 1 rect.bottom_left.y = 2 rect.top_right.x = 3 rect.top_right.y = 4 As you can see when there is a lot of hierarchy it can help flatten things out. Also if you want to use a member in an expression, you can copy the text from the "--flat" output and not have to piece it together manually. This can help when you want to use parts of the STL in expressions: (lldb) frame variable --flat argc = 1 argv = 0x00007fff5fbffea8 hello_world._M_dataplus._M_p = 0x0000000000000000 (lldb) expr hello_world._M_dataplus._M_p[0] == '\0' Modified: lldb/trunk/include/lldb/API/SBType.h lldb/trunk/include/lldb/Core/ValueObject.h lldb/trunk/include/lldb/Core/ValueObjectChild.h lldb/trunk/include/lldb/Core/ValueObjectRegister.h lldb/trunk/include/lldb/Symbol/ClangASTContext.h lldb/trunk/include/lldb/Symbol/Type.h lldb/trunk/source/API/SBFrame.cpp lldb/trunk/source/API/SBType.cpp lldb/trunk/source/Commands/CommandObjectExpression.cpp lldb/trunk/source/Commands/CommandObjectFrame.cpp lldb/trunk/source/Core/ValueObject.cpp lldb/trunk/source/Core/ValueObjectChild.cpp lldb/trunk/source/Core/ValueObjectConstResult.cpp lldb/trunk/source/Core/ValueObjectRegister.cpp lldb/trunk/source/Core/ValueObjectVariable.cpp lldb/trunk/source/Expression/ClangExpressionDeclMap.cpp lldb/trunk/source/Symbol/ClangASTContext.cpp lldb/trunk/source/Symbol/Type.cpp lldb/trunk/test/array_types/TestArrayTypes.py lldb/trunk/test/bitfields/TestBitfields.py Modified: lldb/trunk/include/lldb/API/SBType.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/API/SBType.h?rev=116532&r1=116531&r2=116532&view=diff ============================================================================== --- lldb/trunk/include/lldb/API/SBType.h (original) +++ lldb/trunk/include/lldb/API/SBType.h Thu Oct 14 17:52:14 2010 @@ -71,6 +71,9 @@ ~SBTypeMember (); bool + IsBaseClass (); + + bool IsValid (); void @@ -110,7 +113,7 @@ int32_t m_offset; uint32_t m_bit_size; uint32_t m_bit_offset; - + bool m_is_base_class; }; Modified: lldb/trunk/include/lldb/Core/ValueObject.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/Core/ValueObject.h?rev=116532&r1=116531&r2=116532&view=diff ============================================================================== --- lldb/trunk/include/lldb/Core/ValueObject.h (original) +++ lldb/trunk/include/lldb/Core/ValueObject.h Thu Oct 14 17:52:14 2010 @@ -82,6 +82,15 @@ IsPointerOrReferenceType (); virtual bool + IsBaseClass () + { + return false; + } + + virtual void + GetExpressionPath (Stream &s);//, ValueObject *child); + + virtual bool IsInScope (StackFrame *frame) { return true; @@ -199,7 +208,8 @@ bool show_types, bool show_location, bool use_objc, - bool scope_already_checked); + bool scope_already_checked, + bool flat_output); bool GetIsConstant () const @@ -225,10 +235,22 @@ m_format = format; } + ValueObject * + GetParent() + { + return m_parent; + } + + const ValueObject * + GetParent() const + { + return m_parent; + } protected: //------------------------------------------------------------------ // Classes that inherit from ValueObject can see and modify these //------------------------------------------------------------------ + ValueObject* m_parent; // The parent value object, or NULL if this has no parent lldb::user_id_t m_update_id; // An integer that specifies the update number for this value in // this value object list. If this value object is asked to update itself // it will first check if the update ID match the value object @@ -257,7 +279,7 @@ //------------------------------------------------------------------ // Constructors and Destructors //------------------------------------------------------------------ - ValueObject (); + ValueObject (ValueObject *parent); void SetName (const char *name); Modified: lldb/trunk/include/lldb/Core/ValueObjectChild.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/Core/ValueObjectChild.h?rev=116532&r1=116531&r2=116532&view=diff ============================================================================== --- lldb/trunk/include/lldb/Core/ValueObjectChild.h (original) +++ lldb/trunk/include/lldb/Core/ValueObjectChild.h Thu Oct 14 17:52:14 2010 @@ -31,7 +31,8 @@ uint32_t byte_size, int32_t byte_offset, uint32_t bitfield_bit_size, - uint32_t bitfield_bit_offset); + uint32_t bitfield_bit_offset, + bool is_base_class); virtual ~ValueObjectChild(); @@ -69,8 +70,13 @@ virtual bool IsInScope (StackFrame *frame); + virtual bool + IsBaseClass () + { + return m_is_base_class; + } + protected: - ValueObject* m_parent; // The parent value object of which this is a child of. clang::ASTContext *m_clang_ast; // The clang AST that the clang type comes from void *m_clang_type; // The type of the child in question within the parent (m_parent_sp) ConstString m_type_name; @@ -78,6 +84,7 @@ int32_t m_byte_offset; uint32_t m_bitfield_bit_size; uint32_t m_bitfield_bit_offset; + bool m_is_base_class; uint32_t GetByteOffset() const; Modified: lldb/trunk/include/lldb/Core/ValueObjectRegister.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/Core/ValueObjectRegister.h?rev=116532&r1=116531&r2=116532&view=diff ============================================================================== --- lldb/trunk/include/lldb/Core/ValueObjectRegister.h (original) +++ lldb/trunk/include/lldb/Core/ValueObjectRegister.h Thu Oct 14 17:52:14 2010 @@ -26,7 +26,7 @@ class ValueObjectRegisterContext : public ValueObject { public: - ValueObjectRegisterContext (RegisterContext *reg_ctx); + ValueObjectRegisterContext (ValueObject *parent, RegisterContext *reg_ctx); virtual ~ValueObjectRegisterContext(); @@ -71,7 +71,7 @@ class ValueObjectRegisterSet : public ValueObject { public: - ValueObjectRegisterSet (RegisterContext *reg_ctx, uint32_t set_idx); + ValueObjectRegisterSet (ValueObject *parent, RegisterContext *reg_ctx, uint32_t set_idx); virtual ~ValueObjectRegisterSet(); @@ -119,7 +119,7 @@ class ValueObjectRegister : public ValueObject { public: - ValueObjectRegister (RegisterContext *reg_ctx, uint32_t reg_num); + ValueObjectRegister (ValueObject *parent, RegisterContext *reg_ctx, uint32_t reg_num); virtual ~ValueObjectRegister(); Modified: lldb/trunk/include/lldb/Symbol/ClangASTContext.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/Symbol/ClangASTContext.h?rev=116532&r1=116531&r2=116532&view=diff ============================================================================== --- lldb/trunk/include/lldb/Symbol/ClangASTContext.h (original) +++ lldb/trunk/include/lldb/Symbol/ClangASTContext.h Thu Oct 14 17:52:14 2010 @@ -30,6 +30,26 @@ class ClangASTContext { public: + enum { + eTypeHasChildren = (1u << 0), + eTypeHasValue = (1u << 1), + eTypeIsArray = (1u << 2), + eTypeIsBlock = (1u << 3), + eTypeIsBuiltIn = (1u << 4), + eTypeIsClass = (1u << 5), + eTypeIsCPlusPlus = (1u << 6), + eTypeIsEnumeration = (1u << 7), + eTypeIsFuncPrototype = (1u << 8), + eTypeIsMember = (1u << 9), + eTypeIsObjC = (1u << 10), + eTypeIsPointer = (1u << 11), + eTypeIsReference = (1u << 12), + eTypeIsStructUnion = (1u << 13), + eTypeIsTemplate = (1u << 14), + eTypeIsTypedef = (1u << 15), + eTypeIsVector = (1u << 16) + }; + //------------------------------------------------------------------ // Constructors and Destructors //------------------------------------------------------------------ @@ -304,6 +324,10 @@ static bool IsAggregateType (lldb::clang_type_t clang_type); + // Returns a mask containing bits from the ClangASTContext::eTypeXXX enumerations + static uint32_t + GetTypeInfoMask (lldb::clang_type_t clang_type); + static uint32_t GetNumChildren (lldb::clang_type_t clang_type, bool omit_empty_base_classes); @@ -318,7 +342,8 @@ uint32_t &child_byte_size, int32_t &child_byte_offset, uint32_t &child_bitfield_bit_size, - uint32_t &child_bitfield_bit_offset); + uint32_t &child_bitfield_bit_offset, + bool &child_is_base_class); static lldb::clang_type_t GetChildClangTypeAtIndex (clang::ASTContext *ast_context, @@ -331,7 +356,8 @@ uint32_t &child_byte_size, int32_t &child_byte_offset, uint32_t &child_bitfield_bit_size, - uint32_t &child_bitfield_bit_offset); + uint32_t &child_bitfield_bit_offset, + bool &child_is_base_class); // Lookup a child given a name. This function will match base class names // and member member names in "clang_type" only, not descendants. @@ -529,6 +555,10 @@ IsFloatingPointType (lldb::clang_type_t clang_type, uint32_t &count, bool &is_complex); static bool + GetCXXClassName (lldb::clang_type_t clang_type, + std::string &class_name); + + static bool IsCXXClassType (lldb::clang_type_t clang_type); static bool Modified: lldb/trunk/include/lldb/Symbol/Type.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/Symbol/Type.h?rev=116532&r1=116531&r2=116532&view=diff ============================================================================== --- lldb/trunk/include/lldb/Symbol/Type.h (original) +++ lldb/trunk/include/lldb/Symbol/Type.h Thu Oct 14 17:52:14 2010 @@ -197,7 +197,8 @@ uint32_t &child_byte_size, int32_t &child_byte_offset, uint32_t &child_bitfield_bit_size, - uint32_t &child_bitfield_bit_offset); + uint32_t &child_bitfield_bit_offset, + bool &child_is_base_class); static int Compare(const Type &a, const Type &b); @@ -210,9 +211,11 @@ EncodingDataType m_encoding_uid_type; uint32_t m_encoding_uid; uint32_t m_byte_size; - bool m_is_forward_decl; Declaration m_decl; - lldb::clang_type_t m_clang_qual_type; + lldb::clang_type_t m_clang_type; + bool m_is_forward_decl:1, + m_encoding_type_forward_decl_resolved:1, + m_encoding_type_decl_resolved:1; Type * GetEncodingType (); Modified: lldb/trunk/source/API/SBFrame.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/API/SBFrame.cpp?rev=116532&r1=116531&r2=116532&view=diff ============================================================================== --- lldb/trunk/source/API/SBFrame.cpp (original) +++ lldb/trunk/source/API/SBFrame.cpp Thu Oct 14 17:52:14 2010 @@ -390,7 +390,7 @@ const uint32_t num_sets = reg_ctx->GetRegisterSetCount(); for (uint32_t set_idx = 0; set_idx < num_sets; ++set_idx) { - value_list.Append(ValueObjectSP (new ValueObjectRegisterSet (reg_ctx, set_idx))); + value_list.Append(ValueObjectSP (new ValueObjectRegisterSet (NULL, reg_ctx, set_idx))); } } } Modified: lldb/trunk/source/API/SBType.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/API/SBType.cpp?rev=116532&r1=116531&r2=116532&view=diff ============================================================================== --- lldb/trunk/source/API/SBType.cpp (original) +++ lldb/trunk/source/API/SBType.cpp Thu Oct 14 17:52:14 2010 @@ -83,6 +83,7 @@ int32_t child_byte_offset = 0; uint32_t child_bitfield_bit_size = 0; uint32_t child_bitfield_bit_offset = 0; + bool child_is_base_class = false; if (IsValid ()) { @@ -97,7 +98,8 @@ child_byte_size, child_byte_offset, child_bitfield_bit_size, - child_bitfield_bit_offset); + child_bitfield_bit_offset, + child_is_base_class); } @@ -110,6 +112,7 @@ member.m_offset = child_byte_offset; member.m_bit_size = child_bitfield_bit_size; member.m_bit_offset = child_bitfield_bit_offset; + member.m_is_base_class = child_is_base_class; } else { @@ -192,7 +195,9 @@ m_member_name (NULL), m_offset (0), m_bit_size (0), - m_bit_offset (0) + m_bit_offset (0), + m_is_base_class (false) + { } @@ -222,6 +227,7 @@ m_offset = 0; m_bit_size = 0; m_bit_offset = 0; + m_is_base_class = false; } bool @@ -248,6 +254,12 @@ return m_bit_offset; } +bool +SBTypeMember::IsBaseClass () +{ + return m_is_base_class; +} + size_t SBTypeMember::GetOffset () { Modified: lldb/trunk/source/Commands/CommandObjectExpression.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Commands/CommandObjectExpression.cpp?rev=116532&r1=116531&r2=116532&view=diff ============================================================================== --- lldb/trunk/source/Commands/CommandObjectExpression.cpp (original) +++ lldb/trunk/source/Commands/CommandObjectExpression.cpp Thu Oct 14 17:52:14 2010 @@ -250,8 +250,8 @@ m_options.show_types, // Show types when dumping? false, // Show locations of variables, no since this is a host address which we don't care to see m_options.print_object, // Print the objective C object? - true); // Scope is already checked. Const results are always in scope. - output_stream.EOL(); + true, // Scope is already checked. Const results are always in scope. + false); // Don't flatten output if (result) result->SetStatus (eReturnStatusSuccessFinishResult); } Modified: lldb/trunk/source/Commands/CommandObjectFrame.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Commands/CommandObjectFrame.cpp?rev=116532&r1=116531&r2=116532&view=diff ============================================================================== --- lldb/trunk/source/Commands/CommandObjectFrame.cpp (original) +++ lldb/trunk/source/Commands/CommandObjectFrame.cpp Thu Oct 14 17:52:14 2010 @@ -318,6 +318,7 @@ case 'L': show_location= true; break; case 'c': show_decl = true; break; case 'D': debug = true; break; + case 'f': flat_output = true; break; case 'd': max_depth = Args::StringToUInt32 (option_arg, UINT32_MAX, 0, &success); if (!success) @@ -362,6 +363,7 @@ show_location = false; show_decl = false; debug = false; + flat_output = false; max_depth = UINT32_MAX; ptr_depth = 0; globals.clear(); @@ -386,7 +388,8 @@ show_summary:1, show_location:1, show_decl:1, - debug:1; + debug:1, + flat_output:1; uint32_t max_depth; // The depth to print when dumping concrete (not pointers) aggreate values uint32_t ptr_depth; // The default depth that is dumped when we find pointers std::vector globals; @@ -502,8 +505,8 @@ m_options.show_types, m_options.show_location, m_options.use_objc, - false); - s.EOL(); + false, + m_options.flat_output); } } } @@ -561,8 +564,8 @@ m_options.show_types, m_options.show_location, m_options.use_objc, - false); - s.EOL(); + false, + m_options.flat_output); } } } @@ -731,9 +734,8 @@ m_options.show_types, m_options.show_location, m_options.use_objc, - false); - - s.EOL(); + false, + m_options.flat_output); } } else @@ -813,9 +815,8 @@ m_options.show_types, m_options.show_location, m_options.use_objc, - false); - - s.EOL(); + false, + m_options.flat_output); } } } @@ -849,6 +850,7 @@ { LLDB_OPT_SET_1, false, "objc", 'o', no_argument, NULL, 0, eArgTypeNone, "When looking up a variable by name (--name), print as an Objective-C object."}, { LLDB_OPT_SET_1, false, "ptr-depth", 'p', required_argument, NULL, 0, eArgTypeCount, "The number of pointers to be traversed when dumping values (default is zero)."}, { LLDB_OPT_SET_1, false, "regex", 'r', no_argument, NULL, 0, eArgTypeRegularExpression, "The argument for name lookups are regular expressions."}, +{ LLDB_OPT_SET_1, false, "flat", 'f', no_argument, NULL, 0, eArgTypeNone, "Display results in a flat format that uses expression paths for each variable or member."}, { 0, false, NULL, 0, 0, NULL, NULL, eArgTypeNone, NULL } }; #pragma mark CommandObjectMultiwordFrame Modified: lldb/trunk/source/Core/ValueObject.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Core/ValueObject.cpp?rev=116532&r1=116531&r2=116532&view=diff ============================================================================== --- lldb/trunk/source/Core/ValueObject.cpp (original) +++ lldb/trunk/source/Core/ValueObject.cpp Thu Oct 14 17:52:14 2010 @@ -42,8 +42,9 @@ //---------------------------------------------------------------------- // ValueObject constructor //---------------------------------------------------------------------- -ValueObject::ValueObject () : +ValueObject::ValueObject (ValueObject *parent) : UserID (++g_value_obj_uid), // Unique identifier for every value object + m_parent (parent), m_update_id (0), // Value object lists always start at 1, value objects start at zero m_name (), m_data (), @@ -354,6 +355,7 @@ int32_t child_byte_offset = 0; uint32_t child_bitfield_bit_size = 0; uint32_t child_bitfield_bit_offset = 0; + bool child_is_base_class = false; const bool transparent_pointers = synthetic_array_member == false; clang::ASTContext *clang_ast = GetClangAST(); void *clang_type = GetClangType(); @@ -368,7 +370,8 @@ child_byte_size, child_byte_offset, child_bitfield_bit_size, - child_bitfield_bit_offset); + child_bitfield_bit_offset, + child_is_base_class); if (child_clang_type) { if (synthetic_index) @@ -385,7 +388,8 @@ child_byte_size, child_byte_offset, child_bitfield_bit_size, - child_bitfield_bit_offset)); + child_bitfield_bit_offset, + child_is_base_class)); } return valobj_sp; } @@ -863,6 +867,46 @@ void +ValueObject::GetExpressionPath (Stream &s) +{ + if (m_parent) + { + m_parent->GetExpressionPath (s); + clang_type_t parent_clang_type = m_parent->GetClangType(); + if (parent_clang_type) + { + if (ClangASTContext::IsPointerType(parent_clang_type)) + { + s.PutCString("->"); + } + else if (ClangASTContext::IsAggregateType (parent_clang_type)) + { + if (ClangASTContext::IsArrayType (parent_clang_type) == false && + m_parent->IsBaseClass() == false) + s.PutChar('.'); + } + } + } + + if (IsBaseClass()) + { + clang_type_t clang_type = GetClangType(); + std::string cxx_class_name; + if (ClangASTContext::GetCXXClassName (clang_type, cxx_class_name)) + { + s << cxx_class_name.c_str() << "::"; + } + } + else + { + const char *name = GetName().AsCString(); + if (name) + s.PutCString(name); + } +} + + +void ValueObject::DumpValueObject ( Stream &s, @@ -875,33 +919,59 @@ bool show_types, bool show_location, bool use_objc, - bool scope_already_checked + bool scope_already_checked, + bool flat_output ) { if (valobj) { //const char *loc_cstr = valobj->GetLocationAsCString(); - if (show_location) + clang_type_t clang_type = valobj->GetClangType(); + + const Flags type_info_flags (ClangASTContext::GetTypeInfoMask (clang_type)); + const char *err_cstr = NULL; + const bool has_children = type_info_flags.IsSet (ClangASTContext::eTypeHasChildren); + const bool has_value = type_info_flags.IsSet (ClangASTContext::eTypeHasValue); + + const bool print_valobj = flat_output == false || has_value; + + if (print_valobj) { - s.Printf("%s: ", valobj->GetLocationAsCString(exe_scope)); - } + if (show_location) + { + s.Printf("%s: ", valobj->GetLocationAsCString(exe_scope)); + } - s.Indent(); + s.Indent(); - if (show_types) - s.Printf("(%s) ", valobj->GetTypeName().AsCString()); + if (show_types) + s.Printf("(%s) ", valobj->GetTypeName().AsCString()); - const char *name_cstr = root_valobj_name ? root_valobj_name : valobj->GetName().AsCString(""); - s.Printf ("%s = ", name_cstr); - if (!scope_already_checked && !valobj->IsInScope(exe_scope->CalculateStackFrame())) - { - s.PutCString("error: out of scope"); - return; + if (flat_output) + { + valobj->GetExpressionPath(s); + s.PutCString(" ="); + } + else + { + const char *name_cstr = root_valobj_name ? root_valobj_name : valobj->GetName().AsCString(""); + s.Printf ("%s =", name_cstr); + } + + if (!scope_already_checked && !valobj->IsInScope(exe_scope->CalculateStackFrame())) + { + err_cstr = "error: out of scope"; + } } - const char *val_cstr = valobj->GetValueAsCString(exe_scope); - const char *err_cstr = valobj->GetError().AsCString(); + const char *val_cstr = NULL; + + if (err_cstr == NULL) + { + val_cstr = valobj->GetValueAsCString(exe_scope); + err_cstr = valobj->GetError().AsCString(); + } if (err_cstr) { @@ -909,75 +979,99 @@ } else { - const char *sum_cstr = valobj->GetSummaryAsCString(exe_scope); - - const bool is_aggregate = ClangASTContext::IsAggregateType (valobj->GetClangType()); + if (print_valobj) + { + const char *sum_cstr = valobj->GetSummaryAsCString(exe_scope); - if (val_cstr) - s.PutCString(val_cstr); + if (val_cstr) + s.Printf(" %s", val_cstr); - if (sum_cstr) - s.Printf(" %s", sum_cstr); - - if (use_objc) - { - const char *object_desc = valobj->GetObjectDescription(exe_scope); - if (object_desc) - s.Printf("\n%s\n", object_desc); - else - s.Printf ("No description available.\n"); - return; + if (sum_cstr) + s.Printf(" %s", sum_cstr); + + if (use_objc) + { + const char *object_desc = valobj->GetObjectDescription(exe_scope); + if (object_desc) + s.Printf(" %s\n", object_desc); + else + s.Printf ("No description available.\n"); + return; + } } - if (curr_depth < max_depth) { - if (is_aggregate) - s.PutChar('{'); - - bool is_ptr_or_ref = ClangASTContext::IsPointerOrReferenceType (valobj->GetClangType()); + bool is_ptr_or_ref = type_info_flags.IsSet (ClangASTContext::eTypeIsPointer | ClangASTContext::eTypeIsReference); - if (is_ptr_or_ref && ptr_depth == 0) - return; - - const uint32_t num_children = valobj->GetNumChildren(); - if (num_children) + if (!is_ptr_or_ref || ptr_depth > 0) { - s.IndentMore(); - for (uint32_t idx=0; idxGetNumChildren(); + if (num_children) { - ValueObjectSP child_sp(valobj->GetChildAtIndex(idx, true)); - if (child_sp.get()) + if (flat_output) { - s.EOL(); - DumpValueObject (s, - exe_scope, - child_sp.get(), - NULL, - is_ptr_or_ref ? ptr_depth - 1 : ptr_depth, - curr_depth + 1, - max_depth, - show_types, - show_location, - false, - true); - if (idx + 1 < num_children) - s.PutChar(','); + if (print_valobj) + s.EOL(); + } + else + { + if (print_valobj) + s.PutCString(" {\n"); + s.IndentMore(); + } + + for (uint32_t idx=0; idxGetChildAtIndex(idx, true)); + if (child_sp.get()) + { + DumpValueObject (s, + exe_scope, + child_sp.get(), + NULL, + is_ptr_or_ref ? ptr_depth - 1 : ptr_depth, + curr_depth + 1, + max_depth, + show_types, + show_location, + false, + true, + flat_output); + } + } + + if (!flat_output) + { + s.IndentLess(); + s.Indent("}\n"); } } - s.IndentLess(); + else if (has_children) + { + // Aggregate, no children... + if (print_valobj) + s.PutCString("{}\n"); + } + else + { + if (print_valobj) + s.EOL(); + } + } - if (is_aggregate) - { + else + { + // We printed a pointer, but we are stopping and not printing + // and children of this pointer... s.EOL(); - s.Indent("}"); } } else { - if (is_aggregate) + if (has_children && print_valobj) { - s.PutCString("{...}"); + s.PutCString("{...}\n"); } } } Modified: lldb/trunk/source/Core/ValueObjectChild.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Core/ValueObjectChild.cpp?rev=116532&r1=116531&r2=116532&view=diff ============================================================================== --- lldb/trunk/source/Core/ValueObjectChild.cpp (original) +++ lldb/trunk/source/Core/ValueObjectChild.cpp Thu Oct 14 17:52:14 2010 @@ -33,16 +33,17 @@ uint32_t byte_size, int32_t byte_offset, uint32_t bitfield_bit_size, - uint32_t bitfield_bit_offset + uint32_t bitfield_bit_offset, + bool is_base_class ) : - ValueObject (), - m_parent (parent), + ValueObject (parent), m_clang_ast (clang_ast), m_clang_type (clang_type), m_byte_size (byte_size), m_byte_offset (byte_offset), m_bitfield_bit_size (bitfield_bit_size), - m_bitfield_bit_offset (bitfield_bit_offset) + m_bitfield_bit_offset (bitfield_bit_offset), + m_is_base_class (is_base_class) { m_name = name; } Modified: lldb/trunk/source/Core/ValueObjectConstResult.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Core/ValueObjectConstResult.cpp?rev=116532&r1=116531&r2=116532&view=diff ============================================================================== --- lldb/trunk/source/Core/ValueObjectConstResult.cpp (original) +++ lldb/trunk/source/Core/ValueObjectConstResult.cpp Thu Oct 14 17:52:14 2010 @@ -35,7 +35,7 @@ lldb::ByteOrder data_byte_order, uint8_t data_addr_size ) : - ValueObject (), + ValueObject (NULL), m_clang_ast (clang_ast), m_type_name () { @@ -50,7 +50,7 @@ } ValueObjectConstResult::ValueObjectConstResult (const Error& error) : - ValueObject (), + ValueObject (NULL), m_clang_ast (NULL), m_type_name () { Modified: lldb/trunk/source/Core/ValueObjectRegister.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Core/ValueObjectRegister.cpp?rev=116532&r1=116531&r2=116532&view=diff ============================================================================== --- lldb/trunk/source/Core/ValueObjectRegister.cpp (original) +++ lldb/trunk/source/Core/ValueObjectRegister.cpp Thu Oct 14 17:52:14 2010 @@ -29,8 +29,8 @@ #pragma mark ValueObjectRegisterContext -ValueObjectRegisterContext::ValueObjectRegisterContext (RegisterContext *reg_ctx) : - ValueObject (), +ValueObjectRegisterContext::ValueObjectRegisterContext (ValueObject *parent, RegisterContext *reg_ctx) : + ValueObject (parent), m_reg_ctx (reg_ctx) { assert (reg_ctx); @@ -93,7 +93,7 @@ const uint32_t num_children = GetNumChildren(); if (idx < num_children) - valobj_sp.reset (new ValueObjectRegisterSet(m_reg_ctx, idx)); + valobj_sp.reset (new ValueObjectRegisterSet(this, m_reg_ctx, idx)); return valobj_sp; } @@ -101,8 +101,8 @@ #pragma mark - #pragma mark ValueObjectRegisterSet -ValueObjectRegisterSet::ValueObjectRegisterSet (RegisterContext *reg_ctx, uint32_t reg_set_idx) : - ValueObject (), +ValueObjectRegisterSet::ValueObjectRegisterSet (ValueObject *parent, RegisterContext *reg_ctx, uint32_t reg_set_idx) : + ValueObject (parent), m_reg_ctx (reg_ctx), m_reg_set (NULL), m_reg_set_idx (reg_set_idx) @@ -195,7 +195,7 @@ { const uint32_t num_children = GetNumChildren(); if (idx < num_children) - valobj_sp.reset (new ValueObjectRegister(m_reg_ctx, m_reg_set->registers[idx])); + valobj_sp.reset (new ValueObjectRegister(this, m_reg_ctx, m_reg_set->registers[idx])); } return valobj_sp; } @@ -204,8 +204,8 @@ #pragma mark - #pragma mark ValueObjectRegister -ValueObjectRegister::ValueObjectRegister (RegisterContext *reg_ctx, uint32_t reg_num) : - ValueObject (), +ValueObjectRegister::ValueObjectRegister (ValueObject *parent, RegisterContext *reg_ctx, uint32_t reg_num) : + ValueObject (parent), m_reg_ctx (reg_ctx), m_reg_info (NULL), m_reg_num (reg_num), Modified: lldb/trunk/source/Core/ValueObjectVariable.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Core/ValueObjectVariable.cpp?rev=116532&r1=116531&r2=116532&view=diff ============================================================================== --- lldb/trunk/source/Core/ValueObjectVariable.cpp (original) +++ lldb/trunk/source/Core/ValueObjectVariable.cpp Thu Oct 14 17:52:14 2010 @@ -33,7 +33,7 @@ using namespace lldb_private; ValueObjectVariable::ValueObjectVariable (const lldb::VariableSP &var_sp) : - ValueObject(), + ValueObject(NULL), m_variable_sp(var_sp) { // Do not attempt to construct one of these objects with no variable! Modified: lldb/trunk/source/Expression/ClangExpressionDeclMap.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Expression/ClangExpressionDeclMap.cpp?rev=116532&r1=116531&r2=116532&view=diff ============================================================================== --- lldb/trunk/source/Expression/ClangExpressionDeclMap.cpp (original) +++ lldb/trunk/source/Expression/ClangExpressionDeclMap.cpp Thu Oct 14 17:52:14 2010 @@ -871,6 +871,9 @@ VariableList *var_list = frame.GetVariableList(true); + if (!var_list) + return NULL; + lldb::VariableSP var = var_list->FindVariable(name_cs); if (!var) Modified: lldb/trunk/source/Symbol/ClangASTContext.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Symbol/ClangASTContext.cpp?rev=116532&r1=116531&r2=116532&view=diff ============================================================================== --- lldb/trunk/source/Symbol/ClangASTContext.cpp (original) +++ lldb/trunk/source/Symbol/ClangASTContext.cpp Thu Oct 14 17:52:14 2010 @@ -1651,6 +1651,61 @@ } +uint32_t +ClangASTContext::GetTypeInfoMask (clang_type_t clang_type) +{ + if (clang_type == NULL) + return false; + + QualType qual_type (QualType::getFromOpaquePtr(clang_type)); + + const clang::Type::TypeClass type_class = qual_type->getTypeClass(); + switch (type_class) + { + case clang::Type::BlockPointer: return eTypeIsPointer | eTypeHasChildren | eTypeIsBlock; + case clang::Type::Builtin: return eTypeIsBuiltIn | eTypeHasValue; + case clang::Type::Complex: return eTypeHasChildren | eTypeIsBuiltIn | eTypeHasValue; + case clang::Type::ConstantArray: return eTypeHasChildren | eTypeIsArray; + case clang::Type::DependentName: return 0; + case clang::Type::DependentSizedArray: return eTypeHasChildren | eTypeIsArray; + case clang::Type::DependentSizedExtVector: return eTypeHasChildren | eTypeIsVector; + case clang::Type::DependentTemplateSpecialization: return eTypeIsTemplate; + case clang::Type::Decltype: return 0; + case clang::Type::Enum: return eTypeIsEnumeration | eTypeHasValue; + case clang::Type::Elaborated: return 0; + case clang::Type::ExtVector: return eTypeHasChildren | eTypeIsVector; + case clang::Type::FunctionProto: return eTypeIsFuncPrototype | eTypeHasValue; + case clang::Type::FunctionNoProto: return eTypeIsFuncPrototype | eTypeHasValue; + case clang::Type::IncompleteArray: return eTypeHasChildren | eTypeIsArray; + case clang::Type::InjectedClassName: return 0; + case clang::Type::LValueReference: return eTypeHasChildren | eTypeIsReference | eTypeHasValue; + case clang::Type::MemberPointer: return eTypeIsPointer | eTypeIsMember | eTypeHasValue; + case clang::Type::ObjCObjectPointer: return eTypeHasChildren | eTypeIsObjC | eTypeIsClass | eTypeIsPointer | eTypeHasValue; + case clang::Type::ObjCObject: return eTypeHasChildren | eTypeIsObjC | eTypeIsClass; + case clang::Type::ObjCInterface: return eTypeHasChildren | eTypeIsObjC | eTypeIsClass; + case clang::Type::Pointer: return eTypeHasChildren | eTypeIsPointer | eTypeHasValue; + case clang::Type::Record: + if (qual_type->getAsCXXRecordDecl()) + return eTypeHasChildren | eTypeIsClass | eTypeIsCPlusPlus; + else + return eTypeHasChildren | eTypeIsStructUnion; + break; + case clang::Type::RValueReference: return eTypeHasChildren | eTypeIsReference | eTypeHasValue; + case clang::Type::SubstTemplateTypeParm: return eTypeIsTemplate; + case clang::Type::TemplateTypeParm: return eTypeIsTemplate; + case clang::Type::TemplateSpecialization: return eTypeIsTemplate; + case clang::Type::Typedef: return eTypeIsTypedef | + ClangASTContext::GetTypeInfoMask (cast(qual_type)->LookThroughTypedefs().getAsOpaquePtr()); + case clang::Type::TypeOfExpr: return 0; + case clang::Type::TypeOf: return 0; + case clang::Type::UnresolvedUsing: return 0; + case clang::Type::VariableArray: return eTypeHasChildren | eTypeIsArray; + case clang::Type::Vector: return eTypeHasChildren | eTypeIsVector; + default: return 0; + } + return 0; +} + #pragma mark Aggregate Types @@ -1838,7 +1893,8 @@ uint32_t &child_byte_size, int32_t &child_byte_offset, uint32_t &child_bitfield_bit_size, - uint32_t &child_bitfield_bit_offset + uint32_t &child_bitfield_bit_offset, + bool &child_is_base_class ) { if (parent_clang_type) @@ -1853,7 +1909,8 @@ child_byte_size, child_byte_offset, child_bitfield_bit_size, - child_bitfield_bit_offset); + child_bitfield_bit_offset, + child_is_base_class); return NULL; } @@ -1870,7 +1927,8 @@ uint32_t &child_byte_size, int32_t &child_byte_offset, uint32_t &child_bitfield_bit_size, - uint32_t &child_bitfield_bit_offset + uint32_t &child_bitfield_bit_offset, + bool &child_is_base_class ) { if (parent_clang_type == NULL) @@ -1881,6 +1939,7 @@ uint32_t bit_offset; child_bitfield_bit_size = 0; child_bitfield_bit_offset = 0; + child_is_base_class = false; QualType parent_qual_type(QualType::getFromOpaquePtr(parent_clang_type)); const clang::Type::TypeClass parent_type_class = parent_qual_type->getTypeClass(); switch (parent_type_class) @@ -1956,6 +2015,7 @@ // Base classes biut sizes should be a multiple of 8 bits in size assert (clang_type_info_bit_size % 8 == 0); child_byte_size = clang_type_info_bit_size / 8; + child_is_base_class = true; return base_class->getType().getAsOpaquePtr(); } // We don't increment the child index in the for loop since we might @@ -2025,6 +2085,7 @@ child_byte_size = ivar_type_info.first / 8; child_byte_offset = 0; + child_is_base_class = true; return ivar_qual_type.getAsOpaquePtr(); } @@ -2087,7 +2148,8 @@ child_byte_size, child_byte_offset, child_bitfield_bit_size, - child_bitfield_bit_offset); + child_bitfield_bit_offset, + child_is_base_class); } else { @@ -2119,8 +2181,8 @@ { std::pair field_type_info = ast_context->getTypeInfo(array->getElementType()); - char element_name[32]; - ::snprintf (element_name, sizeof (element_name), "%s[%u]", parent_name ? parent_name : "", idx); + char element_name[64]; + ::snprintf (element_name, sizeof (element_name), "[%u]", idx); child_name.assign(element_name); assert(field_type_info.first % 8 == 0); @@ -2148,7 +2210,8 @@ child_byte_size, child_byte_offset, child_bitfield_bit_size, - child_bitfield_bit_offset); + child_bitfield_bit_offset, + child_is_base_class); } else { @@ -2182,7 +2245,8 @@ child_byte_size, child_byte_offset, child_bitfield_bit_size, - child_bitfield_bit_offset); + child_bitfield_bit_offset, + child_is_base_class); break; default: @@ -3411,6 +3475,26 @@ return false; } + +bool +ClangASTContext::GetCXXClassName (clang_type_t clang_type, std::string &class_name) +{ + if (clang_type) + { + QualType qual_type (QualType::getFromOpaquePtr(clang_type)); + + CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl(); + if (cxx_record_decl) + { + class_name.assign (cxx_record_decl->getIdentifier()->getNameStart()); + return true; + } + } + class_name.clear(); + return false; +} + + bool ClangASTContext::IsCXXClassType (clang_type_t clang_type) { Modified: lldb/trunk/source/Symbol/Type.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Symbol/Type.cpp?rev=116532&r1=116531&r2=116532&view=diff ============================================================================== --- lldb/trunk/source/Symbol/Type.cpp (original) +++ lldb/trunk/source/Symbol/Type.cpp Thu Oct 14 17:52:14 2010 @@ -49,9 +49,11 @@ m_encoding_uid_type (encoding_data_type), m_encoding_uid (encoding_data), m_byte_size (byte_size), - m_is_forward_decl (is_forward_decl), m_decl (decl), - m_clang_qual_type (clang_type) + m_clang_type (clang_type), + m_is_forward_decl (is_forward_decl), + m_encoding_type_forward_decl_resolved (false), + m_encoding_type_decl_resolved (false) { } @@ -66,7 +68,7 @@ m_byte_size (0), m_is_forward_decl (false), m_decl (), - m_clang_qual_type (NULL) + m_clang_type (NULL) { } @@ -86,7 +88,7 @@ m_byte_size = rhs.m_byte_size; m_is_forward_decl = rhs.m_is_forward_decl; m_decl = rhs.m_decl; - m_clang_qual_type = rhs.m_clang_qual_type; + m_clang_type = rhs.m_clang_type; } return *this; } @@ -107,10 +109,10 @@ bool show_fullpaths = (level == lldb::eDescriptionLevelVerbose); m_decl.Dump(s, show_fullpaths); - if (m_clang_qual_type) + if (m_clang_type) { *s << ", clang_type = \""; - ClangASTType::DumpTypeDescription (GetClangAST(), m_clang_qual_type, s); + ClangASTType::DumpTypeDescription (GetClangAST(), m_clang_type, s); *s << '"'; } else if (m_encoding_uid != LLDB_INVALID_UID) @@ -154,11 +156,11 @@ bool show_fullpaths = false; m_decl.Dump (s,show_fullpaths); - if (m_clang_qual_type) + if (m_clang_type) { - *s << ", clang_type = " << m_clang_qual_type << ' '; + *s << ", clang_type = " << m_clang_type << ' '; - ClangASTType::DumpTypeDescription (GetClangAST(), m_clang_qual_type, s); + ClangASTType::DumpTypeDescription (GetClangAST(), m_clang_type, s); } else if (m_encoding_uid != LLDB_INVALID_UID) { @@ -190,7 +192,7 @@ { if (ResolveClangType(true)) { - std::string type_name = ClangASTContext::GetTypeName (m_clang_qual_type); + std::string type_name = ClangASTContext::GetTypeName (m_clang_type); if (!type_name.empty()) m_name.SetCString (type_name.c_str()); } @@ -230,7 +232,7 @@ } lldb_private::ClangASTType::DumpValue (GetClangAST (), - m_clang_qual_type, + m_clang_type, exe_ctx, s, format == lldb::eFormatDefault ? GetFormat() : format, @@ -300,7 +302,7 @@ { if (!ResolveClangType()) return 0; - return ClangASTContext::GetNumChildren (m_clang_qual_type, omit_empty_base_classes); + return ClangASTContext::GetNumChildren (m_clang_type, omit_empty_base_classes); } @@ -308,7 +310,7 @@ lldb_private::Type::IsAggregateType () { if (ResolveClangType()) - return ClangASTContext::IsAggregateType (m_clang_qual_type); + return ClangASTContext::IsAggregateType (m_clang_type); return false; } @@ -318,7 +320,7 @@ // Make sure we resolve our type if it already hasn't been. if (!ResolveClangType()) return lldb::eFormatInvalid; - return lldb_private::ClangASTType::GetFormat (m_clang_qual_type); + return lldb_private::ClangASTType::GetFormat (m_clang_type); } @@ -330,7 +332,7 @@ if (!ResolveClangType()) return lldb::eEncodingInvalid; - return lldb_private::ClangASTType::GetEncoding (m_clang_qual_type, count); + return lldb_private::ClangASTType::GetEncoding (m_clang_type, count); } @@ -422,10 +424,7 @@ bool lldb_private::Type::ResolveClangType (bool forward_decl_is_ok) { -// static int g_depth = 0; -// g_depth++; -// printf ("%.*sType::ResolveClangType (forward = %i) uid = 0x%8.8x, name = %s\n", g_depth, "", forward_decl_is_ok, m_uid, m_name.AsCString()); - if (m_clang_qual_type == NULL) + if (m_clang_type == NULL) { TypeList *type_list = GetTypeList(); Type *encoding_type = GetEncodingType(); @@ -435,38 +434,38 @@ switch (m_encoding_uid_type) { case eEncodingIsUID: - m_clang_qual_type = encoding_type->GetClangType(); + m_clang_type = encoding_type->GetClangType(); break; case eEncodingIsConstUID: - m_clang_qual_type = ClangASTContext::AddConstModifier (encoding_type->GetClangForwardType()); + m_clang_type = ClangASTContext::AddConstModifier (encoding_type->GetClangForwardType()); break; case eEncodingIsRestrictUID: - m_clang_qual_type = ClangASTContext::AddRestrictModifier (encoding_type->GetClangForwardType()); + m_clang_type = ClangASTContext::AddRestrictModifier (encoding_type->GetClangForwardType()); break; case eEncodingIsVolatileUID: - m_clang_qual_type = ClangASTContext::AddVolatileModifier (encoding_type->GetClangForwardType()); + m_clang_type = ClangASTContext::AddVolatileModifier (encoding_type->GetClangForwardType()); break; case eEncodingIsTypedefUID: - m_clang_qual_type = type_list->CreateClangTypedefType (this, encoding_type); + m_clang_type = type_list->CreateClangTypedefType (this, encoding_type); // Clear the name so it can get fully qualified in case the // typedef is in a namespace. m_name.Clear(); break; case eEncodingIsPointerUID: - m_clang_qual_type = type_list->CreateClangPointerType (encoding_type); + m_clang_type = type_list->CreateClangPointerType (encoding_type); break; case eEncodingIsLValueReferenceUID: - m_clang_qual_type = type_list->CreateClangLValueReferenceType (encoding_type); + m_clang_type = type_list->CreateClangLValueReferenceType (encoding_type); break; case eEncodingIsRValueReferenceUID: - m_clang_qual_type = type_list->CreateClangRValueReferenceType (encoding_type); + m_clang_type = type_list->CreateClangRValueReferenceType (encoding_type); break; default: @@ -481,35 +480,35 @@ switch (m_encoding_uid_type) { case eEncodingIsUID: - m_clang_qual_type = void_clang_type; + m_clang_type = void_clang_type; break; case eEncodingIsConstUID: - m_clang_qual_type = ClangASTContext::AddConstModifier (void_clang_type); + m_clang_type = ClangASTContext::AddConstModifier (void_clang_type); break; case eEncodingIsRestrictUID: - m_clang_qual_type = ClangASTContext::AddRestrictModifier (void_clang_type); + m_clang_type = ClangASTContext::AddRestrictModifier (void_clang_type); break; case eEncodingIsVolatileUID: - m_clang_qual_type = ClangASTContext::AddVolatileModifier (void_clang_type); + m_clang_type = ClangASTContext::AddVolatileModifier (void_clang_type); break; case eEncodingIsTypedefUID: - m_clang_qual_type = type_list->GetClangASTContext().CreateTypedefType (m_name.AsCString(), void_clang_type, NULL); + m_clang_type = type_list->GetClangASTContext().CreateTypedefType (m_name.AsCString(), void_clang_type, NULL); break; case eEncodingIsPointerUID: - m_clang_qual_type = type_list->GetClangASTContext().CreatePointerType (void_clang_type); + m_clang_type = type_list->GetClangASTContext().CreatePointerType (void_clang_type); break; case eEncodingIsLValueReferenceUID: - m_clang_qual_type = type_list->GetClangASTContext().CreateLValueReferenceType (void_clang_type); + m_clang_type = type_list->GetClangASTContext().CreateLValueReferenceType (void_clang_type); break; case eEncodingIsRValueReferenceUID: - m_clang_qual_type = type_list->GetClangASTContext().CreateRValueReferenceType (void_clang_type); + m_clang_type = type_list->GetClangASTContext().CreateRValueReferenceType (void_clang_type); break; default: @@ -520,26 +519,51 @@ } // Check if we have a forward reference to a class/struct/union/enum? - if (m_is_forward_decl && m_clang_qual_type && !forward_decl_is_ok) + if (m_clang_type != NULL && + m_is_forward_decl == true && + forward_decl_is_ok == false) { m_is_forward_decl = false; - if (!ClangASTType::IsDefined (m_clang_qual_type)) + if (!ClangASTType::IsDefined (m_clang_type)) { // We have a forward declaration, we need to resolve it to a complete // definition. - m_symbol_file->ResolveClangOpaqueTypeDefinition (m_clang_qual_type); + m_symbol_file->ResolveClangOpaqueTypeDefinition (m_clang_type); } } // If we have an encoding type, then we need to make sure it is - // resolved appropriately - Type *encoding_type = GetEncodingType (); - if (encoding_type != NULL) - encoding_type->ResolveClangType (forward_decl_is_ok); - -// if (g_depth > 0) -// --g_depth; - return m_clang_qual_type != NULL; + // resolved appropriately. + if (m_encoding_type_decl_resolved == false) + { + if ((forward_decl_is_ok == true && !m_encoding_type_forward_decl_resolved) || + (forward_decl_is_ok == false)) + { + Type *encoding_type = GetEncodingType (); + if (encoding_type != NULL) + { + if (encoding_type->ResolveClangType (forward_decl_is_ok)) + { + // We have at least resolve the forward declaration for our + // encoding type... + m_encoding_type_forward_decl_resolved = true; + + // Check if we fully resolved our encoding type, and if so + // mark it as having been completely resolved. + if (forward_decl_is_ok == false) + m_encoding_type_decl_resolved = true; + } + } + else + { + // We don't have an encoding type, so mark everything as being + // resolved so we don't get into this if statement again + m_encoding_type_decl_resolved = true; + m_encoding_type_forward_decl_resolved = true; + } + } + } + return m_clang_type != NULL; } clang_type_t @@ -553,7 +577,8 @@ uint32_t &child_byte_size, int32_t &child_byte_offset, uint32_t &child_bitfield_bit_size, - uint32_t &child_bitfield_bit_offset + uint32_t &child_bitfield_bit_offset, + bool &child_is_base_class ) { if (!ResolveClangType()) @@ -562,7 +587,7 @@ std::string name_str; clang_type_t child_qual_type = GetClangASTContext().GetChildClangTypeAtIndex ( parent_name, - m_clang_qual_type, + m_clang_type, idx, transparent_pointers, omit_empty_base_classes, @@ -570,7 +595,8 @@ child_byte_size, child_byte_offset, child_bitfield_bit_size, - child_bitfield_bit_offset); + child_bitfield_bit_offset, + child_is_base_class); if (child_qual_type) { @@ -588,7 +614,7 @@ { const bool forward_decl_is_ok = false; ResolveClangType(forward_decl_is_ok); - return m_clang_qual_type; + return m_clang_type; } clang_type_t @@ -596,7 +622,7 @@ { const bool forward_decl_is_ok = true; ResolveClangType (forward_decl_is_ok); - return m_clang_qual_type; + return m_clang_type; } clang::ASTContext * Modified: lldb/trunk/test/array_types/TestArrayTypes.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/array_types/TestArrayTypes.py?rev=116532&r1=116531&r2=116532&view=diff ============================================================================== --- lldb/trunk/test/array_types/TestArrayTypes.py (original) +++ lldb/trunk/test/array_types/TestArrayTypes.py Thu Oct 14 17:52:14 2010 @@ -69,18 +69,18 @@ self.expect("frame variable -t strings", VARIABLES_DISPLAYED_CORRECTLY, startstr = '(char *[4])', - substrs = ['(char *) strings[0]', - '(char *) strings[1]', - '(char *) strings[2]', - '(char *) strings[3]', + substrs = ['(char *) [0]', + '(char *) [1]', + '(char *) [2]', + '(char *) [3]', 'Hello', 'Hola', 'Bonjour', 'Guten Tag']) self.expect("frame variable -t char_16", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ['(char) char_16[0]', - '(char) char_16[15]']) + substrs = ['(char) [0]', + '(char) [15]']) self.expect("frame variable -t ushort_matrix", VARIABLES_DISPLAYED_CORRECTLY, startstr = '(unsigned short [2][3])') Modified: lldb/trunk/test/bitfields/TestBitfields.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/bitfields/TestBitfields.py?rev=116532&r1=116531&r2=116532&view=diff ============================================================================== --- lldb/trunk/test/bitfields/TestBitfields.py (original) +++ lldb/trunk/test/bitfields/TestBitfields.py Thu Oct 14 17:52:14 2010 @@ -61,25 +61,25 @@ # This should display correctly. self.expect("frame variable -t bits", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ['(uint32_t:1) b1 = 1,', - '(uint32_t:2) b2 = 3,', - '(uint32_t:3) b3 = 7,', - '(uint32_t:4) b4 = 15,', - '(uint32_t:5) b5 = 31,', - '(uint32_t:6) b6 = 63,', - '(uint32_t:7) b7 = 127,', + substrs = ['(uint32_t:1) b1 = 1', + '(uint32_t:2) b2 = 3', + '(uint32_t:3) b3 = 7', + '(uint32_t:4) b4 = 15', + '(uint32_t:5) b5 = 31', + '(uint32_t:6) b6 = 63', + '(uint32_t:7) b7 = 127', '(uint32_t:4) four = 15']) # And so should this. # rdar://problem/8348251 self.expect("frame variable -t", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ['(uint32_t:1) b1 = 1,', - '(uint32_t:2) b2 = 3,', - '(uint32_t:3) b3 = 7,', - '(uint32_t:4) b4 = 15,', - '(uint32_t:5) b5 = 31,', - '(uint32_t:6) b6 = 63,', - '(uint32_t:7) b7 = 127,', + substrs = ['(uint32_t:1) b1 = 1', + '(uint32_t:2) b2 = 3', + '(uint32_t:3) b3 = 7', + '(uint32_t:4) b4 = 15', + '(uint32_t:5) b5 = 31', + '(uint32_t:6) b6 = 63', + '(uint32_t:7) b7 = 127', '(uint32_t:4) four = 15']) def bitfields_variable_python(self): From jingham at apple.com Thu Oct 14 18:45:03 2010 From: jingham at apple.com (Jim Ingham) Date: Thu, 14 Oct 2010 23:45:03 -0000 Subject: [Lldb-commits] [lldb] r116542 - in /lldb/trunk: include/lldb/Breakpoint/ include/lldb/Core/ include/lldb/Expression/ include/lldb/Target/ lldb.xcodeproj/ source/Breakpoint/ source/Commands/ source/Core/ source/Expression/ source/Target/ Message-ID: <20101014234503.BD12A2A6C12C@llvm.org> Author: jingham Date: Thu Oct 14 18:45:03 2010 New Revision: 116542 URL: http://llvm.org/viewvc/llvm-project?rev=116542&view=rev Log: Added support for breakpoint conditions. I also had to separate the "run the expression" part of ClangFunction::Execute from the "Gather the expression result" so that in the case of the Breakpoint condition I can move the condition evaluation into the normal thread plan processing. Also added support for remembering the "last set breakpoint" so that "break modify" will act on the last set breakpoint. Added: lldb/trunk/include/lldb/Target/ThreadPlanTestCondition.h lldb/trunk/source/Target/ThreadPlanTestCondition.cpp Modified: lldb/trunk/include/lldb/Breakpoint/Breakpoint.h lldb/trunk/include/lldb/Breakpoint/BreakpointLocation.h lldb/trunk/include/lldb/Breakpoint/BreakpointOptions.h lldb/trunk/include/lldb/Core/Event.h lldb/trunk/include/lldb/Expression/ClangExpressionVariable.h lldb/trunk/include/lldb/Expression/ClangUserExpression.h lldb/trunk/include/lldb/Target/Process.h lldb/trunk/include/lldb/Target/StopInfo.h lldb/trunk/include/lldb/Target/Target.h lldb/trunk/include/lldb/Target/Thread.h lldb/trunk/include/lldb/Target/ThreadPlan.h lldb/trunk/lldb.xcodeproj/project.pbxproj lldb/trunk/source/Breakpoint/Breakpoint.cpp lldb/trunk/source/Breakpoint/BreakpointLocation.cpp lldb/trunk/source/Breakpoint/BreakpointOptions.cpp lldb/trunk/source/Commands/CommandObjectBreakpoint.cpp lldb/trunk/source/Commands/CommandObjectBreakpoint.h lldb/trunk/source/Core/Event.cpp lldb/trunk/source/Expression/ClangExpressionParser.cpp lldb/trunk/source/Expression/ClangFunction.cpp lldb/trunk/source/Expression/ClangUserExpression.cpp lldb/trunk/source/Target/Process.cpp lldb/trunk/source/Target/StopInfo.cpp lldb/trunk/source/Target/Target.cpp Modified: lldb/trunk/include/lldb/Breakpoint/Breakpoint.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/Breakpoint/Breakpoint.h?rev=116542&r1=116541&r2=116542&view=diff ============================================================================== --- lldb/trunk/include/lldb/Breakpoint/Breakpoint.h (original) +++ lldb/trunk/include/lldb/Breakpoint/Breakpoint.h Thu Oct 14 18:45:03 2010 @@ -370,12 +370,41 @@ ClearCallback (); //------------------------------------------------------------------ - /// Set the condition expression to be checked when the breakpoint is hit. - /// @param[in] expression - /// The method that will get called when the breakpoint is hit. + /// Set the breakpoint's condition. + /// + /// @param[in] condition + /// The condition expression to evaluate when the breakpoint is hit. + /// Pass in NULL to clear the condition. //------------------------------------------------------------------ - void - SetCondition (void *expression); + void SetCondition (const char *condition); + + //------------------------------------------------------------------ + /// Test the breakpoint condition in the Execution context passed in. + /// + /// @param[in] exe_ctx + /// The execution context in which to evaluate this expression. + /// + /// @param[in] break_loc_sp + /// A shared pointer to the location that we are testing thsi condition for. + /// + /// @param[in] error + /// Error messages will be written to this stream. + /// + /// @return + /// A thread plan to run to test the condition or NULL if no condition. + //------------------------------------------------------------------ + ThreadPlan *GetThreadPlanToTestCondition (ExecutionContext &exe_ctx, + lldb::BreakpointLocationSP break_loc_sp, + Stream &error); + + //------------------------------------------------------------------ + /// Return a pointer to the text of the condition expression. + /// + /// @return + /// A pointer to the condition expression text, or NULL if no + // condition has been set. + //------------------------------------------------------------------ + const char *GetConditionText (); //------------------------------------------------------------------ // The next section are various utility functions. Modified: lldb/trunk/include/lldb/Breakpoint/BreakpointLocation.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/Breakpoint/BreakpointLocation.h?rev=116542&r1=116541&r2=116542&view=diff ============================================================================== --- lldb/trunk/include/lldb/Breakpoint/BreakpointLocation.h (original) +++ lldb/trunk/include/lldb/Breakpoint/BreakpointLocation.h Thu Oct 14 18:45:03 2010 @@ -160,13 +160,35 @@ ClearCallback (); //------------------------------------------------------------------ - /// Set the condition expression to be checked when the breakpoint is hit. + /// Set the breakpoint location's condition. /// - /// @param[in] expression - /// The method that will get called when the breakpoint is hit. + /// @param[in] condition + /// The condition expression to evaluate when the breakpoint is hit. //------------------------------------------------------------------ - void - SetCondition (void *condition); + void SetCondition (const char *condition); + + //------------------------------------------------------------------ + /// Test the breakpoint location's condition in the Execution context passed in. + /// + /// @param[in] exe_ctx + /// The execution context in which to evaluate this expression. + /// + /// @param[in] error + /// Error messages will be written to this stream. + /// + /// @return + /// A thread plan to run to test the condition, or NULL if there is no condition. + //------------------------------------------------------------------ + ThreadPlan *GetThreadPlanToTestCondition (ExecutionContext &exe_ctx, Stream &error); + + //------------------------------------------------------------------ + /// Return a pointer to the text of the condition expression. + /// + /// @return + /// A pointer to the condition expression text, or NULL if no + // condition has been set. + //------------------------------------------------------------------ + const char *GetConditionText (); //------------------------------------------------------------------ @@ -211,6 +233,9 @@ //------------------------------------------------------------------ bool IsResolved () const; + + lldb::BreakpointSiteSP + GetBreakpointSite() const; //------------------------------------------------------------------ // The next section are generic report functions. Modified: lldb/trunk/include/lldb/Breakpoint/BreakpointOptions.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/Breakpoint/BreakpointOptions.h?rev=116542&r1=116541&r2=116542&view=diff ============================================================================== --- lldb/trunk/include/lldb/Breakpoint/BreakpointOptions.h (original) +++ lldb/trunk/include/lldb/Breakpoint/BreakpointOptions.h Thu Oct 14 18:45:03 2010 @@ -18,6 +18,7 @@ #include "lldb/lldb-private.h" #include "lldb/Core/Baton.h" #include "lldb/Core/StringList.h" +#include "lldb/Expression/ClangUserExpression.h" namespace lldb_private { @@ -88,7 +89,46 @@ Baton *GetBaton (); const Baton *GetBaton () const; void ClearCallback (); - + + //------------------------------------------------------------------ + // Condition + //------------------------------------------------------------------ + //------------------------------------------------------------------ + /// Set the breakpoint option's condition. + /// + /// @param[in] condition + /// The condition expression to evaluate when the breakpoint is hit. + //------------------------------------------------------------------ + void SetCondition (const char *condition); + + //------------------------------------------------------------------ + /// Test the breakpoint condition in the Execution context passed in. + /// + /// @param[in] exe_ctx + /// The execution context in which to evaluate this expression. + /// + /// @param[in] break_loc_sp + /// A shared pointer to the location that we are testing thsi condition for. + /// + /// @param[in] error + /// Error messages will be written to this stream. + /// + /// @return + /// A thread plan to run to test the condition, or NULL if there is no thread plan. + //------------------------------------------------------------------ + ThreadPlan *GetThreadPlanToTestCondition (ExecutionContext &exe_ctx, + lldb::BreakpointLocationSP break_loc_sp, + Stream &error); + + //------------------------------------------------------------------ + /// Return a pointer to the text of the condition expression. + /// + /// @return + /// A pointer to the condition expression text, or NULL if no + // condition has been set. + //------------------------------------------------------------------ + const char *GetConditionText (); + //------------------------------------------------------------------ // Enabled/Ignore Count //------------------------------------------------------------------ @@ -107,6 +147,12 @@ void SetEnabled (bool enabled); + //------------------------------------------------------------------ + /// Set the breakpoint to ignore the next \a count breakpoint hits. + /// @param[in] count + /// The number of breakpoint hits to ignore. + //------------------------------------------------------------------ + void SetIgnoreCount (uint32_t n); @@ -119,12 +165,6 @@ GetIgnoreCount () const; //------------------------------------------------------------------ - /// Set the breakpoint to ignore the next \a count breakpoint hits. - /// @param[in] count - /// The number of breakpoint hits to ignore. - //------------------------------------------------------------------ - - //------------------------------------------------------------------ /// Return the current thread spec for this option. This will return NULL if the no thread /// specifications have been set for this Option yet. /// @return @@ -218,6 +258,7 @@ bool m_enabled; uint32_t m_ignore_count; // Number of times to ignore this breakpoint std::auto_ptr m_thread_spec_ap; // Thread for which this breakpoint will take + std::auto_ptr m_condition_ap; // The condition to test. }; Modified: lldb/trunk/include/lldb/Core/Event.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/Core/Event.h?rev=116542&r1=116541&r2=116542&view=diff ============================================================================== --- lldb/trunk/include/lldb/Core/Event.h (original) +++ lldb/trunk/include/lldb/Core/Event.h Thu Oct 14 18:45:03 2010 @@ -134,22 +134,52 @@ Dump (Stream *s) const; EventData * - GetData (); + GetData () + { + return m_data_ap.get(); + } const EventData * - GetData () const; + GetData () const + { + return m_data_ap.get(); + } + + void + SetData (EventData *new_data) + { + m_data_ap.reset (new_data); + } uint32_t - GetType () const; + GetType () const + { + return m_type; + } + + void + SetType (uint32_t new_type) + { + m_type = new_type; + } Broadcaster * - GetBroadcaster () const; - + GetBroadcaster () const + { + return m_broadcaster; + } + bool - BroadcasterIs (Broadcaster *broadcaster); + BroadcasterIs (Broadcaster *broadcaster) + { + return broadcaster == m_broadcaster; + } void - Clear(); + Clear() + { + m_data_ap.reset(); + } private: @@ -164,7 +194,11 @@ // know about it update the contained broadcaster so that events can be // popped off one queue and re-broadcast to others. void - SetBroadcaster (Broadcaster *broadcaster); + SetBroadcaster (Broadcaster *broadcaster) + { + m_broadcaster = broadcaster; + } + Broadcaster * m_broadcaster; // The broadcaster that sent this event uint32_t m_type; // The bit describing this event Modified: lldb/trunk/include/lldb/Expression/ClangExpressionVariable.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/Expression/ClangExpressionVariable.h?rev=116542&r1=116541&r2=116542&view=diff ============================================================================== --- lldb/trunk/include/lldb/Expression/ClangExpressionVariable.h (original) +++ lldb/trunk/include/lldb/Expression/ClangExpressionVariable.h Thu Oct 14 18:45:03 2010 @@ -89,7 +89,8 @@ /// The following values should stay valid for the life of the variable //---------------------------------------------------------------------- std::string m_name; ///< The name of the variable - TypeFromUser m_user_type; ///< The type of the variable according to some LLDB context; NULL if the type hasn't yet been migrated to one + TypeFromUser m_user_type; ///< The type of the variable according to some LLDB context; + ///< NULL if the type hasn't yet been migrated to one //---------------------------------------------------------------------- /// The following values indicate where the variable originally came from Modified: lldb/trunk/include/lldb/Expression/ClangUserExpression.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/Expression/ClangUserExpression.h?rev=116542&r1=116541&r2=116542&view=diff ============================================================================== --- lldb/trunk/include/lldb/Expression/ClangUserExpression.h (original) +++ lldb/trunk/include/lldb/Expression/ClangUserExpression.h Thu Oct 14 18:45:03 2010 @@ -24,6 +24,7 @@ #include "lldb/lldb-private.h" #include "lldb/Core/ClangForward.h" #include "lldb/Expression/ClangExpression.h" +#include "lldb/Expression/ClangExpressionVariable.h" #include "llvm/ExecutionEngine/JITMemoryManager.h" @@ -90,7 +91,15 @@ bool Execute (Stream &error_stream, ExecutionContext &exe_ctx, - ClangExpressionVariable *& result); + ClangExpressionVariable *&result); + + ThreadPlan * + GetThreadPlanToExecuteJITExpression (Stream &error_stream, + ExecutionContext &exe_ctx); + bool + FinalizeJITExecution (Stream &error_stream, + ExecutionContext &exe_ctx, + ClangExpressionVariable *&result); //------------------------------------------------------------------ /// Return the string that the parser should parse. Must be a full @@ -103,6 +112,15 @@ } //------------------------------------------------------------------ + /// Return the string that the user typed. + //------------------------------------------------------------------ + const char * + GetUserText () + { + return m_expr_text.c_str(); + } + + //------------------------------------------------------------------ /// Return the function name that should be used for executing the /// expression. Text() should contain the definition of this /// function. @@ -181,6 +199,12 @@ //------------------------------------------------------------------ void ScanContext(ExecutionContext &exe_ctx); + + bool + PrepareToExecuteJITExpression (Stream &error_stream, + ExecutionContext &exe_ctx, + lldb::addr_t &struct_address, + lldb::addr_t object_ptr); std::string m_expr_text; ///< The text of the expression, as typed by the user std::string m_transformed_text; ///< The text of the expression, as send to the parser Modified: lldb/trunk/include/lldb/Target/Process.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/Target/Process.h?rev=116542&r1=116541&r2=116542&view=diff ============================================================================== --- lldb/trunk/include/lldb/Target/Process.h (original) +++ lldb/trunk/include/lldb/Target/Process.h Thu Oct 14 18:45:03 2010 @@ -232,6 +232,7 @@ public ProcessInstanceSettings { friend class ThreadList; +friend class ClangFunction; // For WaitForStateChangeEventsPrivate public: @@ -316,7 +317,6 @@ static bool SetUpdateStateOnRemoval (Event *event_ptr); - private: void @@ -1592,12 +1592,12 @@ DynamicCheckerFunctions *GetDynamicCheckers() { - return m_dynamic_checkers.get(); + return m_dynamic_checkers_ap.get(); } void SetDynamicCheckers(DynamicCheckerFunctions *dynamic_checkers) { - m_dynamic_checkers.reset(dynamic_checkers); + m_dynamic_checkers_ap.reset(dynamic_checkers); } //------------------------------------------------------------------ @@ -1646,7 +1646,7 @@ BreakpointSiteList m_breakpoint_site_list; ///< This is the list of breakpoint locations we intend ///< to insert in the target. ClangPersistentVariables m_persistent_vars; ///< These are the persistent variables associated with this process for the expression parser. - std::auto_ptr m_dynamic_checkers; ///< The functions used by the expression parser to validate data that expressions use. + 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::ABISP m_abi_sp; Modified: lldb/trunk/include/lldb/Target/StopInfo.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/Target/StopInfo.h?rev=116542&r1=116541&r2=116542&view=diff ============================================================================== --- lldb/trunk/include/lldb/Target/StopInfo.h (original) +++ lldb/trunk/include/lldb/Target/StopInfo.h Thu Oct 14 18:45:03 2010 @@ -90,6 +90,10 @@ static lldb::StopInfoSP CreateStopReasonWithBreakpointSiteID (Thread &thread, lldb::break_id_t break_id); + // This creates a StopInfo for the thread where the should_stop is already set, and won't be recalculated. + static lldb::StopInfoSP + CreateStopReasonWithBreakpointSiteID (Thread &thread, lldb::break_id_t break_id, bool should_stop); + static lldb::StopInfoSP CreateStopReasonWithWatchpointID (Thread &thread, lldb::break_id_t watch_id); Modified: lldb/trunk/include/lldb/Target/Target.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/Target/Target.h?rev=116542&r1=116541&r2=116542&view=diff ============================================================================== --- lldb/trunk/include/lldb/Target/Target.h (original) +++ lldb/trunk/include/lldb/Target/Target.h Thu Oct 14 18:45:03 2010 @@ -204,6 +204,12 @@ const BreakpointList & GetBreakpointList(bool internal = false) const; + + lldb::BreakpointSP + GetLastCreatedBreakpoint () + { + return m_last_created_breakpoint; + } lldb::BreakpointSP GetBreakpointByID (lldb::break_id_t break_id); @@ -443,6 +449,7 @@ SectionLoadList m_section_load_list; BreakpointList m_breakpoint_list; BreakpointList m_internal_breakpoint_list; + lldb::BreakpointSP m_last_created_breakpoint; // We want to tightly control the process destruction process so // we can correctly tear down everything that we need to, so the only // class that knows about the process lifespan is this target class. Modified: lldb/trunk/include/lldb/Target/Thread.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/Target/Thread.h?rev=116542&r1=116541&r2=116542&view=diff ============================================================================== --- lldb/trunk/include/lldb/Target/Thread.h (original) +++ lldb/trunk/include/lldb/Target/Thread.h Thu Oct 14 18:45:03 2010 @@ -238,6 +238,12 @@ StopInfo * GetStopInfo (); + void + SetStopInfo (lldb::StopInfoSP stop_info_sp) + { + m_public_stop_info_sp = stop_info_sp; + } + bool ThreadStoppedForAReason (); Modified: lldb/trunk/include/lldb/Target/ThreadPlan.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/Target/ThreadPlan.h?rev=116542&r1=116541&r2=116542&view=diff ============================================================================== --- lldb/trunk/include/lldb/Target/ThreadPlan.h (original) +++ lldb/trunk/include/lldb/Target/ThreadPlan.h Thu Oct 14 18:45:03 2010 @@ -179,6 +179,8 @@ eThisThread } ThreadScope; + // We use these enums so that we can cast a base thread plan to it's real type without having to resort + // to dynamic casting. typedef enum { eKindGeneric, @@ -191,7 +193,8 @@ eKindStepInRange, eKindRunToAddress, eKindStepThrough, - eKindStepUntil + eKindStepUntil, + eKindTestCondition } ThreadPlanKind; Added: lldb/trunk/include/lldb/Target/ThreadPlanTestCondition.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/Target/ThreadPlanTestCondition.h?rev=116542&view=auto ============================================================================== --- lldb/trunk/include/lldb/Target/ThreadPlanTestCondition.h (added) +++ lldb/trunk/include/lldb/Target/ThreadPlanTestCondition.h Thu Oct 14 18:45:03 2010 @@ -0,0 +1,65 @@ +//===-- ThreadPlanTestCondition.h -----------------------------------*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#ifndef liblldb_ThreadPlanTestCondition_h_ +#define liblldb_ThreadPlanTestCondition_h_ + +// C Includes +// C++ Includes +// Other libraries and framework includes +// Project includes +#include "lldb/Core/AddressRange.h" +#include "lldb/Target/ExecutionContext.h" +#include "lldb/Expression/ClangUserExpression.h" +#include "lldb/Target/StackID.h" +#include "lldb/Target/Thread.h" +#include "lldb/Target/ThreadPlan.h" +#include "lldb/Target/ThreadPlanShouldStopHere.h" + +namespace lldb_private { + +class ThreadPlanTestCondition : public ThreadPlan +{ +public: + virtual ~ThreadPlanTestCondition (); + + ThreadPlanTestCondition (Thread &thread, + ExecutionContext &exe_ctx, + ClangUserExpression *expression, + lldb::BreakpointLocationSP break_loc_sp, + bool stop_others); + + virtual void GetDescription (Stream *s, lldb::DescriptionLevel level); + virtual bool ValidatePlan (Stream *error); + virtual bool PlanExplainsStop (); + virtual bool ShouldStop (Event *event_ptr); + virtual lldb::Vote ShouldReportStop (Event *event_ptr); + virtual bool StopOthers (); + virtual lldb::StateType RunState (); + virtual bool WillStop (); + virtual bool MischiefManaged (); + virtual void DidPush (); + +protected: + +private: + ClangUserExpression *m_expression; + ExecutionContext m_exe_ctx; + lldb::ThreadPlanSP m_expression_plan_sp; + lldb::BreakpointLocationSP m_break_loc_sp; + bool m_did_stop; + bool m_stop_others; + + DISALLOW_COPY_AND_ASSIGN (ThreadPlanTestCondition); + +}; + +} // namespace lldb_private + +#endif // liblldb_ThreadPlanTestCondition_h_ Modified: lldb/trunk/lldb.xcodeproj/project.pbxproj URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/lldb.xcodeproj/project.pbxproj?rev=116542&r1=116541&r2=116542&view=diff ============================================================================== --- lldb/trunk/lldb.xcodeproj/project.pbxproj (original) +++ lldb/trunk/lldb.xcodeproj/project.pbxproj Thu Oct 14 18:45:03 2010 @@ -356,6 +356,8 @@ 4C0A91DB12511CB900CA6636 /* AppleThreadPlanStepThroughObjCTrampoline.h in Headers */ = {isa = PBXBuildFile; fileRef = 4C0A91D712511CB900CA6636 /* AppleThreadPlanStepThroughObjCTrampoline.h */; }; 4C139EA5124A8B03000BFF8D /* AppleObjCRuntimeV2.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 4C139EA3124A8B03000BFF8D /* AppleObjCRuntimeV2.cpp */; }; 4C139EA6124A8B03000BFF8D /* AppleObjCRuntimeV2.h in Headers */ = {isa = PBXBuildFile; fileRef = 4C139EA4124A8B03000BFF8D /* AppleObjCRuntimeV2.h */; }; + 4C1AB23B1263E5F400D0F04A /* ThreadPlanTestCondition.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 4C1AB23A1263E5F400D0F04A /* ThreadPlanTestCondition.cpp */; }; + 4C1AB23F1263E61100D0F04A /* ThreadPlanTestCondition.h in Headers */ = {isa = PBXBuildFile; fileRef = 4C1AB23E1263E61100D0F04A /* ThreadPlanTestCondition.h */; }; 4C5DBBC811E3FEC60035160F /* CommandObjectCommands.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 4C5DBBC611E3FEC60035160F /* CommandObjectCommands.cpp */; }; 4C5DBBC911E3FEC60035160F /* CommandObjectCommands.h in Headers */ = {isa = PBXBuildFile; fileRef = 4C5DBBC711E3FEC60035160F /* CommandObjectCommands.h */; }; 4C74CB6312288704006A8171 /* Carbon.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 4C74CB6212288704006A8171 /* Carbon.framework */; }; @@ -980,6 +982,8 @@ 4C0A91D712511CB900CA6636 /* AppleThreadPlanStepThroughObjCTrampoline.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AppleThreadPlanStepThroughObjCTrampoline.h; path = LanguageRuntime/ObjC/AppleObjCRuntimeV2/AppleThreadPlanStepThroughObjCTrampoline.h; sourceTree = ""; }; 4C139EA3124A8B03000BFF8D /* AppleObjCRuntimeV2.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = AppleObjCRuntimeV2.cpp; path = LanguageRuntime/ObjC/AppleObjCRuntimeV2/AppleObjCRuntimeV2.cpp; sourceTree = ""; }; 4C139EA4124A8B03000BFF8D /* AppleObjCRuntimeV2.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AppleObjCRuntimeV2.h; path = LanguageRuntime/ObjC/AppleObjCRuntimeV2/AppleObjCRuntimeV2.h; sourceTree = ""; }; + 4C1AB23A1263E5F400D0F04A /* ThreadPlanTestCondition.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = ThreadPlanTestCondition.cpp; path = source/Target/ThreadPlanTestCondition.cpp; sourceTree = ""; }; + 4C1AB23E1263E61100D0F04A /* ThreadPlanTestCondition.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = ThreadPlanTestCondition.h; path = include/lldb/Target/ThreadPlanTestCondition.h; sourceTree = ""; }; 4C43DEF9110641F300E55CBF /* ThreadPlanShouldStopHere.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = ThreadPlanShouldStopHere.h; path = include/lldb/Target/ThreadPlanShouldStopHere.h; sourceTree = ""; }; 4C43DEFA110641F300E55CBF /* ThreadPlanShouldStopHere.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = ThreadPlanShouldStopHere.cpp; path = source/Target/ThreadPlanShouldStopHere.cpp; sourceTree = ""; }; 4C43DF8511069BFD00E55CBF /* ThreadPlanStepInRange.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = ThreadPlanStepInRange.h; path = include/lldb/Target/ThreadPlanStepInRange.h; sourceTree = ""; }; @@ -1155,7 +1159,6 @@ children = ( 26C9DF02113C5B80006B0F94 /* Include */, 26F5C32810F3DF7D009D5894 /* Libraries */, - 266960581199F4230075C61A /* Scripts */, 08FB7795FE84155DC02AAC07 /* Source */, 26F5C22410F3D950009D5894 /* Tools */, 1AB674ADFE9D54B511CA2CBB /* Products */, @@ -1166,6 +1169,7 @@ 08FB7795FE84155DC02AAC07 /* Source */ = { isa = PBXGroup; children = ( + 266960581199F4230075C61A /* Scripts */, 26BC7E7410F1B85900F91463 /* lldb.cpp */, 26BC7E7510F1B85900F91463 /* lldb-log.cpp */, 26BC7C2A10F1B3BC00F91463 /* lldb-private.h */, @@ -2064,6 +2068,8 @@ 260C847510F50EFC00BB2B04 /* ThreadPlanStepThrough.cpp */, 4CEDAED311754F5E00E875A6 /* ThreadPlanStepUntil.h */, 2660D9FE11922A7F00958FBD /* ThreadPlanStepUntil.cpp */, + 4C1AB23E1263E61100D0F04A /* ThreadPlanTestCondition.h */, + 4C1AB23A1263E5F400D0F04A /* ThreadPlanTestCondition.cpp */, 4C08CDEB11C81F1E001610A8 /* ThreadSpec.h */, 4C08CDE711C81EF8001610A8 /* ThreadSpec.cpp */, 4C00986F11500B4300F316B0 /* UnixSignals.h */, @@ -2384,6 +2390,7 @@ 4C0A91D912511CB900CA6636 /* AppleObjCTrampolineHandler.h in Headers */, 4C0A91DB12511CB900CA6636 /* AppleThreadPlanStepThroughObjCTrampoline.h in Headers */, 26424E3F125986D30016D82C /* ValueObjectConstResult.h in Headers */, + 4C1AB23F1263E61100D0F04A /* ThreadPlanTestCondition.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -2438,7 +2445,6 @@ isa = PBXProject; buildConfigurationList = 1DEB91EF08733DB70010E9CD /* Build configuration list for PBXProject "lldb" */; compatibilityVersion = "Xcode 3.1"; - developmentRegion = English; hasScannedForEncodings = 1; knownRegions = ( en, @@ -2856,6 +2862,7 @@ 4C0A91D812511CB900CA6636 /* AppleObjCTrampolineHandler.cpp in Sources */, 4C0A91DA12511CB900CA6636 /* AppleThreadPlanStepThroughObjCTrampoline.cpp in Sources */, 26424E3D125986CB0016D82C /* ValueObjectConstResult.cpp in Sources */, + 4C1AB23B1263E5F400D0F04A /* ThreadPlanTestCondition.cpp in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; Modified: lldb/trunk/source/Breakpoint/Breakpoint.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Breakpoint/Breakpoint.cpp?rev=116542&r1=116541&r2=116542&view=diff ============================================================================== --- lldb/trunk/source/Breakpoint/Breakpoint.cpp (original) +++ lldb/trunk/source/Breakpoint/Breakpoint.cpp Thu Oct 14 18:45:03 2010 @@ -185,6 +185,24 @@ return m_options.GetThreadSpec()->GetTID(); } +void +Breakpoint::SetCondition (const char *condition) +{ + m_options.SetCondition (condition); +} + +ThreadPlan * +Breakpoint::GetThreadPlanToTestCondition (ExecutionContext &exe_ctx, lldb::BreakpointLocationSP loc_sp, Stream &error) +{ + return m_options.GetThreadPlanToTestCondition (exe_ctx, loc_sp, error); +} + +const char * +Breakpoint::GetConditionText () +{ + return m_options.GetConditionText(); +} + // This function is used when "baton" doesn't need to be freed void Breakpoint::SetCallback (BreakpointHitCallback callback, void *baton, bool is_synchronous) Modified: lldb/trunk/source/Breakpoint/BreakpointLocation.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Breakpoint/BreakpointLocation.cpp?rev=116542&r1=116541&r2=116542&view=diff ============================================================================== --- lldb/trunk/source/Breakpoint/BreakpointLocation.cpp (original) +++ lldb/trunk/source/Breakpoint/BreakpointLocation.cpp Thu Oct 14 18:45:03 2010 @@ -18,6 +18,7 @@ #include "lldb/Breakpoint/StoppointCallbackContext.h" #include "lldb/Core/Log.h" #include "lldb/Target/Target.h" +#include "lldb/Target/ThreadPlan.h" #include "lldb/Target/Process.h" #include "lldb/Core/StreamString.h" #include "lldb/lldb-private-log.h" @@ -131,12 +132,35 @@ GetLocationOptions()->SetCallback (callback, baton_sp, is_synchronous); } + void BreakpointLocation::ClearCallback () { GetLocationOptions()->ClearCallback(); } +void +BreakpointLocation::SetCondition (const char *condition) +{ + GetLocationOptions()->SetCondition (condition); +} + +ThreadPlan * +BreakpointLocation::GetThreadPlanToTestCondition (ExecutionContext &exe_ctx, Stream &error) +{ + lldb::BreakpointLocationSP my_sp(m_owner.GetLocationSP(this)); + if (m_options_ap.get()) + return m_options_ap->GetThreadPlanToTestCondition (exe_ctx, my_sp, error); + else + return m_owner.GetThreadPlanToTestCondition (exe_ctx, my_sp, error); +} + +const char * +BreakpointLocation::GetConditionText () +{ + return GetLocationOptions()->GetConditionText(); +} + uint32_t BreakpointLocation::GetIgnoreCount () { @@ -185,6 +209,7 @@ BreakpointLocation::ShouldStop (StoppointCallbackContext *context) { bool should_stop = true; + Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS); m_hit_count++; @@ -194,13 +219,31 @@ if (m_hit_count <= GetIgnoreCount()) return false; - // Tell if the callback is synchronous here. + // Next in order of importance is the condition. See if it is true: + StreamString errors; + + // We only run synchronous callbacks in ShouldStop: context->is_synchronous = true; should_stop = InvokeCallback (context); - + + // The SYNCHRONOUS callback says we should stop, next try the condition. + + if (should_stop) + { + ThreadPlanSP condition_plan_sp(GetThreadPlanToTestCondition(context->exe_ctx, errors)); + if (log && errors.GetSize() > 0) + { + log->Printf("Error evaluating condition: \"%s\".\n", errors.GetData()); + } + else if (condition_plan_sp != NULL) + { + context->exe_ctx.thread->QueueThreadPlan(condition_plan_sp, false); + return false; + } + } + if (should_stop) { - Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS); if (log) { StreamString s; @@ -217,6 +260,12 @@ return m_bp_site_sp.get() != NULL; } +lldb::BreakpointSiteSP +BreakpointLocation::GetBreakpointSite() const +{ + return m_bp_site_sp; +} + bool BreakpointLocation::ResolveBreakpointSite () { Modified: lldb/trunk/source/Breakpoint/BreakpointOptions.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Breakpoint/BreakpointOptions.cpp?rev=116542&r1=116541&r2=116542&view=diff ============================================================================== --- lldb/trunk/source/Breakpoint/BreakpointOptions.cpp (original) +++ lldb/trunk/source/Breakpoint/BreakpointOptions.cpp Thu Oct 14 18:45:03 2010 @@ -15,8 +15,11 @@ // Project includes #include "lldb/Core/Stream.h" #include "lldb/Core/StringList.h" +#include "lldb/Core/Value.h" #include "lldb/Breakpoint/StoppointCallbackContext.h" +#include "lldb/Target/Process.h" #include "lldb/Target/ThreadSpec.h" +#include "lldb/Target/ThreadPlanTestCondition.h" using namespace lldb; using namespace lldb_private; @@ -36,7 +39,8 @@ m_callback_is_synchronous (false), m_enabled (true), m_ignore_count (0), - m_thread_spec_ap (NULL) + m_thread_spec_ap (NULL), + m_condition_ap() { } @@ -49,10 +53,13 @@ m_callback_is_synchronous (rhs.m_callback_is_synchronous), m_enabled (rhs.m_enabled), m_ignore_count (rhs.m_ignore_count), - m_thread_spec_ap (NULL) + m_thread_spec_ap (NULL), + m_condition_ap (NULL) { if (rhs.m_thread_spec_ap.get() != NULL) m_thread_spec_ap.reset (new ThreadSpec(*rhs.m_thread_spec_ap.get())); + if (rhs.m_condition_ap.get()) + m_condition_ap.reset (new ClangUserExpression (rhs.m_condition_ap->GetUserText())); } //---------------------------------------------------------------------- @@ -68,6 +75,8 @@ m_ignore_count = rhs.m_ignore_count; if (rhs.m_thread_spec_ap.get() != NULL) m_thread_spec_ap.reset(new ThreadSpec(*rhs.m_thread_spec_ap.get())); + if (rhs.m_condition_ap.get()) + m_condition_ap.reset (new ClangUserExpression (rhs.m_condition_ap->GetUserText())); return *this; } @@ -107,7 +116,8 @@ void BreakpointOptions::ClearCallback () { - m_callback = NULL; + m_callback = BreakpointOptions::NullCallback; + m_callback_is_synchronous = false; m_callback_baton_sp.reset(); } @@ -145,6 +155,71 @@ return m_callback != BreakpointOptions::NullCallback; } +void +BreakpointOptions::SetCondition (const char *condition) +{ + if (condition == NULL || condition[0] == '\0') + { + if (m_condition_ap.get()) + m_condition_ap.reset(); + } + else + { + m_condition_ap.reset(new ClangUserExpression (condition)); + } +} + +ThreadPlan * +BreakpointOptions::GetThreadPlanToTestCondition (ExecutionContext &exe_ctx, + lldb::BreakpointLocationSP break_loc_sp, + Stream &error_stream) +{ + // No condition means we should stop, so return NULL. + if (!m_condition_ap.get()) + return NULL; + + // FIXME: I shouldn't have to do this, the process should handle it for me: + if (!exe_ctx.process->GetDynamicCheckers()) + { + DynamicCheckerFunctions *dynamic_checkers = new DynamicCheckerFunctions(); + + StreamString install_errors; + + if (!dynamic_checkers->Install(install_errors, exe_ctx)) + { + error_stream.Printf("Couldn't install dynamic checkers into the execution context: %s\n", install_errors.GetData()); + return NULL; + } + + exe_ctx.process->SetDynamicCheckers(dynamic_checkers); + } + + if (!m_condition_ap->Parse (error_stream, exe_ctx)) + { + // Errors mean we should stop. + return NULL; + } + // FIXME: When we can execute static expressions without running the target, we should check that here, + // and return something to indicate we should stop or just continue. + + ThreadPlan *new_plan = new ThreadPlanTestCondition (*exe_ctx.thread, + exe_ctx, + m_condition_ap.get(), + break_loc_sp, + true); + + return new_plan; +} + +const char * +BreakpointOptions::GetConditionText () +{ + if (m_condition_ap.get()) + return m_condition_ap->GetUserText(); + else + return ""; +} + //------------------------------------------------------------------ // Enabled/Ignore Count //------------------------------------------------------------------ @@ -234,6 +309,14 @@ if (level != eDescriptionLevelBrief) s->EOL(); m_callback_baton_sp->GetDescription (s, level); + } + if (m_condition_ap.get()) + { + if (level != eDescriptionLevelBrief) + { + s->EOL(); + s->Printf("Condition: %s\n", m_condition_ap->GetUserText()); + } } } Modified: lldb/trunk/source/Commands/CommandObjectBreakpoint.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Commands/CommandObjectBreakpoint.cpp?rev=116542&r1=116541&r2=116542&view=diff ============================================================================== --- lldb/trunk/source/Commands/CommandObjectBreakpoint.cpp (original) +++ lldb/trunk/source/Commands/CommandObjectBreakpoint.cpp Thu Oct 14 18:45:03 2010 @@ -547,9 +547,25 @@ // 2). the full breakpoint & location canonical representation // 3). the word "to" or a hyphen, representing a range (in which case there // had *better* be an entry both before & after of one of the first two types. + // If args is empty, we will use the last created breakpoint (if there is one.) Args temp_args; + if (args.GetArgumentCount() == 0) + { + if (target->GetLastCreatedBreakpoint() != NULL) + { + valid_ids->AddBreakpointID (BreakpointID(target->GetLastCreatedBreakpoint()->GetID(), LLDB_INVALID_BREAK_ID)); + result.SetStatus (eReturnStatusSuccessFinishNoResult); + } + else + { + result.AppendError("No breakpoint specified and no last created breakpoint."); + result.SetStatus (eReturnStatusFailed); + } + return; + } + // Create a new Args variable to use; copy any non-breakpoint-id-ranges stuff directly from the old ARGS to // the new TEMP_ARGS. Do not copy breakpoint id range strings over; instead generate a list of strings for // all the breakpoint ids in the range, and shove all of those breakpoint id strings into TEMP_ARGS. @@ -1076,16 +1092,15 @@ if (args.GetArgumentCount() == 0) { - // No breakpoint selected; disable all currently set breakpoints. - if (args.GetArgumentCount() != 0) + if (!m_interpreter.Confirm ("About to delete all breakpoints, do you want to do that?", true)) { - result.AppendErrorWithFormat ("Specify breakpoints to delete with the -i option.\n"); - result.SetStatus (eReturnStatusFailed); - return false; + result.AppendMessage("Operation cancelled..."); + } + else + { + target->RemoveAllBreakpoints (); + result.AppendMessageWithFormat ("All breakpoints removed. (%d breakpoints)\n", num_breakpoints); } - - target->RemoveAllBreakpoints (); - result.AppendMessageWithFormat ("All breakpoints removed. (%d breakpoints)\n", num_breakpoints); result.SetStatus (eReturnStatusSuccessFinishNoResult); } else @@ -1143,10 +1158,12 @@ m_thread_index (UINT32_MAX), m_thread_name(), m_queue_name(), + m_condition (), m_enable_passed (false), m_enable_value (false), m_name_passed (false), - m_queue_passed (false) + m_queue_passed (false), + m_condition_passed (false) { } @@ -1162,9 +1179,10 @@ { LLDB_OPT_SET_ALL, false, "thread-id", 't', required_argument, NULL, NULL, eArgTypeThreadID, "The breakpoint stops only for the thread whose TID matches this argument."}, { LLDB_OPT_SET_ALL, false, "thread-name", 'T', required_argument, NULL, NULL, eArgTypeThreadName, "The breakpoint stops only for the thread whose thread name matches this argument."}, { LLDB_OPT_SET_ALL, false, "queue-name", 'q', required_argument, NULL, NULL, eArgTypeQueueName, "The breakpoint stops only for threads in the queue whose name is given by this argument."}, +{ LLDB_OPT_SET_ALL, false, "condition", 'c', required_argument, NULL, NULL, eArgTypeExpression, "The breakpoint stops only if this condition expression evaluates to true."}, { LLDB_OPT_SET_1, false, "enable", 'e', no_argument, NULL, NULL, eArgTypeNone, "Enable the breakpoint."}, { LLDB_OPT_SET_2, false, "disable", 'd', no_argument, NULL, NULL, eArgTypeNone, "Disable the breakpoint."}, -{ 0, false, NULL, 0 , 0, NULL, 0, eArgTypeNone, NULL } +{ 0, false, NULL, 0 , 0, NULL, 0, eArgTypeNone, NULL } }; const lldb::OptionDefinition* @@ -1181,6 +1199,13 @@ switch (short_option) { + case 'c': + if (option_arg != NULL) + m_condition = option_arg; + else + m_condition.clear(); + m_condition_passed = true; + break; case 'd': m_enable_passed = true; m_enable_value = false; @@ -1243,9 +1268,11 @@ m_thread_index = UINT32_MAX; m_thread_name.clear(); m_queue_name.clear(); + m_condition.clear(); m_enable_passed = false; m_queue_passed = false; m_name_passed = false; + m_condition_passed = false; } //------------------------------------------------------------------------- @@ -1297,13 +1324,6 @@ CommandReturnObject &result ) { - if (command.GetArgumentCount() == 0) - { - result.AppendError ("No breakpoints specified."); - result.SetStatus (eReturnStatusFailed); - return false; - } - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); if (target == NULL) { @@ -1351,6 +1371,9 @@ if (m_options.m_enable_passed) location->SetEnabled (m_options.m_enable_value); + + if (m_options.m_condition_passed) + location->SetCondition (m_options.m_condition.c_str()); } } else @@ -1372,7 +1395,9 @@ if (m_options.m_enable_passed) bp->SetEnabled (m_options.m_enable_value); - + + if (m_options.m_condition_passed) + bp->SetCondition (m_options.m_condition.c_str()); } } } Modified: lldb/trunk/source/Commands/CommandObjectBreakpoint.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Commands/CommandObjectBreakpoint.h?rev=116542&r1=116541&r2=116542&view=diff ============================================================================== --- lldb/trunk/source/Commands/CommandObjectBreakpoint.h (original) +++ lldb/trunk/source/Commands/CommandObjectBreakpoint.h Thu Oct 14 18:45:03 2010 @@ -167,10 +167,12 @@ uint32_t m_thread_index; std::string m_thread_name; std::string m_queue_name; + std::string m_condition; bool m_enable_passed; bool m_enable_value; bool m_name_passed; bool m_queue_passed; + bool m_condition_passed; }; Modified: lldb/trunk/source/Core/Event.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Core/Event.cpp?rev=116542&r1=116541&r2=116542&view=diff ============================================================================== --- lldb/trunk/source/Core/Event.cpp (original) +++ lldb/trunk/source/Core/Event.cpp Thu Oct 14 18:45:03 2010 @@ -49,12 +49,6 @@ } void -Event::Clear() -{ - m_data_ap.reset(); -} - -void Event::Dump (Stream *s) const { s->Printf("%p Event: broadcaster = %p, type = 0x%8.8x, data = ", this, m_broadcaster, m_type); @@ -69,37 +63,6 @@ } } -Broadcaster * -Event::GetBroadcaster () const -{ - return m_broadcaster; -} - -bool -Event::BroadcasterIs (Broadcaster *broadcaster) -{ - return broadcaster == m_broadcaster; -} - -uint32_t -Event::GetType() const -{ - return m_type; -} - - -EventData * -Event::GetData () -{ - return m_data_ap.get(); -} - -const EventData * -Event::GetData () const -{ - return m_data_ap.get(); -} - void Event::DoOnRemoval () { @@ -107,12 +70,6 @@ m_data_ap->DoOnRemoval (this); } -void -Event::SetBroadcaster (Broadcaster *broadcaster) -{ - m_broadcaster = broadcaster; -} - EventData::EventData() { } Modified: lldb/trunk/source/Expression/ClangExpressionParser.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Expression/ClangExpressionParser.cpp?rev=116542&r1=116541&r2=116542&view=diff ============================================================================== --- lldb/trunk/source/Expression/ClangExpressionParser.cpp (original) +++ lldb/trunk/source/Expression/ClangExpressionParser.cpp Thu Oct 14 18:45:03 2010 @@ -447,7 +447,7 @@ return err; } - if (m_expr.NeedsValidation()) + if (m_expr.NeedsValidation() && exe_ctx.process->GetDynamicCheckers()) { /* Disabled temporarily - TODO Centralize and re-enable this inside Process to avoid race conditions Modified: lldb/trunk/source/Expression/ClangFunction.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Expression/ClangFunction.cpp?rev=116542&r1=116541&r2=116542&view=diff ============================================================================== --- lldb/trunk/source/Expression/ClangFunction.cpp (original) +++ lldb/trunk/source/Expression/ClangFunction.cpp Thu Oct 14 18:45:03 2010 @@ -539,9 +539,11 @@ // Not really sure what to do if Halt fails here... if (log) if (try_all_threads) - log->Printf ("Running function with timeout: %d timed out, trying with all threads enabled.", single_thread_timeout_usec); + log->Printf ("Running function with timeout: %d timed out, trying with all threads enabled.", + single_thread_timeout_usec); else - log->Printf ("Running function with timeout: %d timed out, abandoning execution.", single_thread_timeout_usec); + log->Printf ("Running function with timeout: %d timed out, abandoning execution.", + single_thread_timeout_usec); if (exe_ctx.process->Halt().Success()) { Modified: lldb/trunk/source/Expression/ClangUserExpression.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Expression/ClangUserExpression.cpp?rev=116542&r1=116541&r2=116542&view=diff ============================================================================== --- lldb/trunk/source/Expression/ClangUserExpression.cpp (original) +++ lldb/trunk/source/Expression/ClangUserExpression.cpp Thu Oct 14 18:45:03 2010 @@ -215,27 +215,18 @@ } bool -ClangUserExpression::Execute (Stream &error_stream, - ExecutionContext &exe_ctx, - ClangExpressionVariable *&result) +ClangUserExpression::PrepareToExecuteJITExpression (Stream &error_stream, + ExecutionContext &exe_ctx, + lldb::addr_t &struct_address, + lldb::addr_t object_ptr) { Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS); - if (m_dwarf_opcodes.get()) + if (m_jit_addr != LLDB_INVALID_ADDRESS) { - // TODO execute the JITted opcodes - - error_stream.Printf("We don't currently support executing DWARF expressions"); - - return false; - } - else if (m_jit_addr != LLDB_INVALID_ADDRESS) - { - lldb::addr_t struct_address; Error materialize_error; - lldb::addr_t object_ptr = NULL; if (m_needs_object_ptr && !(m_expr_decl_map->GetObjectPointer(object_ptr, &exe_ctx, materialize_error))) { @@ -274,6 +265,64 @@ } } } + } + return true; +} + +ThreadPlan * +ClangUserExpression::GetThreadPlanToExecuteJITExpression (Stream &error_stream, + ExecutionContext &exe_ctx) +{ + lldb::addr_t struct_address; + + lldb::addr_t object_ptr = NULL; + + PrepareToExecuteJITExpression (error_stream, exe_ctx, struct_address, object_ptr); + + return ClangFunction::GetThreadPlanToCallFunction (exe_ctx, + m_jit_addr, + struct_address, + error_stream, + true, + true, + (m_needs_object_ptr ? &object_ptr : NULL)); +} + +bool +ClangUserExpression::FinalizeJITExecution (Stream &error_stream, + ExecutionContext &exe_ctx, + ClangExpressionVariable *&result) +{ + Error expr_error; + + if (!m_expr_decl_map->Dematerialize(&exe_ctx, result, expr_error)) + { + error_stream.Printf ("Couldn't dematerialize struct : %s\n", expr_error.AsCString("unknown error")); + return false; + } + return true; +} + +bool +ClangUserExpression::Execute (Stream &error_stream, + ExecutionContext &exe_ctx, + ClangExpressionVariable *&result) +{ + if (m_dwarf_opcodes.get()) + { + // TODO execute the JITted opcodes + + error_stream.Printf("We don't currently support executing DWARF expressions"); + + return false; + } + else if (m_jit_addr != LLDB_INVALID_ADDRESS) + { + lldb::addr_t struct_address; + + lldb::addr_t object_ptr = NULL; + + PrepareToExecuteJITExpression (error_stream, exe_ctx, struct_address, object_ptr); ClangFunction::ExecutionResults execution_result = ClangFunction::ExecuteFunction (exe_ctx, @@ -312,15 +361,7 @@ return false; } - Error expr_error; - - if (!m_expr_decl_map->Dematerialize(&exe_ctx, result, expr_error)) - { - error_stream.Printf ("Couldn't dematerialize struct : %s\n", expr_error.AsCString("unknown error")); - return false; - } - - return true; + return FinalizeJITExecution (error_stream, exe_ctx, result); } else { Modified: lldb/trunk/source/Target/Process.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Target/Process.cpp?rev=116542&r1=116541&r2=116542&view=diff ============================================================================== --- lldb/trunk/source/Target/Process.cpp (original) +++ lldb/trunk/source/Target/Process.cpp Thu Oct 14 18:45:03 2010 @@ -82,9 +82,9 @@ m_exit_string (), m_thread_list (this), m_notifications (), + m_persistent_vars(), m_listener(listener), - m_unix_signals (), - m_persistent_vars() + m_unix_signals () { UpdateInstanceName(); Modified: lldb/trunk/source/Target/StopInfo.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Target/StopInfo.cpp?rev=116542&r1=116541&r2=116542&view=diff ============================================================================== --- lldb/trunk/source/Target/StopInfo.cpp (original) +++ lldb/trunk/source/Target/StopInfo.cpp Thu Oct 14 18:45:03 2010 @@ -56,6 +56,14 @@ { } + StopInfoBreakpoint (Thread &thread, break_id_t break_id, bool should_stop) : + StopInfo (thread, break_id), + m_description(), + m_should_stop (should_stop), + m_should_stop_is_valid (true) + { + } + virtual ~StopInfoBreakpoint () { } @@ -367,6 +375,12 @@ } StopInfoSP +StopInfo::CreateStopReasonWithBreakpointSiteID (Thread &thread, break_id_t break_id, bool should_stop) +{ + return StopInfoSP (new StopInfoBreakpoint (thread, break_id, should_stop)); +} + +StopInfoSP StopInfo::CreateStopReasonWithWatchpointID (Thread &thread, break_id_t watch_id) { return StopInfoSP (new StopInfoWatchpoint (thread, watch_id)); Modified: lldb/trunk/source/Target/Target.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Target/Target.cpp?rev=116542&r1=116541&r2=116542&view=diff ============================================================================== --- lldb/trunk/source/Target/Target.cpp (original) +++ lldb/trunk/source/Target/Target.cpp Thu Oct 14 18:45:03 2010 @@ -252,6 +252,12 @@ bp_sp->ResolveBreakpoint(); } + + if (!internal && bp_sp) + { + m_last_created_breakpoint = bp_sp; + } + return bp_sp; } @@ -265,6 +271,8 @@ m_breakpoint_list.RemoveAll (true); if (internal_also) m_internal_breakpoint_list.RemoveAll (false); + + m_last_created_breakpoint.reset(); } void @@ -303,7 +311,11 @@ if (LLDB_BREAK_ID_IS_INTERNAL (break_id)) m_internal_breakpoint_list.Remove(break_id, false); else + { + if (m_last_created_breakpoint->GetID() == break_id) + m_last_created_breakpoint.reset(); m_breakpoint_list.Remove(break_id, true); + } return true; } return false; Added: lldb/trunk/source/Target/ThreadPlanTestCondition.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Target/ThreadPlanTestCondition.cpp?rev=116542&view=auto ============================================================================== --- lldb/trunk/source/Target/ThreadPlanTestCondition.cpp (added) +++ lldb/trunk/source/Target/ThreadPlanTestCondition.cpp Thu Oct 14 18:45:03 2010 @@ -0,0 +1,182 @@ +//===-- ThreadPlanTestCondition.cpp ---------------------------------*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#include "lldb/Target/ThreadPlanTestCondition.h" + +// C Includes +// C++ Includes +// Other libraries and framework includes +// Project includes + +#include "lldb/lldb-private-log.h" +#include "lldb/Breakpoint/BreakpointLocation.h" +#include "lldb/Core/Log.h" +#include "lldb/Core/Stream.h" +#include "lldb/Core/Value.h" +#include "lldb/Core/ValueObject.h" +#include "lldb/Symbol/Function.h" +#include "lldb/Symbol/Symbol.h" +#include "lldb/Target/Process.h" +#include "lldb/Target/RegisterContext.h" +#include "lldb/Target/StopInfo.h" +#include "lldb/Target/Thread.h" + +using namespace lldb; +using namespace lldb_private; + + +//---------------------------------------------------------------------- +// ThreadPlanTestCondition: Step through a stack range, either stepping over or into +// based on the value of \a type. +//---------------------------------------------------------------------- + +ThreadPlanTestCondition::ThreadPlanTestCondition ( + Thread& thread, + ExecutionContext &exe_ctx, + ClangUserExpression *expression, + lldb::BreakpointLocationSP break_loc_sp, + bool stop_others) : + ThreadPlan (ThreadPlan::eKindTestCondition, "test condition", thread, eVoteNoOpinion, eVoteNoOpinion), + m_exe_ctx (exe_ctx), + m_expression (expression), + m_break_loc_sp (break_loc_sp), + m_did_stop (false), + m_stop_others (stop_others) +{ +} + +ThreadPlanTestCondition::~ThreadPlanTestCondition () +{ +} + +bool +ThreadPlanTestCondition::ValidatePlan (Stream *error) +{ + return true; +} + +void +ThreadPlanTestCondition::GetDescription (Stream *s, lldb::DescriptionLevel level) +{ + +} + +bool +ThreadPlanTestCondition::ShouldStop (Event *event_ptr) +{ + Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP); + if (m_thread.IsThreadPlanDone(m_expression_plan_sp.get())) + { + ClangExpressionVariable *expr_result = NULL; + StreamString error_stream; + m_expression->FinalizeJITExecution(error_stream, m_exe_ctx, expr_result); + + ValueObjectSP result_sp (expr_result->GetExpressionResult(&m_exe_ctx)); + if (result_sp) + { + // FIXME: This is not the right answer, we should have a "GetValueAsBoolean..." + Scalar scalar_value = result_sp->GetValue().ResolveValue (&m_exe_ctx, result_sp->GetClangAST()); + if (scalar_value.IsValid()) + { + if (scalar_value.ULongLong(1) == 0) + m_did_stop = false; + else + m_did_stop = true; + } + if (log) + log->Printf("Condition successfully evaluated, result is %s.\n", m_did_stop ? "true" : "false"); + } + else + { + if (log) + log->Printf("Failed to get a result from the expression, error: \"%s\"\n", error_stream.GetData()); + m_did_stop = true; + } + } + else if (m_exe_ctx.thread->WasThreadPlanDiscarded (m_expression_plan_sp.get())) + { + if (log) + log->Printf("ExecuteExpression thread plan was discarded.\n"); + m_did_stop = true; + } + + // Now we have to change the event to a breakpoint event and mark it up appropriately: + Process::ProcessEventData *new_data = new Process::ProcessEventData (m_thread.GetProcess().GetSP(), eStateStopped); + event_ptr->SetData(new_data); + event_ptr->SetType(Process::eBroadcastBitStateChanged); + m_thread.SetStopInfo(StopInfo::CreateStopReasonWithBreakpointSiteID (m_thread, + m_break_loc_sp->GetBreakpointSite()->GetID(), + m_did_stop)); + if (m_did_stop) + { + Process::ProcessEventData::SetRestartedInEvent (event_ptr, false); + } + else + { + Process::ProcessEventData::SetRestartedInEvent (event_ptr, true); + } + + SetPlanComplete(); + return m_did_stop; +} + +bool +ThreadPlanTestCondition::PlanExplainsStop () +{ + // We explain all stops, and we just can the execution and return true if we stop for any + // reason other than that our expression execution is done. + return true; +} + +Vote +ThreadPlanTestCondition::ShouldReportStop (Event *event_ptr) +{ + if (m_did_stop) + { + return eVoteYes; + } + else + { + return eVoteNo; + } +} + +void +ThreadPlanTestCondition::DidPush() +{ + StreamString error_stream; + m_expression_plan_sp.reset(m_expression->GetThreadPlanToExecuteJITExpression (error_stream, m_exe_ctx)); + m_thread.QueueThreadPlan (m_expression_plan_sp, false); +} + +bool +ThreadPlanTestCondition::StopOthers () +{ + return m_stop_others; +} + +bool +ThreadPlanTestCondition::WillStop () +{ + return true; +} + +StateType +ThreadPlanTestCondition::RunState () +{ + return eStateRunning; +} + +bool +ThreadPlanTestCondition::MischiefManaged () +{ + // If we get a stop we're done, we don't puase in the middle of + // condition execution. + return true; +} From johnny.chen at apple.com Thu Oct 14 20:18:30 2010 From: johnny.chen at apple.com (Johnny Chen) Date: Fri, 15 Oct 2010 01:18:30 -0000 Subject: [Lldb-commits] [lldb] r116552 - in /lldb/trunk/test: dotest.py foundation/TestObjCMethods.py lldbtest.py lldbutil.py Message-ID: <20101015011830.1AF6E2A6C12C@llvm.org> Author: johnny Date: Thu Oct 14 20:18:29 2010 New Revision: 116552 URL: http://llvm.org/viewvc/llvm-project?rev=116552&view=rev Log: This is an initial version of test driver enhanceent to be able to dump the session info after a test case failure, allowing more direct inspection of debugger session which leads to the test failure. For a simple usage scenario: [18:06:26] johnny:/Volumes/data/lldb/svn/trunk/test $ ./dotest.py -v . 2> ~/Developer/Log/lldbtest.log ... [18:14:43] johnny:/Volumes/data/lldb/svn/trunk/test $ ls -l .session-* -rw-r--r-- 1 johnny admin 1359 Oct 14 18:06 .session-TestArrayTypes.ArrayTypesTestCase.test_with_dwarf_and_run_command -rw-r--r-- 1 johnny admin 2054 Oct 14 18:07 .session-TestClassTypes.ClassTypesTestCase.test_with_dsym_and_expr_parser -rw-r--r-- 1 johnny admin 2055 Oct 14 18:07 .session-TestClassTypes.ClassTypesTestCase.test_with_dwarf_and_expr_parser -rw-r--r-- 1 johnny admin 1351 Oct 14 17:57 .session-TestClassTypes.ClassTypesTestCase.test_with_dwarf_and_run_command [18:14:51] johnny:/Volumes/data/lldb/svn/trunk/test $ The test case which failed will have its recorded session info dumped to a .session-* file in the current working directory. For test suite using relocated directory, expect to find the .session-* files there. In this checkin, I also add @skip decorator to the two test methods in test/foundation/TestObjCMethods.py as it looks like the test suite is deadlocking when running the tests. More investigations are needed. Modified: lldb/trunk/test/dotest.py lldb/trunk/test/foundation/TestObjCMethods.py lldb/trunk/test/lldbtest.py lldb/trunk/test/lldbutil.py Modified: lldb/trunk/test/dotest.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/dotest.py?rev=116552&r1=116551&r2=116552&view=diff ============================================================================== --- lldb/trunk/test/dotest.py (original) +++ lldb/trunk/test/dotest.py Thu Oct 14 20:18:29 2010 @@ -597,7 +597,29 @@ suite.countTestCases() != 1 and "s" or "")) # Invoke the test runner. - result = unittest2.TextTestRunner(stream=sys.stderr, verbosity=verbose).run(suite) + class LLDBTestResult(unittest2.TextTestResult): + """ + Enforce a singleton pattern to allow inspection of test progress. + """ + __singleton__ = None + + def __init__(self, *args): + if LLDBTestResult.__singleton__: + raise "LLDBTestResult instantiated more than once" + super(LLDBTestResult, self).__init__(*args) + LLDBTestResult.__singleton__ = self + # Now put this singleton into the lldb module namespace. + lldb.test_result = self + + def addFailure(self, test, err): + super(LLDBTestResult, self).addFailure(test, err) + method = getattr(test, "markFailure", None) + if method: + method() + setattr(test, "__failed__", True) + + result = unittest2.TextTestRunner(stream=sys.stderr, verbosity=verbose, + resultclass=LLDBTestResult).run(suite) # Terminate the test suite if ${LLDB_TESTSUITE_FORCE_FINISH} is defined. Modified: lldb/trunk/test/foundation/TestObjCMethods.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/foundation/TestObjCMethods.py?rev=116552&r1=116551&r2=116552&view=diff ============================================================================== --- lldb/trunk/test/foundation/TestObjCMethods.py (original) +++ lldb/trunk/test/foundation/TestObjCMethods.py Thu Oct 14 20:18:29 2010 @@ -23,6 +23,7 @@ self.buildDwarf() self.break_on_objc_methods() + @unittest2.skip("Skip due to deadlock?") @unittest2.expectedFailure # rdar://problem/8542091 # rdar://problem/8492646 @@ -31,6 +32,7 @@ self.buildDsym() self.data_type_and_expr_objc() + @unittest2.skip("Skip due to deadlock?") @unittest2.expectedFailure # rdar://problem/8542091 # rdar://problem/8492646 Modified: lldb/trunk/test/lldbtest.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/lldbtest.py?rev=116552&r1=116551&r2=116552&view=diff ============================================================================== --- lldb/trunk/test/lldbtest.py (original) +++ lldb/trunk/test/lldbtest.py Thu Oct 14 20:18:29 2010 @@ -99,6 +99,7 @@ import os, sys, traceback import re from subprocess import * +import StringIO import time import types import unittest2 @@ -244,6 +245,37 @@ return 8 * ctypes.sizeof(a_pointer) +class recording(StringIO.StringIO): + """ + A nice little context manager for recording the debugger interactions into + our session object. If trace flag is ON, it also emits the interactions + into the stderr. + """ + def __init__(self, test, trace): + """Create a StringIO instance; record session, stderr, and trace.""" + StringIO.StringIO.__init__(self) + self.session = test.session + self.stderr = test.old_stderr + self.trace = trace + + def __enter__(self): + """ + Context management protocol on entry to the body of the with statement. + Just return the StringIO object. + """ + return self + + def __exit__(self, type, value, tb): + """ + Context management protocol on exit from the body of the with statement. + If trace is ON, it emits the recordings into stderr. Always add the + recordings to our session object. And close the StringIO object, too. + """ + if self.trace: + print >> self.stderr, self.getvalue() + print >> self.session, self.getvalue() + self.close() + class TestBase(unittest2.TestCase): """This LLDB abstract base class is meant to be subclassed.""" @@ -369,10 +401,39 @@ self.dict = None self.doTearDownCleanup = False + # Create a string buffer to record the session info. + self.session = StringIO.StringIO() + + # Substitute self.session as the sys.stderr and restore it at the end of + # the test during tearDown(). If trace is ON, we dump the session info + # into the real stderr as well. The session info will be dumped into a + # test case specific file if a failure is encountered. + self.old_stderr = sys.stderr + sys.stderr = self.session + def setTearDownCleanup(self, dictionary=None): self.dict = dictionary self.doTearDownCleanup = True + def markFailure(self): + """Callback invoked when we (the test case instance) failed.""" + with recording(self, False) as sbuf: + # False because there's no need to write "FAIL" to the stderr again. + print >> sbuf, "FAIL" + + def dumpSessionInfo(self): + """ + Dump the debugger interactions leading to a test failure. This allows + for more convenient postmortem analysis. + """ + for test, err in lldb.test_result.failures: + if test is self: + print >> self.session, err + + fname = os.path.join(os.environ["LLDB_TEST"], ".session-" + self.id()) + with open(fname, "w") as f: + print >> f, self.session.getvalue() + def tearDown(self): #import traceback #traceback.print_stack() @@ -393,6 +454,15 @@ if not module.cleanup(dictionary=self.dict): raise Exception("Don't know how to do cleanup") + # lldb.test_result is an instance of unittest2.TextTestResult enforced + # as a singleton. During tearDown(), lldb.test_result can be consulted + # in order to determine whether we failed for the current test instance. + if getattr(self, "__failed__", False): + self.dumpSessionInfo() + + # Restore the sys.stderr to what it was before. + sys.stderr = self.old_stderr + def runCmd(self, cmd, msg=None, check=True, trace=False, setCookie=True): """ Ask the command interpreter to handle the command and then check its @@ -409,13 +479,13 @@ for i in range(self.maxLaunchCount if running else 1): self.ci.HandleCommand(cmd, self.res) - if trace: - print >> sys.stderr, "runCmd:", cmd + with recording(self, trace) as sbuf: + print >> sbuf, "runCmd:", cmd if self.res.Succeeded(): - print >> sys.stderr, "output:", self.res.GetOutput() + print >> sbuf, "output:", self.res.GetOutput() else: - print >> sys.stderr, "runCmd failed!" - print >> sys.stderr, self.res.GetError() + print >> sbuf, "runCmd failed!" + print >> sbuf, self.res.GetError() if running: # For process launch, wait some time before possible next try. @@ -423,8 +493,9 @@ if self.res.Succeeded(): break - elif running: - print >> sys.stderr, "Command '" + cmd + "' failed!" + elif running: + with recording(self, True) as sbuf: + print >> sbuf, "Command '" + cmd + "' failed!" # Modify runStarted only if "run" or "process launch" was encountered. if running: @@ -474,35 +545,35 @@ else: # No execution required, just compare str against the golden input. output = str - if trace: - print >> sys.stderr, "looking at:", output + with recording(self, trace) as sbuf: + print >> sbuf, "looking at:", output # The heading says either "Expecting" or "Not expecting". - if trace: - heading = "Expecting" if matching else "Not expecting" + heading = "Expecting" if matching else "Not expecting" # Start from the startstr, if specified. # If there's no startstr, set the initial state appropriately. matched = output.startswith(startstr) if startstr else (True if matching else False) - if startstr and trace: - print >> sys.stderr, "%s start string: %s" % (heading, startstr) - print >> sys.stderr, "Matched" if matched else "Not matched" - print >> sys.stderr + if startstr: + with recording(self, trace) as sbuf: + print >> sbuf, "%s start string: %s" % (heading, startstr) + print >> sbuf, "Matched" if matched else "Not matched" + print >> sbuf # Look for sub strings, if specified. keepgoing = matched if matching else not matched if substrs and keepgoing: for str in substrs: matched = output.find(str) != -1 - if trace: - print >> sys.stderr, "%s sub string: %s" % (heading, str) - print >> sys.stderr, "Matched" if matched else "Not matched" + with recording(self, trace) as sbuf: + print >> sbuf, "%s sub string: %s" % (heading, str) + print >> sbuf, "Matched" if matched else "Not matched" keepgoing = matched if matching else not matched if not keepgoing: break - if trace: - print >> sys.stderr + with recording(self, trace) as sbuf: + print >> sbuf # Search for regular expression patterns, if specified. keepgoing = matched if matching else not matched @@ -510,14 +581,14 @@ for pattern in patterns: # Match Objects always have a boolean value of True. matched = bool(re.search(pattern, output)) - if trace: - print >> sys.stderr, "%s pattern: %s" % (heading, pattern) - print >> sys.stderr, "Matched" if matched else "Not matched" + with recording(self, trace) as sbuf: + print >> sbuf, "%s pattern: %s" % (heading, pattern) + print >> sbuf, "Matched" if matched else "Not matched" keepgoing = matched if matching else not matched if not keepgoing: break - if trace: - print >> sys.stderr + with recording(self, trace) as sbuf: + print >> sbuf self.assertTrue(matched if matching else not matched, msg if msg else CMD_MSG(str, exe)) @@ -531,8 +602,8 @@ self.assertTrue(inspect.ismethod(method), name + "is a method name of object: " + str(obj)) result = method() - if trace: - print >> sys.stderr, str(method) + ":", result + with recording(self, trace) as sbuf: + print >> sbuf, str(method) + ":", result return result def breakAfterLaunch(self, process, func, trace=False): @@ -548,28 +619,28 @@ # The stop reason of the thread should be breakpoint. thread = process.GetThreadAtIndex(0) SR = thread.GetStopReason() - if trace: - print >> sys.stderr, "StopReason =", StopReasonString(SR) + with recording(self, trace) as sbuf: + print >> sbuf, "StopReason =", StopReasonString(SR) if SR == StopReasonEnum("Breakpoint"): frame = thread.GetFrameAtIndex(0) name = frame.GetFunction().GetName() - if trace: - print >> sys.stderr, "function =", name + with recording(self, trace) as sbuf: + print >> sbuf, "function =", name if (name == func): # We got what we want; now break out of the loop. return True # The inferior is in a transient state; continue the process. time.sleep(1.0) - if trace: - print >> sys.stderr, "Continuing the process:", process + with recording(self, trace) as sbuf: + print >> sbuf, "Continuing the process:", process process.Continue() count = count + 1 if count == 15: - if trace: - print >> sys.stderr, "Reached 15 iterations, giving up..." + with recording(self, trace) as sbuf: + print >> sbuf, "Reached 15 iterations, giving up..." # Enough iterations already, break out of the loop. return False Modified: lldb/trunk/test/lldbutil.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/lldbutil.py?rev=116552&r1=116551&r2=116552&view=diff ============================================================================== --- lldb/trunk/test/lldbutil.py (original) +++ lldb/trunk/test/lldbutil.py Thu Oct 14 20:18:29 2010 @@ -6,6 +6,12 @@ import sys import StringIO +################################################ +# # +# Iterator for lldb aggregate data structures. # +# # +################################################ + def lldb_iter(obj, getsize, getelem): """ A generator adaptor for lldb aggregate data structures. From gclayton at apple.com Thu Oct 14 21:03:22 2010 From: gclayton at apple.com (Greg Clayton) Date: Fri, 15 Oct 2010 02:03:22 -0000 Subject: [Lldb-commits] [lldb] r116558 - in /lldb/trunk/source/Plugins/SymbolFile/DWARF: DWARFCompileUnit.cpp DWARFCompileUnit.h SymbolFileDWARF.cpp SymbolFileDWARF.h Message-ID: <20101015020323.0E5D12A6C12C@llvm.org> Author: gclayton Date: Thu Oct 14 21:03:22 2010 New Revision: 116558 URL: http://llvm.org/viewvc/llvm-project?rev=116558&view=rev Log: Separated the DWARF index for types from that the index of the namespaces since we can't parse DW_TAG_namespace DIEs as types. They are only decls in clang. All of the types we handle right now have both clang "XXXType" classes to go with the "XXXDecl" classes which means they can be used within the lldb_private::Type class. I need to check to see which other decls that don't have associated type objects need to float around the debugger and possibly make a lldb_private::Decl class to manage them. Modified: lldb/trunk/source/Plugins/SymbolFile/DWARF/DWARFCompileUnit.cpp lldb/trunk/source/Plugins/SymbolFile/DWARF/DWARFCompileUnit.h lldb/trunk/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp lldb/trunk/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.h Modified: lldb/trunk/source/Plugins/SymbolFile/DWARF/DWARFCompileUnit.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Plugins/SymbolFile/DWARF/DWARFCompileUnit.cpp?rev=116558&r1=116557&r2=116558&view=diff ============================================================================== --- lldb/trunk/source/Plugins/SymbolFile/DWARF/DWARFCompileUnit.cpp (original) +++ lldb/trunk/source/Plugins/SymbolFile/DWARF/DWARFCompileUnit.cpp Thu Oct 14 21:03:22 2010 @@ -571,6 +571,7 @@ NameToDIE& objc_class_selector_dies, NameToDIE& name_to_global_die, NameToDIE& name_to_type_die, + NameToDIE& name_to_namespace_die, const DWARFDebugRanges *debug_ranges, DWARFDebugAranges *aranges ) @@ -874,13 +875,17 @@ case DW_TAG_structure_type: case DW_TAG_union_type: case DW_TAG_typedef: - case DW_TAG_namespace: if (name && is_declaration == false) { name_to_type_die.Insert (ConstString(name), die_info); } break; + case DW_TAG_namespace: + if (name) + name_to_namespace_die.Insert (ConstString(name), die_info); + break; + case DW_TAG_variable: if (name && has_location && is_global_or_static_variable) { Modified: lldb/trunk/source/Plugins/SymbolFile/DWARF/DWARFCompileUnit.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Plugins/SymbolFile/DWARF/DWARFCompileUnit.h?rev=116558&r1=116557&r2=116558&view=diff ============================================================================== --- lldb/trunk/source/Plugins/SymbolFile/DWARF/DWARFCompileUnit.h (original) +++ lldb/trunk/source/Plugins/SymbolFile/DWARF/DWARFCompileUnit.h Thu Oct 14 21:03:22 2010 @@ -141,6 +141,7 @@ NameToDIE& objc_class_selector_dies, NameToDIE& name_to_global_die, NameToDIE& name_to_type_die, + NameToDIE& name_to_namespace_die, const DWARFDebugRanges* debug_ranges, DWARFDebugAranges *aranges); 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=116558&r1=116557&r2=116558&view=diff ============================================================================== --- lldb/trunk/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp (original) +++ lldb/trunk/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp Thu Oct 14 21:03:22 2010 @@ -163,7 +163,8 @@ m_function_selector_index(), m_objc_class_selectors_index(), m_global_index(), - m_types_index(), + m_type_index(), + m_namespace_index(), m_indexed(false), m_ranges() { @@ -1718,7 +1719,8 @@ m_function_selector_index, m_objc_class_selectors_index, m_global_index, - m_types_index, + m_type_index, + m_namespace_index, DebugRanges(), m_aranges.get()); @@ -1742,7 +1744,9 @@ s.Printf("\nFunction selectors:\n"); m_function_selector_index.Dump (&s); s.Printf("\nObjective C class selectors:\n"); m_objc_class_selectors_index.Dump (&s); s.Printf("\nGlobals and statics:\n"); m_global_index.Dump (&s); - s.Printf("\nTypes:\n"); m_types_index.Dump (&s); + s.Printf("\nTypes:\n"); m_type_index.Dump (&s); + s.Printf("\nNamepaces:\n"); m_namespace_index.Dump (&s); + #endif } } @@ -2033,7 +2037,7 @@ DWARFCompileUnit* prev_cu = NULL; const DWARFDebugInfoEntry* die = NULL; std::vector die_info_array; - const size_t num_matches = m_types_index.Find (name, die_info_array); + const size_t num_matches = m_type_index.Find (name, die_info_array); for (size_t i=0; iGetCompileUnitAtIndex(die_info_array[i].cu_idx); @@ -2770,7 +2774,7 @@ { // We have a forward declaration std::vector die_info_array; - const size_t num_matches = m_types_index.Find (type_name_const_str, die_info_array); + const size_t num_matches = m_type_index.Find (type_name_const_str, die_info_array); DWARFCompileUnit* type_cu = NULL; DWARFCompileUnit* curr_cu = dwarf_cu; DWARFDebugInfo *info = DebugInfo(); 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=116558&r1=116557&r2=116558&view=diff ============================================================================== --- lldb/trunk/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.h (original) +++ lldb/trunk/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.h Thu Oct 14 21:03:22 2010 @@ -313,8 +313,9 @@ NameToDIE m_function_method_index; // All inlined functions NameToDIE m_function_selector_index; // All method names for functions of classes NameToDIE m_objc_class_selectors_index; // Given a class name, find all selectors for the class - NameToDIE m_global_index; // Global and static variables - NameToDIE m_types_index; // All type DIE offsets + NameToDIE m_global_index; // Global and static variables + NameToDIE m_type_index; // All type DIE offsets + NameToDIE m_namespace_index; // All type DIE offsets bool m_indexed; std::auto_ptr m_ranges; From johnny.chen at apple.com Thu Oct 14 21:28:13 2010 From: johnny.chen at apple.com (Johnny Chen) Date: Fri, 15 Oct 2010 02:28:13 -0000 Subject: [Lldb-commits] [lldb] r116559 - in /lldb/trunk/test: dotest.py lldbtest.py Message-ID: <20101015022813.5B5BC2A6C12C@llvm.org> Author: johnny Date: Thu Oct 14 21:28:13 2010 New Revision: 116559 URL: http://llvm.org/viewvc/llvm-project?rev=116559&view=rev Log: Simply use the TestBase.markFailure() callback method to set the __failed__ flag. Modified: lldb/trunk/test/dotest.py lldb/trunk/test/lldbtest.py Modified: lldb/trunk/test/dotest.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/dotest.py?rev=116559&r1=116558&r2=116559&view=diff ============================================================================== --- lldb/trunk/test/dotest.py (original) +++ lldb/trunk/test/dotest.py Thu Oct 14 21:28:13 2010 @@ -616,7 +616,6 @@ method = getattr(test, "markFailure", None) if method: method() - setattr(test, "__failed__", True) result = unittest2.TextTestRunner(stream=sys.stderr, verbosity=verbose, resultclass=LLDBTestResult).run(suite) Modified: lldb/trunk/test/lldbtest.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/lldbtest.py?rev=116559&r1=116558&r2=116559&view=diff ============================================================================== --- lldb/trunk/test/lldbtest.py (original) +++ lldb/trunk/test/lldbtest.py Thu Oct 14 21:28:13 2010 @@ -411,12 +411,16 @@ self.old_stderr = sys.stderr sys.stderr = self.session + # Optimistically set self.failed to False initially. + self.__failed__ = False + def setTearDownCleanup(self, dictionary=None): self.dict = dictionary self.doTearDownCleanup = True def markFailure(self): """Callback invoked when we (the test case instance) failed.""" + self.__failed__ = True with recording(self, False) as sbuf: # False because there's no need to write "FAIL" to the stderr again. print >> sbuf, "FAIL" @@ -454,10 +458,10 @@ if not module.cleanup(dictionary=self.dict): raise Exception("Don't know how to do cleanup") - # lldb.test_result is an instance of unittest2.TextTestResult enforced - # as a singleton. During tearDown(), lldb.test_result can be consulted - # in order to determine whether we failed for the current test instance. - if getattr(self, "__failed__", False): + # See also LLDBTestResult (dotest.py) which is a singlton class derived + # from TextTestResult and overwrites addFailure() method to allow us to + # to check the failure status here. + if self.__failed__: self.dumpSessionInfo() # Restore the sys.stderr to what it was before. From gclayton at apple.com Thu Oct 14 21:39:01 2010 From: gclayton at apple.com (Greg Clayton) Date: Fri, 15 Oct 2010 02:39:01 -0000 Subject: [Lldb-commits] [lldb] r116561 - in /lldb/trunk: include/lldb/Target/UnixSignals.h source/Target/UnixSignals.cpp Message-ID: <20101015023901.60DE52A6C12C@llvm.org> Author: gclayton Date: Thu Oct 14 21:39:01 2010 New Revision: 116561 URL: http://llvm.org/viewvc/llvm-project?rev=116561&view=rev Log: Added short names and descriptions to the UnixSignals class. Also cleaned up the code a bit. Modified: lldb/trunk/include/lldb/Target/UnixSignals.h lldb/trunk/source/Target/UnixSignals.cpp Modified: lldb/trunk/include/lldb/Target/UnixSignals.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/Target/UnixSignals.h?rev=116561&r1=116560&r2=116561&view=diff ============================================================================== --- lldb/trunk/include/lldb/Target/UnixSignals.h (original) +++ lldb/trunk/include/lldb/Target/UnixSignals.h Thu Oct 14 21:39:01 2010 @@ -97,9 +97,11 @@ void AddSignal (int signo, const char *name, + const char *short_name, bool default_suppress, bool default_stop, - bool default_notify); + bool default_notify, + const char *description); void RemoveSignal (int signo); @@ -111,37 +113,23 @@ struct Signal { - typedef enum - { - eCondSuppress = 0, - eCondStop = 1, - eCondNotify - } Condition; - ConstString m_name; - bool m_conditions[3]; + ConstString m_short_name; + std::string m_description; + bool m_suppress:1, + m_stop:1, + m_notify:1; Signal (const char *name, + const char *short_name, bool default_suppress, bool default_stop, - bool default_notify); + bool default_notify, + const char *description); ~Signal () {} }; - bool - GetCondition (int signo, - Signal::Condition cond_pos) const; - bool - SetCondition (int signo, - Signal::Condition cond_pos, - bool value); - - bool - SetCondition (const char *signal_name, - Signal::Condition cond_pos, - bool value); - Signal * GetSignalByName (const char *name, int32_t &signo); Modified: lldb/trunk/source/Target/UnixSignals.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Target/UnixSignals.cpp?rev=116561&r1=116560&r2=116561&view=diff ============================================================================== --- lldb/trunk/source/Target/UnixSignals.cpp (original) +++ lldb/trunk/source/Target/UnixSignals.cpp Thu Oct 14 21:39:01 2010 @@ -16,13 +16,24 @@ using namespace lldb_private; -UnixSignals::Signal::Signal (const char *name, bool default_suppress, bool default_stop, bool default_notify) : +UnixSignals::Signal::Signal +( + const char *name, + const char *short_name, + bool default_suppress, + bool default_stop, + bool default_notify, + const char *description +) : m_name (name), - m_conditions () + m_short_name (short_name), + m_description (), + m_suppress (default_suppress), + m_stop (default_stop), + m_notify (default_notify) { - m_conditions[Signal::eCondSuppress] = default_suppress; - m_conditions[Signal::eCondStop] = default_stop; - m_conditions[Signal::eCondNotify] = default_notify; + if (description) + m_description.assign (description); } //---------------------------------------------------------------------- @@ -47,51 +58,55 @@ // order, you can either subclass this class, and use Add & Remove to change them // or you can subclass and build them afresh in your constructor; m_signals.clear(); - // SIGNO NAME SUPPRESS STOP NOTIFY - // ===== ============ ========= ====== ====== - AddSignal(1, "SIGHUP", false, true, true ); // 1 hangup - AddSignal(2, "SIGINT", true, true, true ); // 2 interrupt - AddSignal(3, "SIGQUIT", false, true, true ); // 3 quit - AddSignal(4, "SIGILL", false, true, true ); // 4 illegal instruction (not reset when caught) - AddSignal(5, "SIGTRAP", true, true, true ); // 5 trace trap (not reset when caught) - AddSignal(6, "SIGABRT", false, true, true ); // 6 abort() - AddSignal(7, "SIGEMT", false, true, true ); // 7 pollable event ([XSR] generated, not supported) - AddSignal(8, "SIGFPE", false, true, true ); // 8 floating point exception - AddSignal(9, "SIGKILL", false, true, true ); // 9 kill (cannot be caught or ignored) - AddSignal(10, "SIGBUS", false, true, true ); // 10 bus error - AddSignal(11, "SIGSEGV", false, true, true ); // 11 segmentation violation - AddSignal(12, "SIGSYS", false, true, true ); // 12 bad argument to system call - AddSignal(13, "SIGPIPE", false, true, true ); // 13 write on a pipe with no one to read it - AddSignal(14, "SIGALRM", false, false, true ); // 14 alarm clock - AddSignal(15, "SIGTERM", false, true, true ); // 15 software termination signal from kill - AddSignal(16, "SIGURG", false, false, false); // 16 urgent condition on IO channel - AddSignal(17, "SIGSTOP", false, true, true ); // 17 sendable stop signal not from tty - AddSignal(18, "SIGTSTP", false, true, true ); // 18 stop signal from tty - AddSignal(19, "SIGCONT", false, true, true ); // 19 continue a stopped process - AddSignal(20, "SIGCHLD", false, false, true ); // 20 to parent on child stop or exit - AddSignal(21, "SIGTTIN", false, true, true ); // 21 to readers pgrp upon background tty read - AddSignal(22, "SIGTTOU", false, true, true ); // 22 like TTIN for output if (tp->t_local<OSTOP) - AddSignal(23, "SIGIO", false, false, false); // 23 input/output possible signal - AddSignal(24, "SIGXCPU", false, true, true ); // 24 exceeded CPU time limit - AddSignal(25, "SIGXFSZ", false, true, true ); // 25 exceeded file size limit - AddSignal(26, "SIGVTALRM", false, false, false); // 26 virtual time alarm - AddSignal(27, "SIGPROF", false, false, false); // 27 profiling time alarm - AddSignal(28, "SIGWINCH", false, false, false); // 28 window size changes - AddSignal(29, "SIGINFO", false, true, true ); // 29 information request - AddSignal(30, "SIGUSR1", false, true, true ); // 30 user defined signal 1 - AddSignal(31, "SIGUSR2", false, true, true ); // 31 user defined signal 2 + // SIGNO NAME SHORT NAME SUPPRESS STOP NOTIFY DESCRIPTION + // ====== ============ ========== ========= ====== ====== =================================================== + AddSignal (1, "SIGHUP", "HUP", false, true, true, "hangup"); + AddSignal (2, "SIGINT", "INT", true, true, true, "interrupt"); + AddSignal (3, "SIGQUIT", "QUIT", false, true, true, "quit"); + AddSignal (4, "SIGILL", "ILL", false, true, true, "illegal instruction"); + AddSignal (5, "SIGTRAP", "TRAP", true, true, true, "trace trap (not reset when caught)"); + AddSignal (6, "SIGABRT", "ABRT", false, true, true, "abort()"); + AddSignal (7, "SIGEMT", "EMT", false, true, true, "pollable event"); + AddSignal (8, "SIGFPE", "FPE", false, true, true, "floating point exception"); + AddSignal (9, "SIGKILL", "KILL", false, true, true, "kill"); + AddSignal (10, "SIGBUS", "BUS", false, true, true, "bus error"); + AddSignal (11, "SIGSEGV", "SEGV", false, true, true, "segmentation violation"); + AddSignal (12, "SIGSYS", "SYS", false, true, true, "bad argument to system call"); + AddSignal (13, "SIGPIPE", "PIPE", false, true, true, "write on a pipe with no one to read it"); + AddSignal (14, "SIGALRM", "ALRM", false, false, true, "alarm clock"); + AddSignal (15, "SIGTERM", "TERM", false, true, true, "software termination signal from kill"); + AddSignal (16, "SIGURG", "URG", false, false, false, "urgent condition on IO channel"); + AddSignal (17, "SIGSTOP", "STOP", false, true, true, "sendable stop signal not from tty"); + AddSignal (18, "SIGTSTP", "TSTP", false, true, true, "stop signal from tty"); + AddSignal (19, "SIGCONT", "CONT", false, true, true, "continue a stopped process"); + AddSignal (20, "SIGCHLD", "CHLD", false, false, true, "to parent on child stop or exit"); + AddSignal (21, "SIGTTIN", "TTIN", false, true, true, "to readers process group upon background tty read"); + AddSignal (22, "SIGTTOU", "TTOU", false, true, true, "to readers process group upon background tty write"); + AddSignal (23, "SIGIO", "IO", false, false, false, "input/output possible signal"); + AddSignal (24, "SIGXCPU", "XCPU", false, true, true, "exceeded CPU time limit"); + AddSignal (25, "SIGXFSZ", "XFSZ", false, true, true, "exceeded file size limit"); + AddSignal (26, "SIGVTALRM", "VTALRM", false, false, false, "virtual time alarm"); + AddSignal (27, "SIGPROF", "PROF", false, false, false, "profiling time alarm"); + AddSignal (28, "SIGWINCH", "WINCH", false, false, false, "window size changes"); + AddSignal (29, "SIGINFO", "INFO", false, true, true, "information request"); + AddSignal (30, "SIGUSR1", "USR1", false, true, true, "user defined signal 1"); + AddSignal (31, "SIGUSR2", "USR2", false, true, true, "user defined signal 2"); } void -UnixSignals::AddSignal (int signo, const char *name, bool default_suppress, bool default_stop, bool default_notify) +UnixSignals::AddSignal +( + int signo, + const char *name, + const char *short_name, + bool default_suppress, + bool default_stop, + bool default_notify, + const char *description +) { - collection::iterator iter = m_signals.find (signo); - struct Signal new_signal (name, default_suppress, default_stop, default_notify); - - if (iter != m_signals.end()) - m_signals.erase (iter); - - m_signals.insert (iter, collection::value_type (signo, new_signal)); + Signal new_signal (name, short_name, default_suppress, default_stop, default_notify, description); + m_signals.insert (std::make_pair(signo, new_signal)); } void @@ -110,10 +125,10 @@ collection::iterator pos, end = m_signals.end (); for (pos = m_signals.begin (); pos != end; pos++) { - if (const_name == (*pos).second.m_name) + if ((const_name == pos->second.m_name) || (const_name == pos->second.m_short_name)) { - signo = (*pos).first; - return &((*pos).second); + signo = pos->first; + return &pos->second; } } return NULL; @@ -128,10 +143,10 @@ collection::const_iterator pos, end = m_signals.end (); for (pos = m_signals.begin (); pos != end; pos++) { - if (const_name == (*pos).second.m_name) + if (const_name == pos->second.m_name) { - signo = (*pos).first; - return &((*pos).second); + signo = pos->first; + return &(pos->second); } } return NULL; @@ -144,7 +159,7 @@ if (pos == m_signals.end()) return NULL; else - return (*pos).second.m_name.GetCString (); + return pos->second.m_name.GetCString (); } @@ -188,7 +203,7 @@ if (pos == end) return LLDB_INVALID_SIGNAL_NUMBER; else - return (*pos).first; + return pos->first; } } @@ -206,107 +221,92 @@ return NULL; else { - const Signal &signal = (*pos).second; - should_suppress = signal.m_conditions[Signal::eCondSuppress]; - should_stop = signal.m_conditions[Signal::eCondStop]; - should_notify = signal.m_conditions[Signal::eCondNotify]; + const Signal &signal = pos->second; + should_suppress = signal.m_suppress; + should_stop = signal.m_stop; + should_notify = signal.m_notify; return signal.m_name.AsCString(""); } } bool -UnixSignals::GetCondition -( - int32_t signo, - UnixSignals::Signal::Condition cond_pos -) const +UnixSignals::GetShouldSuppress (int signo) const { collection::const_iterator pos = m_signals.find (signo); - if (pos == m_signals.end()) - return false; - else - return (*pos).second.m_conditions[cond_pos]; + if (pos != m_signals.end()) + return pos->second.m_suppress; + return false; } bool -UnixSignals::SetCondition (int32_t signo, UnixSignals::Signal::Condition cond_pos, bool value) +UnixSignals::SetShouldSuppress (int signo, bool value) { collection::iterator pos = m_signals.find (signo); - if (pos == m_signals.end()) - return false; - else - { - bool ret_value = (*pos).second.m_conditions[cond_pos]; - (*pos).second.m_conditions[cond_pos] = value; - return ret_value; - } -} - -bool -UnixSignals::SetCondition (const char *signal_name, UnixSignals::Signal::Condition cond_pos, bool value) -{ - int32_t signo; - Signal *signal = GetSignalByName (signal_name, signo); - if (signal == NULL) - return false; - else + if (pos != m_signals.end()) { - bool ret_value = signal->m_conditions[cond_pos]; - signal->m_conditions[cond_pos] = value; - return ret_value; + pos->second.m_suppress = value; + return true; } -} - -bool -UnixSignals::GetShouldSuppress (int signo) const -{ - return GetCondition (signo, Signal::eCondSuppress); -} - -bool -UnixSignals::SetShouldSuppress (int signo, bool value) -{ - return SetCondition (signo, Signal::eCondSuppress, value); + return false; } bool UnixSignals::SetShouldSuppress (const char *signal_name, bool value) { - return SetCondition (signal_name, Signal::eCondSuppress, value); + return SetShouldSuppress (GetSignalNumberFromName (signal_name), value); } bool UnixSignals::GetShouldStop (int signo) const { - return GetCondition (signo, Signal::eCondStop); + collection::const_iterator pos = m_signals.find (signo); + if (pos != m_signals.end()) + return pos->second.m_stop; + return false; } bool UnixSignals::SetShouldStop (int signo, bool value) { - return SetCondition (signo, Signal::eCondStop, value); + collection::iterator pos = m_signals.find (signo); + if (pos != m_signals.end()) + { + pos->second.m_stop = value; + return true; + } + return false; } bool UnixSignals::SetShouldStop (const char *signal_name, bool value) { - return SetCondition (signal_name, Signal::eCondStop, value); + return SetShouldStop (GetSignalNumberFromName (signal_name), value); } bool UnixSignals::GetShouldNotify (int signo) const { - return GetCondition (signo, Signal::eCondNotify); + collection::const_iterator pos = m_signals.find (signo); + if (pos != m_signals.end()) + return pos->second.m_notify; + return false; } bool UnixSignals::SetShouldNotify (int signo, bool value) { - return SetCondition (signo, Signal::eCondNotify, value); + collection::iterator pos = m_signals.find (signo); + if (pos != m_signals.end()) + { + pos->second.m_notify = value; + return true; + } + return false; } bool UnixSignals::SetShouldNotify (const char *signal_name, bool value) { - return SetCondition (signal_name, Signal::eCondNotify, value); + return SetShouldNotify (GetSignalNumberFromName (signal_name), value); } + From gclayton at apple.com Thu Oct 14 21:45:05 2010 From: gclayton at apple.com (Greg Clayton) Date: Fri, 15 Oct 2010 02:45:05 -0000 Subject: [Lldb-commits] [lldb] r116562 - in /lldb/trunk: lldb.xcodeproj/project.pbxproj source/Plugins/SymbolFile/DWARF/DWARFCompileUnit.cpp source/Plugins/SymbolFile/DWARF/DWARFCompileUnit.h Message-ID: <20101015024505.371E92A6C12C@llvm.org> Author: gclayton Date: Thu Oct 14 21:45:05 2010 New Revision: 116562 URL: http://llvm.org/viewvc/llvm-project?rev=116562&view=rev Log: Did a bit of parameter renaming. Modified: lldb/trunk/lldb.xcodeproj/project.pbxproj lldb/trunk/source/Plugins/SymbolFile/DWARF/DWARFCompileUnit.cpp lldb/trunk/source/Plugins/SymbolFile/DWARF/DWARFCompileUnit.h Modified: lldb/trunk/lldb.xcodeproj/project.pbxproj URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/lldb.xcodeproj/project.pbxproj?rev=116562&r1=116561&r2=116562&view=diff ============================================================================== --- lldb/trunk/lldb.xcodeproj/project.pbxproj (original) +++ lldb/trunk/lldb.xcodeproj/project.pbxproj Thu Oct 14 21:45:05 2010 @@ -2445,6 +2445,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/Plugins/SymbolFile/DWARF/DWARFCompileUnit.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Plugins/SymbolFile/DWARF/DWARFCompileUnit.cpp?rev=116562&r1=116561&r2=116562&view=diff ============================================================================== --- lldb/trunk/source/Plugins/SymbolFile/DWARF/DWARFCompileUnit.cpp (original) +++ lldb/trunk/source/Plugins/SymbolFile/DWARF/DWARFCompileUnit.cpp Thu Oct 14 21:45:05 2010 @@ -564,14 +564,14 @@ DWARFCompileUnit::Index ( const uint32_t cu_idx, - NameToDIE& base_name_to_function_die, - NameToDIE& full_name_to_function_die, - NameToDIE& method_name_to_function_die, - NameToDIE& selector_name_to_function_die, - NameToDIE& objc_class_selector_dies, - NameToDIE& name_to_global_die, - NameToDIE& name_to_type_die, - NameToDIE& name_to_namespace_die, + NameToDIE& func_basenames, + NameToDIE& func_fullnames, + NameToDIE& func_methods, + NameToDIE& func_selectors, + NameToDIE& objc_class_selectors, + NameToDIE& globals, + NameToDIE& types, + NameToDIE& namespaces, const DWARFDebugRanges *debug_ranges, DWARFDebugAranges *aranges ) @@ -799,14 +799,14 @@ // Keep a map of the objective C class name to all selector // DIEs - objc_class_selector_dies.Insert(class_name, die_info); + objc_class_selectors.Insert(class_name, die_info); // Skip the space ++method_name; // Extract the objective C basename and add it to the // accelerator tables size_t method_name_len = name_len - (method_name - name) - 1; - selector_name_to_function_die.Insert (ConstString (method_name, method_name_len), die_info); + func_selectors.Insert (ConstString (method_name, method_name_len), die_info); } } } @@ -843,14 +843,14 @@ if (is_method) - method_name_to_function_die.Insert (ConstString(name), die_info); + func_methods.Insert (ConstString(name), die_info); else - base_name_to_function_die.Insert (ConstString(name), die_info); + func_basenames.Insert (ConstString(name), die_info); } if (mangled.GetMangledName()) - full_name_to_function_die.Insert (mangled.GetMangledName(), die_info); + func_fullnames.Insert (mangled.GetMangledName(), die_info); if (mangled.GetDemangledName()) - full_name_to_function_die.Insert (mangled.GetDemangledName(), die_info); + func_fullnames.Insert (mangled.GetDemangledName(), die_info); } break; @@ -858,11 +858,11 @@ if (has_address) { if (name) - base_name_to_function_die.Insert (ConstString(name), die_info); + func_basenames.Insert (ConstString(name), die_info); if (mangled.GetMangledName()) - full_name_to_function_die.Insert (mangled.GetMangledName(), die_info); + func_fullnames.Insert (mangled.GetMangledName(), die_info); if (mangled.GetDemangledName()) - full_name_to_function_die.Insert (mangled.GetDemangledName(), die_info); + func_fullnames.Insert (mangled.GetDemangledName(), die_info); } break; @@ -877,19 +877,19 @@ case DW_TAG_typedef: if (name && is_declaration == false) { - name_to_type_die.Insert (ConstString(name), die_info); + types.Insert (ConstString(name), die_info); } break; case DW_TAG_namespace: if (name) - name_to_namespace_die.Insert (ConstString(name), die_info); + namespaces.Insert (ConstString(name), die_info); break; case DW_TAG_variable: if (name && has_location && is_global_or_static_variable) { - name_to_global_die.Insert (ConstString(name), die_info); + globals.Insert (ConstString(name), die_info); } break; Modified: lldb/trunk/source/Plugins/SymbolFile/DWARF/DWARFCompileUnit.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Plugins/SymbolFile/DWARF/DWARFCompileUnit.h?rev=116562&r1=116561&r2=116562&view=diff ============================================================================== --- lldb/trunk/source/Plugins/SymbolFile/DWARF/DWARFCompileUnit.h (original) +++ lldb/trunk/source/Plugins/SymbolFile/DWARF/DWARFCompileUnit.h Thu Oct 14 21:45:05 2010 @@ -134,14 +134,14 @@ // void Index (const uint32_t cu_idx, - NameToDIE& base_name_to_function_die, - NameToDIE& full_name_to_function_die, - NameToDIE& method_name_to_function_die, - NameToDIE& selector_name_to_function_die, - NameToDIE& objc_class_selector_dies, - NameToDIE& name_to_global_die, - NameToDIE& name_to_type_die, - NameToDIE& name_to_namespace_die, + NameToDIE& func_basenames, + NameToDIE& func_fullnames, + NameToDIE& func_methods, + NameToDIE& func_selectors, + NameToDIE& objc_class_selectors, + NameToDIE& globals, + NameToDIE& types, + NameToDIE& namespaces, const DWARFDebugRanges* debug_ranges, DWARFDebugAranges *aranges); From gclayton at apple.com Thu Oct 14 22:36:13 2010 From: gclayton at apple.com (Greg Clayton) Date: Fri, 15 Oct 2010 03:36:13 -0000 Subject: [Lldb-commits] [lldb] r116565 - in /lldb/trunk/source/Expression: ClangASTSource.cpp ClangExpressionDeclMap.cpp Message-ID: <20101015033613.834802A6C12C@llvm.org> Author: gclayton Date: Thu Oct 14 22:36:13 2010 New Revision: 116565 URL: http://llvm.org/viewvc/llvm-project?rev=116565&view=rev Log: Skip checking for a bunch of built-ins when evaluating an expression. Modified: lldb/trunk/source/Expression/ClangASTSource.cpp lldb/trunk/source/Expression/ClangExpressionDeclMap.cpp Modified: lldb/trunk/source/Expression/ClangASTSource.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Expression/ClangASTSource.cpp?rev=116565&r1=116564&r2=116565&view=diff ============================================================================== --- lldb/trunk/source/Expression/ClangASTSource.cpp (original) +++ lldb/trunk/source/Expression/ClangASTSource.cpp Thu Oct 14 22:36:13 2010 @@ -9,6 +9,7 @@ #include "clang/AST/ASTContext.h" +#include "lldb/Core/Log.h" #include "lldb/Expression/ClangASTSource.h" #include "lldb/Expression/ClangExpression.h" #include "lldb/Expression/ClangExpressionDeclMap.h" @@ -37,8 +38,13 @@ uint32_t ClangASTSource::GetNumExternalSelectors() { return 0; } // The core lookup interface. -DeclContext::lookup_result ClangASTSource::FindExternalVisibleDeclsByName(const DeclContext *DC, DeclarationName Name) { - switch (Name.getNameKind()) { +DeclContext::lookup_result ClangASTSource::FindExternalVisibleDeclsByName +( + const DeclContext *decl_ctx, + DeclarationName decl_name +) +{ + switch (decl_name.getNameKind()) { // Normal identifiers. case DeclarationName::Identifier: break; @@ -51,7 +57,7 @@ // Using directives found in this context. // Tell Sema we didn't find any or we'll end up getting asked a *lot*. case DeclarationName::CXXUsingDirective: - return SetNoExternalVisibleDeclsForName(DC, Name); + return SetNoExternalVisibleDeclsForName(decl_ctx, decl_name); // These aren't looked up like this. case DeclarationName::ObjCZeroArgSelector: @@ -65,19 +71,34 @@ case DeclarationName::CXXConversionFunctionName: return DeclContext::lookup_result(); } + + + std::string name (decl_name.getAsString()); + if (0 == name.compare ("__va_list_tag") || + 0 == name.compare ("__int128_t") || + 0 == name.compare ("__uint128_t") || + 0 == name.compare ("SEL") || + 0 == name.compare ("id") || + 0 == name.compare ("Class") || + 0 == name.compare ("nil") || + 0 == name.compare ("gp_offset") || + 0 == name.compare ("fp_offset") || + 0 == name.compare ("overflow_arg_area") || + 0 == name.compare ("reg_save_area") || + 0 == name.find ("__builtin") ) + { + Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS); + if (log) + log->Printf("Ignoring built-in in find external declarations for name: '%s'", name.c_str()); + + return SetNoExternalVisibleDeclsForName(decl_ctx, decl_name); + } llvm::SmallVector Decls; - NameSearchContext NSC(*this, Decls, Name, DC); - - std::string name (Name.getAsString()); - // TODO: Figure out what to do here, after recent changes to the DWARF - // parser where more types are now in type by name index, we were sometimes - // finding our own version of a builtin? Skip it for now until we figure out - // how to get around this properly. - if (name.compare("__va_list_tag") != 0) - DeclMap.GetDecls(NSC, name.c_str()); - return SetExternalVisibleDeclsForName(DC, Name, Decls); + NameSearchContext NSC(*this, Decls, decl_name, decl_ctx); + DeclMap.GetDecls(NSC, name.c_str()); + return SetExternalVisibleDeclsForName(decl_ctx, decl_name, Decls); } void ClangASTSource::MaterializeVisibleDecls(const DeclContext *DC) Modified: lldb/trunk/source/Expression/ClangExpressionDeclMap.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Expression/ClangExpressionDeclMap.cpp?rev=116565&r1=116564&r2=116565&view=diff ============================================================================== --- lldb/trunk/source/Expression/ClangExpressionDeclMap.cpp (original) +++ lldb/trunk/source/Expression/ClangExpressionDeclMap.cpp Thu Oct 14 22:36:13 2010 @@ -907,7 +907,7 @@ Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS); if (log) - log->Printf("Hunting for a definition for %s", name); + log->Printf("Hunting for a definition for '%s'", name); // Back out in all cases where we're not fully initialized if (!m_exe_ctx || !m_exe_ctx->frame || !m_sym_ctx) From johnny.chen at apple.com Fri Oct 15 11:13:00 2010 From: johnny.chen at apple.com (Johnny Chen) Date: Fri, 15 Oct 2010 16:13:00 -0000 Subject: [Lldb-commits] [lldb] r116582 - /lldb/trunk/test/lldbtest.py Message-ID: <20101015161300.F0B352A6C12C@llvm.org> Author: johnny Date: Fri Oct 15 11:13:00 2010 New Revision: 116582 URL: http://llvm.org/viewvc/llvm-project?rev=116582&view=rev Log: Be more specific about cases whenthe runCmd() check flag is False, meaning there is no need to check the return status of the command execution, and an error status is not deemed a failure in the test. Modified: lldb/trunk/test/lldbtest.py Modified: lldb/trunk/test/lldbtest.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/lldbtest.py?rev=116582&r1=116581&r2=116582&view=diff ============================================================================== --- lldb/trunk/test/lldbtest.py (original) +++ lldb/trunk/test/lldbtest.py Fri Oct 15 11:13:00 2010 @@ -485,6 +485,8 @@ with recording(self, trace) as sbuf: print >> sbuf, "runCmd:", cmd + if not check: + print >> sbuf, "checking of return status not required" if self.res.Succeeded(): print >> sbuf, "output:", self.res.GetOutput() else: From johnny.chen at apple.com Fri Oct 15 11:22:10 2010 From: johnny.chen at apple.com (Johnny Chen) Date: Fri, 15 Oct 2010 16:22:10 -0000 Subject: [Lldb-commits] [lldb] r116583 - /lldb/trunk/test/lldbtest.py Message-ID: <20101015162210.4D34C2A6C12C@llvm.org> Author: johnny Date: Fri Oct 15 11:22:10 2010 New Revision: 116583 URL: http://llvm.org/viewvc/llvm-project?rev=116583&view=rev Log: Add more comments. Modified: lldb/trunk/test/lldbtest.py Modified: lldb/trunk/test/lldbtest.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/lldbtest.py?rev=116583&r1=116582&r2=116583&view=diff ============================================================================== --- lldb/trunk/test/lldbtest.py (original) +++ lldb/trunk/test/lldbtest.py Fri Oct 15 11:22:10 2010 @@ -411,7 +411,9 @@ self.old_stderr = sys.stderr sys.stderr = self.session - # Optimistically set self.failed to False initially. + # Optimistically set self.__failed__ to False initially. If the test + # failed, the session info (self.session) is then dumped into a session + # specific file for diagnosis. self.__failed__ = False def setTearDownCleanup(self, dictionary=None): @@ -422,7 +424,8 @@ """Callback invoked when we (the test case instance) failed.""" self.__failed__ = True with recording(self, False) as sbuf: - # False because there's no need to write "FAIL" to the stderr again. + # False because there's no need to write "FAIL" to the stderr twice. + # Once by the Python unittest framework, and a second time by us. print >> sbuf, "FAIL" def dumpSessionInfo(self): From johnny.chen at apple.com Fri Oct 15 11:33:17 2010 From: johnny.chen at apple.com (Johnny Chen) Date: Fri, 15 Oct 2010 16:33:17 -0000 Subject: [Lldb-commits] [lldb] r116585 - /lldb/trunk/examples/python/disasm.py Message-ID: <20101015163317.A71152A6C12C@llvm.org> Author: johnny Date: Fri Oct 15 11:33:17 2010 New Revision: 116585 URL: http://llvm.org/viewvc/llvm-project?rev=116585&view=rev Log: There's no need to explicitly call lldb.SBDebugger.Initialize() now. It is done when importing the lldb module. Modified: lldb/trunk/examples/python/disasm.py Modified: lldb/trunk/examples/python/disasm.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/examples/python/disasm.py?rev=116585&r1=116584&r2=116585&view=diff ============================================================================== --- lldb/trunk/examples/python/disasm.py (original) +++ lldb/trunk/examples/python/disasm.py Fri Oct 15 11:33:17 2010 @@ -17,9 +17,6 @@ for i in range(insts.GetSize()): print insts.GetInstructionAtIndex(i) -# Initialize LLDB so we can use it -lldb.SBDebugger.Initialize() - # Create a new debugger instance debugger = lldb.SBDebugger.Create() From johnny.chen at apple.com Fri Oct 15 13:07:09 2010 From: johnny.chen at apple.com (Johnny Chen) Date: Fri, 15 Oct 2010 18:07:09 -0000 Subject: [Lldb-commits] [lldb] r116596 - /lldb/trunk/test/lldbtest.py Message-ID: <20101015180709.9FC112A6C12C@llvm.org> Author: johnny Date: Fri Oct 15 13:07:09 2010 New Revision: 116596 URL: http://llvm.org/viewvc/llvm-project?rev=116596&view=rev Log: Add a const string for assert message. Remove extra printing of newlines from the session recordings. Modified: lldb/trunk/test/lldbtest.py Modified: lldb/trunk/test/lldbtest.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/lldbtest.py?rev=116596&r1=116595&r2=116596&view=diff ============================================================================== --- lldb/trunk/test/lldbtest.py (original) +++ lldb/trunk/test/lldbtest.py Fri Oct 15 13:07:09 2010 @@ -147,6 +147,8 @@ BREAKPOINT_HIT_TWICE = "Breakpoint resolved with hit cout = 2" +BREAKPOINT_HIT_THRICE = "Breakpoint resolved with hit cout = 3" + STEP_OUT_SUCCEEDED = "Thread step-out succeeded" STOPPED_DUE_TO_BREAKPOINT = "Process state is stopped due to breakpoint" @@ -568,7 +570,6 @@ with recording(self, trace) as sbuf: print >> sbuf, "%s start string: %s" % (heading, startstr) print >> sbuf, "Matched" if matched else "Not matched" - print >> sbuf # Look for sub strings, if specified. keepgoing = matched if matching else not matched @@ -581,8 +582,6 @@ keepgoing = matched if matching else not matched if not keepgoing: break - with recording(self, trace) as sbuf: - print >> sbuf # Search for regular expression patterns, if specified. keepgoing = matched if matching else not matched @@ -596,8 +595,6 @@ keepgoing = matched if matching else not matched if not keepgoing: break - with recording(self, trace) as sbuf: - print >> sbuf self.assertTrue(matched if matching else not matched, msg if msg else CMD_MSG(str, exe)) From johnny.chen at apple.com Fri Oct 15 13:52:22 2010 From: johnny.chen at apple.com (Johnny Chen) Date: Fri, 15 Oct 2010 18:52:22 -0000 Subject: [Lldb-commits] [lldb] r116607 - in /lldb/trunk/test: breakpoint_conditions/ breakpoint_conditions/Makefile breakpoint_conditions/TestBreakpointConditions.py breakpoint_conditions/main.c lldbtest.py Message-ID: <20101015185222.CDCAD2A6C12C@llvm.org> Author: johnny Date: Fri Oct 15 13:52:22 2010 New Revision: 116607 URL: http://llvm.org/viewvc/llvm-project?rev=116607&view=rev Log: Add a test case for exercising breakpoint conditions using the lldb command: breakpoint modify -c 'val == 3' 1 after: breakpoint set -n c which sets a breakpoint on function 'c'. The breakpoint should only stop if expression 'val == 3' evaluates to true. Added: lldb/trunk/test/breakpoint_conditions/ lldb/trunk/test/breakpoint_conditions/Makefile lldb/trunk/test/breakpoint_conditions/TestBreakpointConditions.py lldb/trunk/test/breakpoint_conditions/main.c Modified: lldb/trunk/test/lldbtest.py Added: lldb/trunk/test/breakpoint_conditions/Makefile URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/breakpoint_conditions/Makefile?rev=116607&view=auto ============================================================================== --- lldb/trunk/test/breakpoint_conditions/Makefile (added) +++ lldb/trunk/test/breakpoint_conditions/Makefile Fri Oct 15 13:52:22 2010 @@ -0,0 +1,5 @@ +LEVEL = ../make + +C_SOURCES := main.c + +include $(LEVEL)/Makefile.rules Added: lldb/trunk/test/breakpoint_conditions/TestBreakpointConditions.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/breakpoint_conditions/TestBreakpointConditions.py?rev=116607&view=auto ============================================================================== --- lldb/trunk/test/breakpoint_conditions/TestBreakpointConditions.py (added) +++ lldb/trunk/test/breakpoint_conditions/TestBreakpointConditions.py Fri Oct 15 13:52:22 2010 @@ -0,0 +1,68 @@ +""" +Test breakpoint conditions with 'breakpoint modify -c id'. +""" + +import os, time +import re +import unittest2 +import lldb, lldbutil +from lldbtest import * + +class BreakpointConditionsTestCase(TestBase): + + mydir = "breakpoint_conditions" + + @unittest2.skipUnless(sys.platform.startswith("darwin"), "requires Darwin") + def test_with_dsym_python(self): + """Exercise breakpoint condition with 'breakpoint modify -c id'.""" + self.buildDsym() + self.breakpoint_conditions() + + def test_with_dwarf_python(self): + """Exercise breakpoint condition with 'breakpoint modify -c id'.""" + self.buildDwarf() + self.breakpoint_conditions() + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to of function 'c'. + self.line = line_number('main.c', '// Find the line number of function "c" here.') + + def breakpoint_conditions(self): + """Exercise breakpoint condition with 'breakpoint modify -c id'.""" + exe = os.path.join(os.getcwd(), "a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Create a breakpoint by function name 'c'. + self.expect("breakpoint set -n c", BREAKPOINT_CREATED, + startstr = "Breakpoint created: 1: name = 'c', locations = 1") + + # And set a condition on the breakpoint to stop on when 'val == 3'. + self.runCmd("breakpoint modify -c 'val == 3' 1") + + # Now run the program. + self.runCmd("run", RUN_SUCCEEDED) + + # 'frame variable -t val' should return 3 due to breakpoint condition. + self.expect("frame variable -t val", VARIABLES_DISPLAYED_CORRECTLY, + startstr = '(int) val = 3') + + # Also check the hit count, which should be 3, by design. + self.expect("breakpoint list", BREAKPOINT_HIT_THRICE, + substrs = ["resolved = 1", + "Condition: val == 3", + "hit count = 3"]) + + # The frame #0 should correspond to main.c:36, the executable statement + # in function name 'c'. + self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT, + substrs = ["stop reason = breakpoint"], + patterns = ["frame #0.*main.c:%d" % self.line]) + + +if __name__ == '__main__': + import atexit + lldb.SBDebugger.Initialize() + atexit.register(lambda: lldb.SBDebugger.Terminate()) + unittest2.main() Added: lldb/trunk/test/breakpoint_conditions/main.c URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/breakpoint_conditions/main.c?rev=116607&view=auto ============================================================================== --- lldb/trunk/test/breakpoint_conditions/main.c (added) +++ lldb/trunk/test/breakpoint_conditions/main.c Fri Oct 15 13:52:22 2010 @@ -0,0 +1,51 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +#include + +// This simple program is to demonstrate the capability of the lldb command +// "breakpoint modify -c 'val == 3' breakpt-id" to break within c(int val) only +// when the value of the arg is 3. + +int a(int); +int b(int); +int c(int); + +int a(int val) +{ + if (val <= 1) + return b(val); + else if (val >= 3) + return c(val); + + return val; +} + +int b(int val) +{ + return c(val); +} + +int c(int val) +{ + return val + 3; // Find the line number of function "c" here. +} + +int main (int argc, char const *argv[]) +{ + int A1 = a(1); // a(1) -> b(1) -> c(1) + printf("a(1) returns %d\n", A1); + + int B2 = b(2); // b(2) -> c(2) + printf("b(2) returns %d\n", B2); + + int A3 = a(3); // a(3) -> c(3) + printf("a(3) returns %d\n", A3); + + return 0; +} Modified: lldb/trunk/test/lldbtest.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/lldbtest.py?rev=116607&r1=116606&r2=116607&view=diff ============================================================================== --- lldb/trunk/test/lldbtest.py (original) +++ lldb/trunk/test/lldbtest.py Fri Oct 15 13:52:22 2010 @@ -491,7 +491,7 @@ with recording(self, trace) as sbuf: print >> sbuf, "runCmd:", cmd if not check: - print >> sbuf, "checking of return status not required" + print >> sbuf, "check of return status not required" if self.res.Succeeded(): print >> sbuf, "output:", self.res.GetOutput() else: From johnny.chen at apple.com Fri Oct 15 14:06:16 2010 From: johnny.chen at apple.com (Johnny Chen) Date: Fri, 15 Oct 2010 19:06:16 -0000 Subject: [Lldb-commits] [lldb] r116609 - /lldb/trunk/test/class_types/TestClassTypes.py Message-ID: <20101015190616.6E9AE2A6C12C@llvm.org> Author: johnny Date: Fri Oct 15 14:06:16 2010 New Revision: 116609 URL: http://llvm.org/viewvc/llvm-project?rev=116609&view=rev Log: Add two @expectedFailure decorators for: # rdar://problem/8557478 # test/class_types test failures: runCmd: expr this->m_c_int 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=116609&r1=116608&r2=116609&view=diff ============================================================================== --- lldb/trunk/test/class_types/TestClassTypes.py (original) +++ lldb/trunk/test/class_types/TestClassTypes.py Fri Oct 15 14:06:16 2010 @@ -36,11 +36,17 @@ self.breakpoint_creation_by_filespec_python() @unittest2.skipUnless(sys.platform.startswith("darwin"), "requires Darwin") + @unittest2.expectedFailure + # rdar://problem/8557478 + # test/class_types test failures: runCmd: expr this->m_c_int def test_with_dsym_and_expr_parser(self): """Test 'frame variable this' and 'expr this' when stopped inside a constructor.""" self.buildDsym() self.class_types_expr_parser() + @unittest2.expectedFailure + # rdar://problem/8557478 + # test/class_types test failures: runCmd: expr this->m_c_int def test_with_dwarf_and_expr_parser(self): """Test 'frame variable this' and 'expr this' when stopped inside a constructor.""" self.buildDwarf() From johnny.chen at apple.com Fri Oct 15 14:29:15 2010 From: johnny.chen at apple.com (Johnny Chen) Date: Fri, 15 Oct 2010 19:29:15 -0000 Subject: [Lldb-commits] [lldb] r116610 - /lldb/trunk/test/foundation/TestObjCMethods.py Message-ID: <20101015192915.356DA2A6C12C@llvm.org> Author: johnny Date: Fri Oct 15 14:29:15 2010 New Revision: 116610 URL: http://llvm.org/viewvc/llvm-project?rev=116610&view=rev Log: Remove the @skip("Skip due to deadlock?") decorators. Change the command to 'breakpoint delete 1' from 'breakpoint delete'. With 'breakpoint delete', the command interpreter was asking for a confirmation from the user, which there isn't any. Modified: lldb/trunk/test/foundation/TestObjCMethods.py Modified: lldb/trunk/test/foundation/TestObjCMethods.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/foundation/TestObjCMethods.py?rev=116610&r1=116609&r2=116610&view=diff ============================================================================== --- lldb/trunk/test/foundation/TestObjCMethods.py (original) +++ lldb/trunk/test/foundation/TestObjCMethods.py Fri Oct 15 14:29:15 2010 @@ -23,7 +23,6 @@ self.buildDwarf() self.break_on_objc_methods() - @unittest2.skip("Skip due to deadlock?") @unittest2.expectedFailure # rdar://problem/8542091 # rdar://problem/8492646 @@ -32,7 +31,6 @@ self.buildDsym() self.data_type_and_expr_objc() - @unittest2.skip("Skip due to deadlock?") @unittest2.expectedFailure # rdar://problem/8542091 # rdar://problem/8492646 @@ -161,7 +159,7 @@ # error: 1 errors parsing expression # - self.runCmd("breakpoint delete") + self.runCmd("breakpoint delete 1") self.expect("breakpoint set -f main.m -l %d" % self.line, BREAKPOINT_CREATED, startstr = "Breakpoint created: 2: file ='main.m', line = %d, locations = 1" % From johnny.chen at apple.com Fri Oct 15 16:18:07 2010 From: johnny.chen at apple.com (Johnny Chen) Date: Fri, 15 Oct 2010 21:18:07 -0000 Subject: [Lldb-commits] [lldb] r116621 - /lldb/trunk/test/lldbutil.py Message-ID: <20101015211807.42E552A6C12D@llvm.org> Author: johnny Date: Fri Oct 15 16:18:07 2010 New Revision: 116621 URL: http://llvm.org/viewvc/llvm-project?rev=116621&view=rev Log: Make sure to close the string buffer when finished. Modified: lldb/trunk/test/lldbutil.py Modified: lldb/trunk/test/lldbutil.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/lldbutil.py?rev=116621&r1=116620&r2=116621&view=diff ============================================================================== --- lldb/trunk/test/lldbutil.py (original) +++ lldb/trunk/test/lldbutil.py Fri Oct 15 16:18:07 2010 @@ -4,7 +4,7 @@ import lldb import sys -import StringIO +import cStringIO ################################################ # # @@ -167,7 +167,7 @@ def PrintStackTrace(thread, string_buffer = False): """Prints a simple stack trace of this thread.""" - output = StringIO.StringIO() if string_buffer else sys.stdout + output = cStringIO.StringIO() if string_buffer else sys.stdout target = thread.GetProcess().GetTarget() depth = thread.GetNumFrames() @@ -196,13 +196,14 @@ num=i, addr=load_addr, mod=mods[i], func=funcs[i], file=files[i], line=lines[i]) if string_buffer: - return output.getvalue() + with output: + return output.getvalue() def PrintStackTraces(process, string_buffer = False): """Prints the stack traces of all the threads.""" - output = StringIO.StringIO() if string_buffer else sys.stdout + output = cStringIO.StringIO() if string_buffer else sys.stdout print >> output, "Stack traces for " + repr(process) @@ -210,4 +211,5 @@ print >> output, PrintStackTrace(process.GetThreadAtIndex(i), string_buffer=True) if string_buffer: - return output.getvalue() + with output: + return output.getvalue() From ctice at apple.com Fri Oct 15 16:52:38 2010 From: ctice at apple.com (Caroline Tice) Date: Fri, 15 Oct 2010 21:52:38 -0000 Subject: [Lldb-commits] [lldb] r116626 - in /lldb/trunk/source: Commands/CommandObjectProcess.cpp lldb.cpp Message-ID: <20101015215238.A09922A6C12C@llvm.org> Author: ctice Date: Fri Oct 15 16:52:38 2010 New Revision: 116626 URL: http://llvm.org/viewvc/llvm-project?rev=116626&view=rev Log: Disable "process.macosx" plugin, since it is not being actively supported at the moment, and no longer works properly (bit rot). Modified: lldb/trunk/source/Commands/CommandObjectProcess.cpp lldb/trunk/source/lldb.cpp Modified: lldb/trunk/source/Commands/CommandObjectProcess.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Commands/CommandObjectProcess.cpp?rev=116626&r1=116625&r2=116626&view=diff ============================================================================== --- lldb/trunk/source/Commands/CommandObjectProcess.cpp (original) +++ lldb/trunk/source/Commands/CommandObjectProcess.cpp Fri Oct 15 16:52:38 2010 @@ -168,7 +168,7 @@ if (process == NULL) { - result.AppendErrorWithFormat ("Failed to find a process plugin for executable"); + result.AppendErrorWithFormat ("Failed to find a process plugin for executable.\n"); result.SetStatus (eReturnStatusFailed); return false; } Modified: lldb/trunk/source/lldb.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/lldb.cpp?rev=116626&r1=116625&r2=116626&view=diff ============================================================================== --- lldb/trunk/source/lldb.cpp (original) +++ lldb/trunk/source/lldb.cpp Fri Oct 15 16:52:38 2010 @@ -80,7 +80,7 @@ ObjectContainerUniversalMachO::Initialize(); ObjectFileMachO::Initialize(); ProcessGDBRemote::Initialize(); - ProcessMacOSX::Initialize(); + //ProcessMacOSX::Initialize(); SymbolVendorMacOSX::Initialize(); #endif Debugger::GetSettingsController (false); @@ -117,7 +117,7 @@ ObjectContainerUniversalMachO::Terminate(); ObjectFileMachO::Terminate(); ProcessGDBRemote::Terminate(); - ProcessMacOSX::Terminate(); + //ProcessMacOSX::Terminate(); SymbolVendorMacOSX::Terminate(); #endif From jingham at apple.com Fri Oct 15 17:47:37 2010 From: jingham at apple.com (Jim Ingham) Date: Fri, 15 Oct 2010 22:47:37 -0000 Subject: [Lldb-commits] [lldb] r116633 - /lldb/trunk/source/Core/ValueObjectConstResult.cpp Message-ID: <20101015224737.09D2E2A6C12C@llvm.org> Author: jingham Date: Fri Oct 15 17:47:36 2010 New Revision: 116633 URL: http://llvm.org/viewvc/llvm-project?rev=116633&view=rev Log: Mark a ValueObjectConstResult as valid if it is created with some data, don't wait till it gets updated. Modified: lldb/trunk/source/Core/ValueObjectConstResult.cpp Modified: lldb/trunk/source/Core/ValueObjectConstResult.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Core/ValueObjectConstResult.cpp?rev=116633&r1=116632&r2=116633&view=diff ============================================================================== --- lldb/trunk/source/Core/ValueObjectConstResult.cpp (original) +++ lldb/trunk/source/Core/ValueObjectConstResult.cpp Fri Oct 15 17:47:36 2010 @@ -47,6 +47,7 @@ m_value.SetContext(Value::eContextTypeOpaqueClangQualType, clang_type); m_name = name; SetIsConstant (); + SetValueIsValid(true); } ValueObjectConstResult::ValueObjectConstResult (const Error& error) : From gclayton at apple.com Fri Oct 15 17:48:33 2010 From: gclayton at apple.com (Greg Clayton) Date: Fri, 15 Oct 2010 22:48:33 -0000 Subject: [Lldb-commits] [lldb] r116634 - in /lldb/trunk: include/lldb/Core/ include/lldb/Expression/ source/Core/ source/Expression/ Message-ID: <20101015224833.C1A792A6C12C@llvm.org> Author: gclayton Date: Fri Oct 15 17:48:33 2010 New Revision: 116634 URL: http://llvm.org/viewvc/llvm-project?rev=116634&view=rev Log: Made many ConstString functions inlined in the header file. Changed all of our synthesized "___clang" functions, types and variables that get used in expressions over to have a prefix of "$_lldb". Now when we do name lookups we can easily switch off of the first '$' character to know if we should look through only our internal (when first char is '$') stuff, or when we should look through program variables, functions and types. Converted all of the clang expression code over to using "const ConstString&" values for names instead of "const char *" since there were many places that were converting the "const char *" names into ConstString names and them throwing them away. We now avoid making a lot of ConstString conversions and benefit from the quick comparisons in a few extra spots. Converted a lot of code from LLVM coding conventions into LLDB coding conventions. Modified: lldb/trunk/include/lldb/Core/ConstString.h lldb/trunk/include/lldb/Expression/ASTResultSynthesizer.h lldb/trunk/include/lldb/Expression/ASTStructExtractor.h lldb/trunk/include/lldb/Expression/ClangASTSource.h lldb/trunk/include/lldb/Expression/ClangExpressionDeclMap.h lldb/trunk/include/lldb/Expression/ClangExpressionVariable.h lldb/trunk/include/lldb/Expression/ClangPersistentVariables.h lldb/trunk/include/lldb/Expression/ClangUserExpression.h lldb/trunk/include/lldb/Expression/IRDynamicChecks.h lldb/trunk/include/lldb/Expression/IRForTarget.h lldb/trunk/include/lldb/Expression/IRToDWARF.h lldb/trunk/source/Core/ConstString.cpp lldb/trunk/source/Expression/ASTResultSynthesizer.cpp lldb/trunk/source/Expression/ClangASTSource.cpp lldb/trunk/source/Expression/ClangExpressionDeclMap.cpp lldb/trunk/source/Expression/ClangExpressionParser.cpp lldb/trunk/source/Expression/ClangExpressionVariable.cpp lldb/trunk/source/Expression/ClangFunction.cpp lldb/trunk/source/Expression/ClangPersistentVariables.cpp lldb/trunk/source/Expression/ClangUserExpression.cpp lldb/trunk/source/Expression/IRDynamicChecks.cpp lldb/trunk/source/Expression/IRForTarget.cpp Modified: lldb/trunk/include/lldb/Core/ConstString.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/Core/ConstString.h?rev=116634&r1=116633&r2=116634&view=diff ============================================================================== --- lldb/trunk/include/lldb/Core/ConstString.h (original) +++ lldb/trunk/include/lldb/Core/ConstString.h Fri Oct 15 17:48:33 2010 @@ -122,7 +122,7 @@ }; //------------------------------------------------------------------ - /// Convert to pointer operator. + /// Convert to bool operator. /// /// This allows code to check a ConstString object to see if it /// contains a valid string using code such as: @@ -137,8 +137,10 @@ /// A pointer to this object if the string isn't empty, NULL /// otherwise. //------------------------------------------------------------------ - operator void*() const; - + operator bool() const + { + return m_string && m_string[0]; + } //------------------------------------------------------------------ /// Assignment operator @@ -157,7 +159,11 @@ /// A const reference to this object. //------------------------------------------------------------------ const ConstString& - operator = (const ConstString& rhs); + operator = (const ConstString& rhs) + { + m_string = rhs.m_string; + return *this; + } //------------------------------------------------------------------ /// Equal to operator @@ -175,7 +181,12 @@ /// @li \b false if this object is not equal to \a rhs. //------------------------------------------------------------------ bool - operator == (const ConstString& rhs) const; + operator == (const ConstString& rhs) const + { + // We can do a pointer compare to compare these strings since they + // must come from the same pool in order to be equal. + return m_string == rhs.m_string; + } //------------------------------------------------------------------ /// Not equal to operator @@ -193,7 +204,10 @@ /// @li \b false if this object is equal to \a rhs. //------------------------------------------------------------------ bool - operator != (const ConstString& rhs) const; + operator != (const ConstString& rhs) const + { + return m_string != rhs.m_string; + } bool operator < (const ConstString& rhs) const; @@ -211,11 +225,19 @@ /// the C string value contained in this object. //------------------------------------------------------------------ const char * - AsCString(const char *value_if_empty = NULL) const; - + AsCString(const char *value_if_empty = NULL) const + { + if (m_string == NULL) + return value_if_empty; + return m_string; + } const char * - GetCString () const; + GetCString () const + { + return m_string; + } + size_t GetLength () const; @@ -230,7 +252,10 @@ /// count reaches zero. //------------------------------------------------------------------ void - Clear (); + Clear () + { + m_string = NULL; + } //------------------------------------------------------------------ /// Compare two string objects. Modified: lldb/trunk/include/lldb/Expression/ASTResultSynthesizer.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/Expression/ASTResultSynthesizer.h?rev=116634&r1=116633&r2=116634&view=diff ============================================================================== --- lldb/trunk/include/lldb/Expression/ASTResultSynthesizer.h (original) +++ lldb/trunk/include/lldb/Expression/ASTResultSynthesizer.h Fri Oct 15 17:48:33 2010 @@ -22,7 +22,7 @@ /// Users expect the expression "i + 3" to return a result, even if a result /// variable wasn't specifically declared. To fulfil this requirement, LLDB adds /// a result variable to the expression, transforming it to -/// "int ___clang_expr_result = i + 3." The IR transformers ensure that the +/// "int $__lldb_expr_result = i + 3." The IR transformers ensure that the /// resulting variable is mapped to the right piece of memory. /// ASTResultSynthesizer's job is to add the variable and its initialization to /// the ASTs for the expression, and it does so by acting as a SemaConsumer for @@ -57,7 +57,7 @@ void Initialize(clang::ASTContext &Context); //---------------------------------------------------------------------- - /// Examine a list of Decls to find the function ___clang_expr and + /// Examine a list of Decls to find the function $__lldb_expr and /// transform its code /// /// @param[in] D @@ -107,7 +107,7 @@ void ForgetSema(); private: //---------------------------------------------------------------------- - /// Hunt the given Decl for FunctionDecls named ___clang_expr, recursing + /// Hunt the given Decl for FunctionDecls named $__lldb_expr, recursing /// as necessary through LinkageSpecDecls, and calling SynthesizeResult on /// anything that was found /// Modified: lldb/trunk/include/lldb/Expression/ASTStructExtractor.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/Expression/ASTStructExtractor.h?rev=116634&r1=116633&r2=116634&view=diff ============================================================================== --- lldb/trunk/include/lldb/Expression/ASTStructExtractor.h (original) +++ lldb/trunk/include/lldb/Expression/ASTStructExtractor.h Fri Oct 15 17:48:33 2010 @@ -71,7 +71,7 @@ void Initialize(clang::ASTContext &Context); //---------------------------------------------------------------------- - /// Examine a list of Decls to find the function ___clang_expr and + /// Examine a list of Decls to find the function $__lldb_expr and /// transform its code /// /// @param[in] D Modified: lldb/trunk/include/lldb/Expression/ClangASTSource.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/Expression/ClangASTSource.h?rev=116634&r1=116633&r2=116634&view=diff ============================================================================== --- lldb/trunk/include/lldb/Expression/ClangASTSource.h (original) +++ lldb/trunk/include/lldb/Expression/ClangASTSource.h Fri Oct 15 17:48:33 2010 @@ -29,8 +29,8 @@ /// the actual lookups. //---------------------------------------------------------------------- class ClangASTSource : public clang::ExternalSemaSource { - clang::ASTContext &Context; ///< The parser's AST context, for copying types into - ClangExpressionDeclMap &DeclMap; ///< The object that looks up named entities in LLDB + clang::ASTContext &m_ast_context; ///< The parser's AST context, for copying types into + ClangExpressionDeclMap &m_decl_map; ///< The object that looks up named entities in LLDB public: friend struct NameSearchContext; @@ -46,9 +46,11 @@ /// A reference to the LLDB object that handles entity lookup. //------------------------------------------------------------------ ClangASTSource(clang::ASTContext &context, - ClangExpressionDeclMap &declMap) : - Context(context), - DeclMap(declMap) {} + ClangExpressionDeclMap &decl_map) : + m_ast_context(context), + m_decl_map(decl_map) + { + } //------------------------------------------------------------------ /// Destructor @@ -123,10 +125,10 @@ /// Decls given appropriate type information. //---------------------------------------------------------------------- struct NameSearchContext { - ClangASTSource &ASTSource; ///< The AST source making the request - llvm::SmallVectorImpl &Decls; ///< The list of declarations already constructed - clang::DeclarationName &Name; ///< The name being looked for - const clang::DeclContext *DC; ///< The DeclContext to put declarations into + ClangASTSource &m_ast_source; ///< The AST source making the request + llvm::SmallVectorImpl &m_decls; ///< The list of declarations already constructed + const clang::DeclarationName &m_decl_name; ///< The name being looked for + const clang::DeclContext *m_decl_context; ///< The DeclContext to put declarations into //------------------------------------------------------------------ /// Constructor @@ -150,10 +152,10 @@ llvm::SmallVectorImpl &decls, clang::DeclarationName &name, const clang::DeclContext *dc) : - ASTSource(astSource), - Decls(decls), - Name(name), - DC(dc) {} + m_ast_source(astSource), + m_decls(decls), + m_decl_name(name), + m_decl_context(dc) {} //------------------------------------------------------------------ /// Return the AST context for the current search. Useful when copying Modified: lldb/trunk/include/lldb/Expression/ClangExpressionDeclMap.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/Expression/ClangExpressionDeclMap.h?rev=116634&r1=116633&r2=116634&view=diff ============================================================================== --- lldb/trunk/include/lldb/Expression/ClangExpressionDeclMap.h (original) +++ lldb/trunk/include/lldb/Expression/ClangExpressionDeclMap.h Fri Oct 15 17:48:33 2010 @@ -24,6 +24,8 @@ #include "lldb/Core/Value.h" #include "lldb/Expression/ClangExpressionVariable.h" #include "lldb/Symbol/TaggedASTType.h" +#include "lldb/Symbol/SymbolContext.h" +#include "lldb/Target/ExecutionContext.h" namespace llvm { class Type; @@ -88,7 +90,8 @@ /// @param[in] name /// The std::string to place the name into. //------------------------------------------------------------------ - void GetPersistentResultName (std::string &name); + const ConstString & + GetPersistentResultName (); //------------------------------------------------------------------ /// [Used by IRForTarget] Add a variable to the list of persistent @@ -108,7 +111,7 @@ /// True on success; false otherwise. //------------------------------------------------------------------ bool AddPersistentVariable (const clang::NamedDecl *decl, - const char *name, + const ConstString &name, TypeFromParser type); //------------------------------------------------------------------ @@ -134,7 +137,7 @@ /// True on success; false otherwise. //------------------------------------------------------------------ bool AddValueToStruct (const clang::NamedDecl *decl, - const char *name, + const ConstString &name, llvm::Value *value, size_t size, off_t alignment); @@ -175,7 +178,7 @@ /// @param[out] decl /// The parsed Decl for the field, as generated by ClangASTSource /// on ClangExpressionDeclMap's behalf. In the case of the result - /// value, this will have the name ___clang_result even if the + /// value, this will have the name $__lldb_result even if the /// result value ends up having the name $1. This is an /// implementation detail of IRForTarget. /// @@ -202,7 +205,7 @@ bool GetStructElement (const clang::NamedDecl *&decl, llvm::Value *&value, off_t &offset, - const char *&name, + ConstString &name, uint32_t index); //------------------------------------------------------------------ @@ -242,7 +245,7 @@ /// @return /// True if the address could be retrieved; false otherwise. //------------------------------------------------------------------ - bool GetFunctionAddress (const char *name, + bool GetFunctionAddress (const ConstString &name, uint64_t &ptr); //------------------------------------------------------------------ @@ -348,20 +351,34 @@ /// True on success; false otherwise. //------------------------------------------------------------------ void GetDecls (NameSearchContext &context, - const char *name); + const ConstString &name); + + bool + GetLookupsEnabled () + { + return m_enable_lookups; + } + + void + SetLookupsEnabled (bool b) + { + m_enable_lookups = b; + } + private: ClangExpressionVariableStore m_found_entities; ///< All entities that were looked up for the parser. ClangExpressionVariableList m_struct_members; ///< All entities that need to be placed in the struct. - ExecutionContext *m_exe_ctx; ///< The execution context where this expression was first defined. It determines types for all the external variables, even if the expression is re-used. - SymbolContext *m_sym_ctx; ///< [owned by ClangExpressionDeclMap] The symbol context where this expression was first defined. + ExecutionContext m_exe_ctx; ///< The execution context where this expression was first defined. It determines types for all the external variables, even if the expression is re-used. + SymbolContext m_sym_ctx; ///< [owned by ClangExpressionDeclMap] The symbol context where this expression was first defined. ClangPersistentVariables *m_persistent_vars; ///< The list of persistent variables to use when resolving symbols in the expression and when creating new ones (like the result). off_t m_struct_alignment; ///< The alignment of the struct in bytes. size_t m_struct_size; ///< The size of the struct in bytes. bool m_struct_laid_out; ///< True if the struct has been laid out and the layout is valid (that is, no new fields have been added since). + bool m_enable_lookups; ///< Set to true during expression evaluation if we have found the first "$__lldb" name. lldb::addr_t m_allocated_area; ///< The base of the memory allocated for the struct. Starts on a potentially unaligned address and may therefore be larger than the struct. lldb::addr_t m_materialized_location; ///< The address at which the struct is placed. Falls inside the allocated area. - std::string m_result_name; ///< The name of the result variable ($1, for example) + 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. @@ -395,7 +412,7 @@ /// The LLDB Variable found, or NULL if none was found. //------------------------------------------------------------------ Variable *FindVariableInScope(StackFrame &frame, - const char *name, + const ConstString &name, TypeFromUser *type = NULL); //------------------------------------------------------------------ @@ -487,7 +504,7 @@ /// The type that needs to be created. /// /// @param[in] add_method - /// True if a method with signature void ___clang_expr(void*) + /// True if a method with signature void $__lldb_expr(void*) /// should be added to the C++ class type passed in //------------------------------------------------------------------ void AddOneType(NameSearchContext &context, @@ -549,7 +566,7 @@ //------------------------------------------------------------------ bool DoMaterializeOnePersistentVariable(bool dematerialize, ExecutionContext &exe_ctx, - const char *name, + const ConstString &name, lldb::addr_t addr, Error &err); @@ -586,7 +603,7 @@ bool DoMaterializeOneVariable(bool dematerialize, ExecutionContext &exe_ctx, const SymbolContext &sym_ctx, - const char *name, + const ConstString &name, TypeFromUser type, lldb::addr_t addr, Error &err); Modified: lldb/trunk/include/lldb/Expression/ClangExpressionVariable.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/Expression/ClangExpressionVariable.h?rev=116634&r1=116633&r2=116634&view=diff ============================================================================== --- lldb/trunk/include/lldb/Expression/ClangExpressionVariable.h (original) +++ lldb/trunk/include/lldb/Expression/ClangExpressionVariable.h Fri Oct 15 17:48:33 2010 @@ -21,6 +21,7 @@ // Other libraries and framework includes // Project includes #include "lldb/Core/ClangForward.h" +#include "lldb/Core/ConstString.h" #include "lldb/Symbol/TaggedASTType.h" namespace llvm { @@ -88,7 +89,7 @@ //---------------------------------------------------------------------- /// The following values should stay valid for the life of the variable //---------------------------------------------------------------------- - std::string m_name; ///< The name of the variable + ConstString m_name; ///< The name of the variable TypeFromUser m_user_type; ///< The type of the variable according to some LLDB context; ///< NULL if the type hasn't yet been migrated to one @@ -231,12 +232,12 @@ /// @return /// The variable requested, or NULL if that variable is not in the list. //---------------------------------------------------------------------- - ClangExpressionVariable *GetVariable (const char *name) + ClangExpressionVariable *GetVariable (const ConstString &name) { for (uint64_t index = 0, size = Size(); index < size; ++index) { ClangExpressionVariable &candidate (VariableAtIndex(index)); - if (!candidate.m_name.compare(name)) + if (candidate.m_name == name) return &candidate; } return NULL; Modified: lldb/trunk/include/lldb/Expression/ClangPersistentVariables.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/Expression/ClangPersistentVariables.h?rev=116634&r1=116633&r2=116634&view=diff ============================================================================== --- lldb/trunk/include/lldb/Expression/ClangPersistentVariables.h (original) +++ lldb/trunk/include/lldb/Expression/ClangPersistentVariables.h Fri Oct 15 17:48:33 2010 @@ -33,17 +33,19 @@ /// @param[in] name /// A string to place the variable name in. //---------------------------------------------------------------------- - void GetNextResultName (std::string &name); + void + GetNextResultName (ConstString &name); //---------------------------------------------------------------------- /// Constructor //---------------------------------------------------------------------- ClangPersistentVariables (); - bool CreatePersistentVariable(const char *name, - TypeFromUser user_type); + bool + CreatePersistentVariable (const ConstString &name, + TypeFromUser user_type); private: - uint64_t m_result_counter; ///< The counter used by GetNextResultName(). + uint64_t m_result_counter; ///< The counter used by GetNextResultName(). }; } Modified: lldb/trunk/include/lldb/Expression/ClangUserExpression.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/Expression/ClangUserExpression.h?rev=116634&r1=116633&r2=116634&view=diff ============================================================================== --- lldb/trunk/include/lldb/Expression/ClangUserExpression.h (original) +++ lldb/trunk/include/lldb/Expression/ClangUserExpression.h Fri Oct 15 17:48:33 2010 @@ -128,7 +128,7 @@ const char * FunctionName () { - return "___clang_expr"; + return "$__lldb_expr"; } //------------------------------------------------------------------ Modified: lldb/trunk/include/lldb/Expression/IRDynamicChecks.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/Expression/IRDynamicChecks.h?rev=116634&r1=116633&r2=116634&view=diff ============================================================================== --- lldb/trunk/include/lldb/Expression/IRDynamicChecks.h (original) +++ lldb/trunk/include/lldb/Expression/IRDynamicChecks.h Fri Oct 15 17:48:33 2010 @@ -105,8 +105,8 @@ /// The mapping used to look up entities in the target process. In /// this case, used to find objc_msgSend //------------------------------------------------------------------ - IRDynamicChecks(DynamicCheckerFunctions &checker_functions, - const char* func_name = "___clang_expr"); + IRDynamicChecks (DynamicCheckerFunctions &checker_functions, + const char* func_name = "$__lldb_expr"); //------------------------------------------------------------------ /// Destructor @@ -118,7 +118,7 @@ /// /// @param[in] M /// The module to run on. This module is searched for the function - /// ___clang_expr, and that function is passed to the passes one by + /// $__lldb_expr, and that function is passed to the passes one by /// one. /// /// @return Modified: lldb/trunk/include/lldb/Expression/IRForTarget.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/Expression/IRForTarget.h?rev=116634&r1=116633&r2=116634&view=diff ============================================================================== --- lldb/trunk/include/lldb/Expression/IRForTarget.h (original) +++ lldb/trunk/include/lldb/Expression/IRForTarget.h Fri Oct 15 17:48:33 2010 @@ -61,7 +61,7 @@ //------------------------------------------------------------------ IRForTarget(lldb_private::ClangExpressionDeclMap *decl_map, bool resolve_vars, - const char* func_name = "___clang_expr"); + const char* func_name = "$__lldb_expr"); //------------------------------------------------------------------ /// Destructor @@ -73,7 +73,7 @@ /// /// @param[in] M /// The module to run on. This module is searched for the function - /// ___clang_expr, and that function is passed to the passes one by + /// $__lldb_expr, and that function is passed to the passes one by /// one. /// /// @return @@ -94,7 +94,7 @@ private: //------------------------------------------------------------------ /// A function-level pass to take the generated global value - /// ___clang_expr_result and make it into a persistent variable. + /// $__lldb_expr_result and make it into a persistent variable. /// Also see ASTResultSynthesizer. //------------------------------------------------------------------ Modified: lldb/trunk/include/lldb/Expression/IRToDWARF.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/Expression/IRToDWARF.h?rev=116634&r1=116633&r2=116634&view=diff ============================================================================== --- lldb/trunk/include/lldb/Expression/IRToDWARF.h (original) +++ lldb/trunk/include/lldb/Expression/IRToDWARF.h Fri Oct 15 17:48:33 2010 @@ -67,7 +67,7 @@ IRToDWARF(lldb_private::ClangExpressionVariableStore &local_vars, lldb_private::ClangExpressionDeclMap *decl_map, lldb_private::StreamString &strm, - const char* func_name = "___clang_expr"); + const char* func_name = "$__lldb_expr"); //------------------------------------------------------------------ /// Destructor @@ -79,7 +79,7 @@ /// /// @param[in] M /// The module to run on. This module is searched for the function - /// ___clang_expr, and that function is converted to a location + /// $__lldb_expr, and that function is converted to a location /// expression. /// /// @return Modified: lldb/trunk/source/Core/ConstString.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Core/ConstString.cpp?rev=116634&r1=116633&r2=116634&view=diff ============================================================================== --- lldb/trunk/source/Core/ConstString.cpp (original) +++ lldb/trunk/source/Core/ConstString.cpp Fri Oct 15 17:48:33 2010 @@ -213,58 +213,6 @@ { } -//---------------------------------------------------------------------- -// Convert to pointer operator. This allows code to check any -// ConstString objects to see if they contain anything (not empty) -// valid using code such as: -// -// ConstString str(...); -// if (str) -// { ... -//---------------------------------------------------------------------- -ConstString::operator void*() const -{ - return IsEmpty() ? NULL : const_cast(this); -} - -//---------------------------------------------------------------------- -// Assignment operator -// -// Assigns the string in this object with the value from "rhs" -// and increments the reference count of that string. -// -// The previously contained string will be get its reference count -// decremented and removed from the string pool if its reference -// count reaches zero. -//---------------------------------------------------------------------- -const ConstString& -ConstString::operator=(const ConstString& rhs) -{ - m_string = rhs.m_string; - return *this; -} - -//---------------------------------------------------------------------- -// Equal to operator -// -// Returns true if this string is equal to that in "rhs". This is -// very fast as it results in a pointer comparison since all strings -// are in a uniqued and reference counted string pool. -//------------------------------------------------------------------ -bool -ConstString::operator == (const ConstString& rhs) const -{ - // We can do a pointer compare to compare these strings since they - // must come from the same pool in order to be equal. - return m_string == rhs.m_string; -} - -bool -ConstString::operator != (const ConstString& rhs) const -{ - return m_string != rhs.m_string; -} - bool ConstString::operator < (const ConstString& rhs) const { @@ -295,45 +243,12 @@ return s; } -//---------------------------------------------------------------------- -// Get the value of the contained string as a NULL terminated C -// string value. Return "fail_value" if the string is empty. -//---------------------------------------------------------------------- -const char * -ConstString::AsCString(const char *fail_value) const -{ - if (m_string == NULL) - return fail_value; - return m_string; -} - -const char * -ConstString::GetCString () const -{ - return m_string; -} - size_t ConstString::GetLength () const { return StringPool().GetConstCStringLength (m_string); } - -//---------------------------------------------------------------------- -// Clear any contained string and reset the value to the an empty -// string value. -// -// The previously contained string will be get its reference count -// decremented and removed from the string pool if its reference -// count reaches zero. -//---------------------------------------------------------------------- -void -ConstString::Clear () -{ - m_string = NULL; -} - //---------------------------------------------------------------------- // Compare two string objects. // Modified: lldb/trunk/source/Expression/ASTResultSynthesizer.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Expression/ASTResultSynthesizer.cpp?rev=116634&r1=116633&r2=116634&view=diff ============================================================================== --- lldb/trunk/source/Expression/ASTResultSynthesizer.cpp (original) +++ lldb/trunk/source/Expression/ASTResultSynthesizer.cpp Fri Oct 15 17:48:33 2010 @@ -70,7 +70,7 @@ if (m_ast_context && function_decl && - !function_decl->getNameInfo().getAsString().compare("___clang_expr")) + !function_decl->getNameInfo().getAsString().compare("$__lldb_expr")) { SynthesizeResult(function_decl); } @@ -164,7 +164,7 @@ log->Printf("Last statement's type: %s", s.c_str()); } - IdentifierInfo &result_id = Ctx.Idents.get("___clang_expr_result"); + IdentifierInfo &result_id = Ctx.Idents.get("$__lldb_expr_result"); clang::VarDecl *result_decl = VarDecl::Create(Ctx, function_decl, Modified: lldb/trunk/source/Expression/ClangASTSource.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Expression/ClangASTSource.cpp?rev=116634&r1=116633&r2=116634&view=diff ============================================================================== --- lldb/trunk/source/Expression/ClangASTSource.cpp (original) +++ lldb/trunk/source/Expression/ClangASTSource.cpp Fri Oct 15 17:48:33 2010 @@ -21,8 +21,8 @@ void ClangASTSource::StartTranslationUnit(ASTConsumer *Consumer) { // Tell Sema to ask us when looking into the translation unit's decl. - Context.getTranslationUnitDecl()->setHasExternalVisibleStorage(); - Context.getTranslationUnitDecl()->setHasExternalLexicalStorage(); + m_ast_context.getTranslationUnitDecl()->setHasExternalVisibleStorage(); + m_ast_context.getTranslationUnitDecl()->setHasExternalLexicalStorage(); } // These are only required for AST source that want to lazily load @@ -41,13 +41,15 @@ DeclContext::lookup_result ClangASTSource::FindExternalVisibleDeclsByName ( const DeclContext *decl_ctx, - DeclarationName decl_name + DeclarationName clang_decl_name ) { - switch (decl_name.getNameKind()) { + switch (clang_decl_name.getNameKind()) { // Normal identifiers. case DeclarationName::Identifier: - break; + if (clang_decl_name.getAsIdentifierInfo()->getBuiltinID() != 0) + return SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name); + break; // Operator names. Not important for now. case DeclarationName::CXXOperatorName: @@ -57,7 +59,7 @@ // Using directives found in this context. // Tell Sema we didn't find any or we'll end up getting asked a *lot*. case DeclarationName::CXXUsingDirective: - return SetNoExternalVisibleDeclsForName(decl_ctx, decl_name); + return SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name); // These aren't looked up like this. case DeclarationName::ObjCZeroArgSelector: @@ -72,33 +74,28 @@ return DeclContext::lookup_result(); } - - std::string name (decl_name.getAsString()); - if (0 == name.compare ("__va_list_tag") || - 0 == name.compare ("__int128_t") || - 0 == name.compare ("__uint128_t") || - 0 == name.compare ("SEL") || - 0 == name.compare ("id") || - 0 == name.compare ("Class") || - 0 == name.compare ("nil") || - 0 == name.compare ("gp_offset") || - 0 == name.compare ("fp_offset") || - 0 == name.compare ("overflow_arg_area") || - 0 == name.compare ("reg_save_area") || - 0 == name.find ("__builtin") ) - { - Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS); - if (log) - log->Printf("Ignoring built-in in find external declarations for name: '%s'", name.c_str()); + std::string decl_name (clang_decl_name.getAsString()); - return SetNoExternalVisibleDeclsForName(decl_ctx, decl_name); + if (!m_decl_map.GetLookupsEnabled()) + { + // Wait until we see a '$' at the start of a name before we start doing + // any lookups so we can avoid lookup up all of the builtin types. + if (!decl_name.empty() && decl_name[0] == '$') + { + m_decl_map.SetLookupsEnabled (true); + } + else + { + return SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name); + } } + + llvm::SmallVector name_decls; - llvm::SmallVector Decls; - - NameSearchContext NSC(*this, Decls, decl_name, decl_ctx); - DeclMap.GetDecls(NSC, name.c_str()); - return SetExternalVisibleDeclsForName(decl_ctx, decl_name, Decls); + NameSearchContext name_search_context(*this, name_decls, clang_decl_name, decl_ctx); + ConstString const_decl_name(decl_name.c_str()); + m_decl_map.GetDecls(name_search_context, const_decl_name); + return SetExternalVisibleDeclsForName (decl_ctx, clang_decl_name, name_decls); } void ClangASTSource::MaterializeVisibleDecls(const DeclContext *DC) @@ -114,103 +111,101 @@ } clang::ASTContext *NameSearchContext::GetASTContext() { - return &ASTSource.Context; + return &m_ast_source.m_ast_context; } clang::NamedDecl *NameSearchContext::AddVarDecl(void *type) { - IdentifierInfo *ii = Name.getAsIdentifierInfo(); + IdentifierInfo *ii = m_decl_name.getAsIdentifierInfo(); - clang::NamedDecl *Decl = VarDecl::Create(ASTSource.Context, - const_cast(DC), + clang::NamedDecl *Decl = VarDecl::Create(m_ast_source.m_ast_context, + const_cast(m_decl_context), SourceLocation(), ii, QualType::getFromOpaquePtr(type), 0, SC_Static, SC_Static); - Decls.push_back(Decl); + m_decls.push_back(Decl); return Decl; } -clang::NamedDecl *NameSearchContext::AddFunDecl(void *type) { - clang::FunctionDecl *Decl = FunctionDecl::Create(ASTSource.Context, - const_cast(DC), - SourceLocation(), - Name.getAsIdentifierInfo(), - QualType::getFromOpaquePtr(type), - NULL, - SC_Static, - SC_Static, - false, - true); +clang::NamedDecl *NameSearchContext::AddFunDecl (void *type) { + clang::FunctionDecl *func_decl = FunctionDecl::Create (m_ast_source.m_ast_context, + const_cast(m_decl_context), + SourceLocation(), + m_decl_name.getAsIdentifierInfo(), + QualType::getFromOpaquePtr(type), + NULL, + SC_Static, + SC_Static, + false, + true); // We have to do more than just synthesize the FunctionDecl. We have to // synthesize ParmVarDecls for all of the FunctionDecl's arguments. To do // this, we raid the function's FunctionProtoType for types. - QualType QT = QualType::getFromOpaquePtr(type); - clang::Type *T = QT.getTypePtr(); - const FunctionProtoType *FPT = T->getAs(); + QualType qual_type (QualType::getFromOpaquePtr(type)); + const FunctionProtoType *func_proto_type = qual_type->getAs(); - if (FPT) + if (func_proto_type) { - unsigned NumArgs = FPT->getNumArgs(); + unsigned NumArgs = func_proto_type->getNumArgs(); unsigned ArgIndex; - ParmVarDecl **ParmVarDecls = new ParmVarDecl*[NumArgs]; + ParmVarDecl **param_var_decls = new ParmVarDecl*[NumArgs]; for (ArgIndex = 0; ArgIndex < NumArgs; ++ArgIndex) { - QualType ArgQT = FPT->getArgType(ArgIndex); + QualType arg_qual_type (func_proto_type->getArgType(ArgIndex)); - ParmVarDecls[ArgIndex] = ParmVarDecl::Create(ASTSource.Context, - const_cast(DC), - SourceLocation(), - NULL, - ArgQT, - NULL, - SC_Static, - SC_Static, - NULL); + param_var_decls[ArgIndex] = ParmVarDecl::Create (m_ast_source.m_ast_context, + const_cast(m_decl_context), + SourceLocation(), + NULL, + arg_qual_type, + NULL, + SC_Static, + SC_Static, + NULL); } - Decl->setParams(ParmVarDecls, NumArgs); + func_decl->setParams(param_var_decls, NumArgs); - delete [] ParmVarDecls; + delete [] param_var_decls; } - Decls.push_back(Decl); + m_decls.push_back(func_decl); - return Decl; + return func_decl; } clang::NamedDecl *NameSearchContext::AddGenericFunDecl() { - QualType generic_function_type(ASTSource.Context.getFunctionType(ASTSource.Context.getSizeType(), // result - NULL, // argument types - 0, // number of arguments - true, // variadic? - 0, // type qualifiers - false, // has exception specification? - false, // has any exception specification? - 0, // number of exceptions - NULL, // exceptions - FunctionType::ExtInfo())); // defaults for noreturn, regparm, calling convention - + QualType generic_function_type(m_ast_source.m_ast_context.getFunctionType (m_ast_source.m_ast_context.getSizeType(), // result + NULL, // argument types + 0, // number of arguments + true, // variadic? + 0, // type qualifiers + false, // has exception specification? + false, // has any exception specification? + 0, // number of exceptions + NULL, // exceptions + FunctionType::ExtInfo())); // defaults for noreturn, regparm, calling convention + return AddFunDecl(generic_function_type.getAsOpaquePtr()); } clang::NamedDecl *NameSearchContext::AddTypeDecl(void *type) { - QualType QT = QualType::getFromOpaquePtr(type); - clang::Type *T = QT.getTypePtr(); + QualType qual_type = QualType::getFromOpaquePtr(type); - if (TagType *tag_type = dyn_cast(T)) + if (TagType *tag_type = dyn_cast(qual_type)) { TagDecl *tag_decl = tag_type->getDecl(); - Decls.push_back(tag_decl); + m_decls.push_back(tag_decl); return tag_decl; } Modified: lldb/trunk/source/Expression/ClangExpressionDeclMap.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Expression/ClangExpressionDeclMap.cpp?rev=116634&r1=116633&r2=116634&view=diff ============================================================================== --- lldb/trunk/source/Expression/ClangExpressionDeclMap.cpp (original) +++ lldb/trunk/source/Expression/ClangExpressionDeclMap.cpp Fri Oct 15 17:48:33 2010 @@ -39,17 +39,30 @@ using namespace lldb_private; using namespace clang; -ClangExpressionDeclMap::ClangExpressionDeclMap(ExecutionContext *exe_ctx) : - m_exe_ctx(exe_ctx), m_struct_laid_out(false), - m_materialized_location(0) -{ - if (exe_ctx && exe_ctx->frame) - m_sym_ctx = new SymbolContext(exe_ctx->frame->GetSymbolContext(lldb::eSymbolContextEverything)); - else - m_sym_ctx = NULL; - - if (exe_ctx && exe_ctx->process) - m_persistent_vars = &exe_ctx->process->GetPersistentVariables(); +ClangExpressionDeclMap::ClangExpressionDeclMap (ExecutionContext *exe_ctx) : + m_found_entities (), + m_struct_members (), + m_exe_ctx (), + m_sym_ctx (), + m_persistent_vars (NULL), + m_struct_alignment (0), + m_struct_size (0), + m_struct_laid_out (false), + m_enable_lookups (false), + m_allocated_area (0), + m_materialized_location (0), + m_result_name (), + m_object_pointer_type (), + m_lookedup_types () +{ + if (exe_ctx) + { + m_exe_ctx = *exe_ctx; + if (exe_ctx->frame) + m_sym_ctx = exe_ctx->frame->GetSymbolContext(lldb::eSymbolContextEverything); + if (exe_ctx->process) + m_persistent_vars = &exe_ctx->process->GetPersistentVariables(); + } } ClangExpressionDeclMap::~ClangExpressionDeclMap() @@ -76,30 +89,30 @@ if (m_materialized_location) { - m_exe_ctx->process->DeallocateMemory(m_materialized_location); + m_exe_ctx.process->DeallocateMemory(m_materialized_location); m_materialized_location = 0; } - - if (m_sym_ctx) - delete m_sym_ctx; } // Interface for IRForTarget -void -ClangExpressionDeclMap::GetPersistentResultName (std::string &name) +const ConstString & +ClangExpressionDeclMap::GetPersistentResultName () { - m_persistent_vars->GetNextResultName(m_result_name); - - name = m_result_name; + if (!m_result_name) + m_persistent_vars->GetNextResultName(m_result_name); + return m_result_name; } bool -ClangExpressionDeclMap::AddPersistentVariable (const clang::NamedDecl *decl, - const char *name, - TypeFromParser parser_type) +ClangExpressionDeclMap::AddPersistentVariable +( + const clang::NamedDecl *decl, + const ConstString &name, + TypeFromParser parser_type +) { - clang::ASTContext *context(m_exe_ctx->target->GetScratchClangASTContext()->getASTContext()); + clang::ASTContext *context(m_exe_ctx.target->GetScratchClangASTContext()->getASTContext()); TypeFromUser user_type(ClangASTContext::CopyType(context, parser_type.GetASTContext(), @@ -123,11 +136,14 @@ } bool -ClangExpressionDeclMap::AddValueToStruct (const clang::NamedDecl *decl, - const char *name, - llvm::Value *value, - size_t size, - off_t alignment) +ClangExpressionDeclMap::AddValueToStruct +( + const clang::NamedDecl *decl, + const ConstString &name, + llvm::Value *value, + size_t size, + off_t alignment +) { Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS); @@ -147,8 +163,8 @@ if (log) log->Printf("Adding value for decl %p [%s - %s] to the structure", decl, - name, - var->m_name.c_str()); + name.GetCString(), + var->m_name.GetCString()); // We know entity->m_parser_vars is valid because we used a parser variable // to find it @@ -199,9 +215,12 @@ return true; } -bool ClangExpressionDeclMap::GetStructInfo (uint32_t &num_elements, - size_t &size, - off_t &alignment) +bool ClangExpressionDeclMap::GetStructInfo +( + uint32_t &num_elements, + size_t &size, + off_t &alignment +) { if (!m_struct_laid_out) return false; @@ -214,11 +233,14 @@ } bool -ClangExpressionDeclMap::GetStructElement (const clang::NamedDecl *&decl, - llvm::Value *&value, - off_t &offset, - const char *&name, - uint32_t index) +ClangExpressionDeclMap::GetStructElement +( + const clang::NamedDecl *&decl, + llvm::Value *&value, + off_t &offset, + ConstString &name, + uint32_t index +) { if (!m_struct_laid_out) return false; @@ -235,15 +257,18 @@ decl = member.m_parser_vars->m_named_decl; value = member.m_parser_vars->m_llvm_value; offset = member.m_jit_vars->m_offset; - name = member.m_name.c_str(); + name = member.m_name; return true; } bool -ClangExpressionDeclMap::GetFunctionInfo (const clang::NamedDecl *decl, - llvm::Value**& value, - uint64_t &ptr) +ClangExpressionDeclMap::GetFunctionInfo +( + const clang::NamedDecl *decl, + llvm::Value**& value, + uint64_t &ptr +) { ClangExpressionVariable *entity = m_found_entities.GetVariable(decl); @@ -260,17 +285,19 @@ } bool -ClangExpressionDeclMap::GetFunctionAddress (const char *name, - uint64_t &ptr) +ClangExpressionDeclMap::GetFunctionAddress +( + const ConstString &name, + uint64_t &ptr +) { // Back out in all cases where we're not fully initialized - if (!m_exe_ctx || !m_exe_ctx->frame || !m_sym_ctx) + if (m_exe_ctx.frame == NULL) return false; - ConstString name_cs(name); SymbolContextList sym_ctxs; - m_sym_ctx->FindFunctionsByName(name_cs, false, sym_ctxs); + m_sym_ctx.FindFunctionsByName(name, false, sym_ctxs); if (!sym_ctxs.GetSize()) return false; @@ -287,7 +314,7 @@ else return false; - ptr = fun_address->GetLoadAddress(m_exe_ctx->target); + ptr = fun_address->GetLoadAddress (m_exe_ctx.target); return true; } @@ -295,9 +322,12 @@ // Interface for CommandObjectExpression bool -ClangExpressionDeclMap::Materialize (ExecutionContext *exe_ctx, - lldb::addr_t &struct_address, - Error &err) +ClangExpressionDeclMap::Materialize +( + ExecutionContext *exe_ctx, + lldb::addr_t &struct_address, + Error &err +) { bool result = DoMaterialize(false, exe_ctx, NULL, err); @@ -308,9 +338,12 @@ } bool -ClangExpressionDeclMap::GetObjectPointer(lldb::addr_t &object_ptr, - ExecutionContext *exe_ctx, - Error &err) +ClangExpressionDeclMap::GetObjectPointer +( + lldb::addr_t &object_ptr, + ExecutionContext *exe_ctx, + Error &err +) { if (!exe_ctx || !exe_ctx->frame || !exe_ctx->target || !exe_ctx->process) { @@ -324,7 +357,8 @@ return false; } - Variable *object_ptr_var = FindVariableInScope(*exe_ctx->frame, "this", &m_object_pointer_type); + static ConstString g_this_cs ("this"); + Variable *object_ptr_var = FindVariableInScope(*exe_ctx->frame, g_this_cs, &m_object_pointer_type); if (!object_ptr_var) { @@ -380,17 +414,23 @@ } bool -ClangExpressionDeclMap::Dematerialize (ExecutionContext *exe_ctx, - ClangExpressionVariable *&result, - Error &err) +ClangExpressionDeclMap::Dematerialize +( + ExecutionContext *exe_ctx, + ClangExpressionVariable *&result, + Error &err +) { return DoMaterialize(true, exe_ctx, &result, err); } bool -ClangExpressionDeclMap::DumpMaterializedStruct(ExecutionContext *exe_ctx, - Stream &s, - Error &err) +ClangExpressionDeclMap::DumpMaterializedStruct +( + ExecutionContext *exe_ctx, + Stream &s, + Error &err +) { if (!m_struct_laid_out) { @@ -434,7 +474,7 @@ { ClangExpressionVariable &member (m_struct_members.VariableAtIndex(member_index)); - s.Printf("[%s]\n", member.m_name.c_str()); + s.Printf("[%s]\n", member.m_name.GetCString()); if (!member.m_jit_vars.get()) return false; @@ -456,10 +496,13 @@ } bool -ClangExpressionDeclMap::DoMaterialize (bool dematerialize, - ExecutionContext *exe_ctx, - ClangExpressionVariable **result, - Error &err) +ClangExpressionDeclMap::DoMaterialize +( + bool dematerialize, + ExecutionContext *exe_ctx, + ClangExpressionVariable **result, + Error &err +) { Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS); @@ -529,19 +572,19 @@ return false; ClangExpressionVariable *entity = m_found_entities.GetVariable(member.m_parser_vars->m_named_decl); - ClangExpressionVariable *persistent_variable = m_persistent_vars->GetVariable(member.m_name.c_str()); + ClangExpressionVariable *persistent_variable = m_persistent_vars->GetVariable(member.m_name); if (entity) { if (!member.m_jit_vars.get()) return false; - if (!DoMaterializeOneVariable(dematerialize, *exe_ctx, sym_ctx, member.m_name.c_str(), member.m_user_type, m_materialized_location + member.m_jit_vars->m_offset, err)) + if (!DoMaterializeOneVariable(dematerialize, *exe_ctx, sym_ctx, member.m_name, member.m_user_type, m_materialized_location + member.m_jit_vars->m_offset, err)) return false; } else if (persistent_variable) { - if (!member.m_name.compare(m_result_name)) + if (member.m_name == m_result_name) { if (!dematerialize) continue; @@ -553,14 +596,14 @@ } if (log) - log->Printf("Searched for persistent variable %s and found %s", member.m_name.c_str(), persistent_variable->m_name.c_str()); + log->Printf("Searched for persistent variable %s and found %s", member.m_name.GetCString(), persistent_variable->m_name.GetCString()); - if (!DoMaterializeOnePersistentVariable(dematerialize, *exe_ctx, persistent_variable->m_name.c_str(), m_materialized_location + member.m_jit_vars->m_offset, err)) + if (!DoMaterializeOnePersistentVariable(dematerialize, *exe_ctx, persistent_variable->m_name, m_materialized_location + member.m_jit_vars->m_offset, err)) return false; } else { - err.SetErrorStringWithFormat("Unexpected variable %s", member.m_name.c_str()); + err.SetErrorStringWithFormat("Unexpected variable %s", member.m_name.GetCString()); return false; } } @@ -569,17 +612,20 @@ } bool -ClangExpressionDeclMap::DoMaterializeOnePersistentVariable(bool dematerialize, - ExecutionContext &exe_ctx, - const char *name, - lldb::addr_t addr, - Error &err) +ClangExpressionDeclMap::DoMaterializeOnePersistentVariable +( + bool dematerialize, + ExecutionContext &exe_ctx, + const ConstString &name, + lldb::addr_t addr, + Error &err +) { ClangExpressionVariable *pvar(m_persistent_vars->GetVariable(name)); if (!pvar) { - err.SetErrorStringWithFormat("Undefined persistent variable %s", name); + err.SetErrorStringWithFormat("Undefined persistent variable %s", name.GetCString()); return LLDB_INVALID_ADDRESS; } @@ -612,13 +658,16 @@ } bool -ClangExpressionDeclMap::DoMaterializeOneVariable(bool dematerialize, - ExecutionContext &exe_ctx, - const SymbolContext &sym_ctx, - const char *name, - TypeFromUser type, - lldb::addr_t addr, - Error &err) +ClangExpressionDeclMap::DoMaterializeOneVariable +( + bool dematerialize, + ExecutionContext &exe_ctx, + const SymbolContext &sym_ctx, + const ConstString &name, + TypeFromUser type, + lldb::addr_t addr, + Error &err +) { Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS); @@ -629,12 +678,12 @@ if (!var) { - err.SetErrorStringWithFormat("Couldn't find %s with appropriate type", name); + err.SetErrorStringWithFormat("Couldn't find %s with appropriate type", name.GetCString()); return false; } if (log) - log->Printf("%s %s with type %p", (dematerialize ? "Dematerializing" : "Materializing"), name, type.GetOpaqueQualType()); + log->Printf("%s %s with type %p", (dematerialize ? "Dematerializing" : "Materializing"), name.GetCString(), type.GetOpaqueQualType()); std::auto_ptr location_value(GetVariableValue(exe_ctx, var, @@ -642,7 +691,7 @@ if (!location_value.get()) { - err.SetErrorStringWithFormat("Couldn't get value for %s", name); + err.SetErrorStringWithFormat("Couldn't get value for %s", name.GetCString()); return false; } @@ -661,7 +710,7 @@ location_value->Dump(&ss); - err.SetErrorStringWithFormat("%s has a value of unhandled type: %s", name, ss.GetString().c_str()); + err.SetErrorStringWithFormat("%s has a value of unhandled type: %s", name.GetCString(), ss.GetString().c_str()); return false; } break; @@ -689,13 +738,13 @@ Error error; if (exe_ctx.process->ReadMemory (src_addr, data.GetBytes(), addr_byte_size, error) != addr_byte_size) { - err.SetErrorStringWithFormat ("Couldn't read %s from the target: %s", name, error.AsCString()); + err.SetErrorStringWithFormat ("Couldn't read %s from the target: %s", name.GetCString(), error.AsCString()); return false; } if (exe_ctx.process->WriteMemory (dest_addr, data.GetBytes(), addr_byte_size, error) != addr_byte_size) { - err.SetErrorStringWithFormat ("Couldn't write %s to the target: %s", name, error.AsCString()); + err.SetErrorStringWithFormat ("Couldn't write %s to the target: %s", name.GetCString(), error.AsCString()); return false; } @@ -711,7 +760,7 @@ location_value->Dump(&ss); - err.SetErrorStringWithFormat("%s is a scalar of unhandled type: %s", name, ss.GetString().c_str()); + err.SetErrorStringWithFormat("%s is a scalar of unhandled type: %s", name.GetCString(), ss.GetString().c_str()); return false; } @@ -719,7 +768,7 @@ if (!register_info) { - err.SetErrorStringWithFormat("Couldn't get the register information for %s", name); + err.SetErrorStringWithFormat("Couldn't get the register information for %s", name.GetCString()); return false; } @@ -727,7 +776,7 @@ if (!register_context) { - err.SetErrorStringWithFormat("Couldn't read register context to read %s from %s", name, register_info->name); + err.SetErrorStringWithFormat("Couldn't read register context to read %s from %s", name.GetCString(), register_info->name); return false; } @@ -755,7 +804,7 @@ if (addr_byte_size > register_byte_size) { - err.SetErrorStringWithFormat("%s is too big to store in %s", name, register_info->name); + err.SetErrorStringWithFormat("%s is too big to store in %s", name.GetCString(), register_info->name); return false; } @@ -764,7 +813,7 @@ switch (exe_ctx.process->GetByteOrder()) { default: - err.SetErrorStringWithFormat("%s is stored with an unhandled byte order", name); + err.SetErrorStringWithFormat("%s is stored with an unhandled byte order", name.GetCString()); return false; case lldb::eByteOrderLittle: register_offset = 0; @@ -779,7 +828,7 @@ Error error; if (exe_ctx.process->ReadMemory (addr, register_data.GetBytes() + register_offset, addr_byte_size, error) != addr_byte_size) { - err.SetErrorStringWithFormat ("Couldn't read %s from the target: %s", name, error.AsCString()); + err.SetErrorStringWithFormat ("Couldn't read %s from the target: %s", name.GetCString(), error.AsCString()); return false; } @@ -787,7 +836,7 @@ if (!register_context->WriteRegisterBytes(register_number, register_extractor, 0)) { - err.SetErrorStringWithFormat("Couldn't read %s from %s", name, register_info->name); + err.SetErrorStringWithFormat("Couldn't read %s from %s", name.GetCString(), register_info->name); return false; } } @@ -812,7 +861,7 @@ if (addr_byte_size > register_byte_size) { - err.SetErrorStringWithFormat("%s is too big to store in %s", name, register_info->name); + err.SetErrorStringWithFormat("%s is too big to store in %s", name.GetCString(), register_info->name); return false; } @@ -821,7 +870,7 @@ switch (exe_ctx.process->GetByteOrder()) { default: - err.SetErrorStringWithFormat("%s is stored with an unhandled byte order", name); + err.SetErrorStringWithFormat("%s is stored with an unhandled byte order", name.GetCString()); return false; case lldb::eByteOrderLittle: register_offset = 0; @@ -835,7 +884,7 @@ if (!register_context->ReadRegisterBytes(register_number, register_extractor)) { - err.SetErrorStringWithFormat("Couldn't read %s from %s", name, register_info->name); + err.SetErrorStringWithFormat("Couldn't read %s from %s", name.GetCString(), register_info->name); return false; } @@ -843,7 +892,7 @@ if (!register_data) { - err.SetErrorStringWithFormat("Read but couldn't extract data for %s from %s", name, register_info->name); + err.SetErrorStringWithFormat("Read but couldn't extract data for %s from %s", name.GetCString(), register_info->name); return false; } @@ -861,20 +910,21 @@ } Variable * -ClangExpressionDeclMap::FindVariableInScope(StackFrame &frame, - const char *name, - TypeFromUser *type) +ClangExpressionDeclMap::FindVariableInScope +( + StackFrame &frame, + const ConstString &name, + TypeFromUser *type +) { Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS); - ConstString name_cs(name); - VariableList *var_list = frame.GetVariableList(true); if (!var_list) return NULL; - lldb::VariableSP var = var_list->FindVariable(name_cs); + lldb::VariableSP var = var_list->FindVariable(name); if (!var) return NULL; @@ -901,25 +951,27 @@ // Interface for ClangASTSource void -ClangExpressionDeclMap::GetDecls(NameSearchContext &context, - const char *name) +ClangExpressionDeclMap::GetDecls +( + NameSearchContext &context, + const ConstString &name +) { Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS); if (log) - log->Printf("Hunting for a definition for '%s'", name); + log->Printf("Hunting for a definition for '%s'", name.GetCString()); // Back out in all cases where we're not fully initialized - if (!m_exe_ctx || !m_exe_ctx->frame || !m_sym_ctx) + if (m_exe_ctx.frame == NULL) return; - ConstString name_cs(name); - - if (!strcmp(name, "___clang_class")) + static ConstString g_lldb_class_name ("$__lldb_class"); + if (name == g_lldb_class_name) { // Clang is looking for the type of "this" - VariableList *vars = m_exe_ctx->frame->GetVariableList(false); + VariableList *vars = m_exe_ctx.frame->GetVariableList(false); if (!vars) return; @@ -955,59 +1007,72 @@ SymbolContextList sym_ctxs; - m_sym_ctx->FindFunctionsByName(name_cs, false, sym_ctxs); - - bool found_specific = false; - Symbol *generic_symbol = NULL; - Symbol *non_extern_symbol = NULL; - - for (uint32_t index = 0, num_indices = sym_ctxs.GetSize(); - index < num_indices; - ++index) + // Only look for functions by name out in our symbols if the function + // doesn't start with our phony prefix of '$' + if (name.GetCString()[0] != '$') { - SymbolContext sym_ctx; - sym_ctxs.GetContextAtIndex(index, sym_ctx); - - if (sym_ctx.function) + + Variable *var = FindVariableInScope(*m_exe_ctx.frame, name); + + // If we found a variable in scope, no need to pull up function names + if (var != NULL) { - // TODO only do this if it's a C function; C++ functions may be - // overloaded - if (!found_specific) - AddOneFunction(context, sym_ctx.function, NULL); - found_specific = true; + AddOneVariable(context, var); } - else if (sym_ctx.symbol) + else { - if (sym_ctx.symbol->IsExternal()) - generic_symbol = sym_ctx.symbol; - else - non_extern_symbol = sym_ctx.symbol; + m_sym_ctx.FindFunctionsByName (name, false, sym_ctxs); + + bool found_specific = false; + Symbol *generic_symbol = NULL; + Symbol *non_extern_symbol = NULL; + + for (uint32_t index = 0, num_indices = sym_ctxs.GetSize(); + index < num_indices; + ++index) + { + SymbolContext sym_ctx; + sym_ctxs.GetContextAtIndex(index, sym_ctx); + + if (sym_ctx.function) + { + // TODO only do this if it's a C function; C++ functions may be + // overloaded + if (!found_specific) + AddOneFunction(context, sym_ctx.function, NULL); + found_specific = true; + } + else if (sym_ctx.symbol) + { + if (sym_ctx.symbol->IsExternal()) + generic_symbol = sym_ctx.symbol; + else + non_extern_symbol = sym_ctx.symbol; + } + } + + if (!found_specific) + { + if (generic_symbol) + AddOneFunction(context, NULL, generic_symbol); + else if (non_extern_symbol) + AddOneFunction(context, NULL, non_extern_symbol); + } } } - - if (!found_specific) + else { - if (generic_symbol) - AddOneFunction(context, NULL, generic_symbol); - else if (non_extern_symbol) - AddOneFunction(context, NULL, non_extern_symbol); - } + ClangExpressionVariable *pvar(m_persistent_vars->GetVariable(name)); - Variable *var = FindVariableInScope(*m_exe_ctx->frame, name); - - if (var) - AddOneVariable(context, var); - - ClangExpressionVariable *pvar(m_persistent_vars->GetVariable(name)); - - if (pvar) - AddOneVariable(context, pvar); + if (pvar) + AddOneVariable(context, pvar); + } // See information on gating of this operation next to the definition for // m_lookedup_types. - const char *name_uniq = name_cs.GetCString(); + const char *name_uniq = name.GetCString(); if (m_lookedup_types.find(name_uniq) == m_lookedup_types.end()) { @@ -1015,7 +1080,7 @@ m_lookedup_types.insert(std::pair(name_uniq, true)); // 2 The type is looked up and added, potentially causing more type loookups. - lldb::TypeSP type = m_sym_ctx->FindTypeByName(name_cs); + lldb::TypeSP type = m_sym_ctx.FindTypeByName (name); if (type.get()) { @@ -1028,15 +1093,17 @@ // 3 The name is removed from m_lookedup_types. m_lookedup_types.erase(name_uniq); } - } Value * -ClangExpressionDeclMap::GetVariableValue(ExecutionContext &exe_ctx, - Variable *var, - clang::ASTContext *parser_ast_context, - TypeFromUser *user_type, - TypeFromParser *parser_type) +ClangExpressionDeclMap::GetVariableValue +( + ExecutionContext &exe_ctx, + Variable *var, + clang::ASTContext *parser_ast_context, + TypeFromUser *user_type, + TypeFromParser *parser_type +) { Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS); @@ -1129,7 +1196,7 @@ Address so_addr(var_location->GetScalar().ULongLong(), object_file->GetSectionList()); - lldb::addr_t load_addr = so_addr.GetLoadAddress(m_exe_ctx->target); + lldb::addr_t load_addr = so_addr.GetLoadAddress(m_exe_ctx.target); var_location->GetScalar() = load_addr; var_location->SetValueType(Value::eValueTypeLoadAddress); @@ -1150,17 +1217,18 @@ TypeFromUser ut; TypeFromParser pt; - Value *var_location = GetVariableValue(*m_exe_ctx, - var, - context.GetASTContext(), - &ut, - &pt); + Value *var_location = GetVariableValue (m_exe_ctx, + var, + context.GetASTContext(), + &ut, + &pt); NamedDecl *var_decl = context.AddVarDecl(pt.GetOpaqueQualType()); ClangExpressionVariable &entity(m_found_entities.VariableAtIndex(m_found_entities.CreateVariable())); - entity.m_name = context.Name.getAsString(); - entity.m_user_type = ut; + std::string decl_name(context.m_decl_name.getAsString()); + entity.m_name.SetCString (decl_name.c_str()); + entity.m_user_type = ut; entity.EnableParserVars(); entity.m_parser_vars->m_parser_type = pt; @@ -1169,7 +1237,9 @@ entity.m_parser_vars->m_lldb_value = var_location; if (log) - log->Printf("Found variable %s, returned (NamedDecl)%p", context.Name.getAsString().c_str(), var_decl); + { + log->Printf("Found variable %s, returned (NamedDecl)%p", decl_name.c_str(), var_decl); + } } void @@ -1194,7 +1264,7 @@ pvar->m_parser_vars->m_lldb_value = NULL; if (log) - log->Printf("Added pvar %s, returned (NamedDecl)%p", pvar->m_name.c_str(), var_decl); + log->Printf("Added pvar %s, returned (NamedDecl)%p", pvar->m_name.GetCString(), var_decl); } void @@ -1261,12 +1331,13 @@ return; } - lldb::addr_t load_addr = fun_address->GetLoadAddress(m_exe_ctx->target); + lldb::addr_t load_addr = fun_address->GetLoadAddress(m_exe_ctx.target); fun_location->SetValueType(Value::eValueTypeLoadAddress); fun_location->GetScalar() = load_addr; ClangExpressionVariable &entity(m_found_entities.VariableAtIndex(m_found_entities.CreateVariable())); - entity.m_name = context.Name.getAsString(); + std::string decl_name(context.m_decl_name.getAsString()); + entity.m_name.SetCString(decl_name.c_str()); entity.m_user_type = TypeFromUser(fun_opaque_type, fun_ast_context);; entity.EnableParserVars(); @@ -1275,7 +1346,9 @@ entity.m_parser_vars->m_lldb_value = fun_location.release(); if (log) - log->Printf("Found %s function %s, returned (NamedDecl)%p", (fun ? "specific" : "generic"), context.Name.getAsString().c_str(), fun_decl); + { + log->Printf("Found %s function %s, returned (NamedDecl)%p", (fun ? "specific" : "generic"), decl_name.c_str(), fun_decl); + } } void @@ -1310,7 +1383,7 @@ ClangASTContext::AddMethodToCXXRecordType (parser_ast_context, copied_type, - "___clang_expr", + "$__lldb_expr", method_type, lldb::eAccessPublic, is_virtual, Modified: lldb/trunk/source/Expression/ClangExpressionParser.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Expression/ClangExpressionParser.cpp?rev=116634&r1=116633&r2=116634&view=diff ============================================================================== --- lldb/trunk/source/Expression/ClangExpressionParser.cpp (original) +++ lldb/trunk/source/Expression/ClangExpressionParser.cpp Fri Oct 15 17:48:33 2010 @@ -272,7 +272,7 @@ m_compiler->setASTContext(ast_context.release()); - std::string module_name("___clang_module"); + std::string module_name("$__lldb_module"); m_code_generator.reset(CreateLLVMCodeGen(m_compiler->getDiagnostics(), module_name, Modified: lldb/trunk/source/Expression/ClangExpressionVariable.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Expression/ClangExpressionVariable.cpp?rev=116634&r1=116633&r2=116634&view=diff ============================================================================== --- lldb/trunk/source/Expression/ClangExpressionVariable.cpp (original) +++ lldb/trunk/source/Expression/ClangExpressionVariable.cpp Fri Oct 15 17:48:33 2010 @@ -127,7 +127,7 @@ } result_sp.reset (new ValueObjectConstResult (m_user_type.GetASTContext(), m_user_type.GetOpaqueQualType(), - ConstString (m_name.c_str()), + m_name, m_data_sp,// TODO: sean can you get this to be valid? byte_order, addr_byte_size)); Modified: lldb/trunk/source/Expression/ClangFunction.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Expression/ClangFunction.cpp?rev=116634&r1=116633&r2=116634&view=diff ============================================================================== --- lldb/trunk/source/Expression/ClangFunction.cpp (original) +++ lldb/trunk/source/Expression/ClangFunction.cpp Fri Oct 15 17:48:33 2010 @@ -45,11 +45,14 @@ //---------------------------------------------------------------------- // ClangFunction constructor //---------------------------------------------------------------------- -ClangFunction::ClangFunction(const char *target_triple, - ClangASTContext *ast_context, - void *return_qualtype, - const Address& functionAddress, - const ValueList &arg_value_list) : +ClangFunction::ClangFunction +( + const char *target_triple, + ClangASTContext *ast_context, + void *return_qualtype, + const Address& functionAddress, + const ValueList &arg_value_list +) : m_target_triple (target_triple), m_function_ptr (NULL), m_function_addr (functionAddress), @@ -65,10 +68,13 @@ { } -ClangFunction::ClangFunction(const char *target_triple, - Function &function, - ClangASTContext *ast_context, - const ValueList &arg_value_list) : +ClangFunction::ClangFunction +( + const char *target_triple, + Function &function, + ClangASTContext *ast_context, + const ValueList &arg_value_list +) : m_target_triple (target_triple), m_function_ptr (&function), m_function_addr (), Modified: lldb/trunk/source/Expression/ClangPersistentVariables.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Expression/ClangPersistentVariables.cpp?rev=116634&r1=116633&r2=116634&view=diff ============================================================================== --- lldb/trunk/source/Expression/ClangPersistentVariables.cpp (original) +++ lldb/trunk/source/Expression/ClangPersistentVariables.cpp Fri Oct 15 17:48:33 2010 @@ -22,19 +22,16 @@ } void -ClangPersistentVariables::GetNextResultName (std::string &name) +ClangPersistentVariables::GetNextResultName (ConstString &name) { - StreamString s; - s.Printf("$%llu", m_result_counter); - - m_result_counter++; - - name = s.GetString(); + char result_name[256]; + ::snprintf (result_name, sizeof(result_name), "$%llu", m_result_counter++); + name.SetCString(result_name); } bool -ClangPersistentVariables::CreatePersistentVariable(const char *name, - TypeFromUser user_type) +ClangPersistentVariables::CreatePersistentVariable (const ConstString &name, + TypeFromUser user_type) { if (GetVariable(name)) return false; Modified: lldb/trunk/source/Expression/ClangUserExpression.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Expression/ClangUserExpression.cpp?rev=116634&r1=116633&r2=116634&view=diff ============================================================================== --- lldb/trunk/source/Expression/ClangUserExpression.cpp (original) +++ lldb/trunk/source/Expression/ClangUserExpression.cpp Fri Oct 15 17:48:33 2010 @@ -88,7 +88,7 @@ if (m_cplusplus) { m_transformed_stream.Printf("void \n" - "___clang_class::%s(void *___clang_arg) \n" + "$__lldb_class::%s(void *$__lldb_arg) \n" "{ \n" " %s; \n" "} \n", @@ -100,7 +100,7 @@ else { m_transformed_stream.Printf("void \n" - "%s(void *___clang_arg) \n" + "%s(void *$__lldb_arg) \n" "{ \n" " %s; \n" "} \n", Modified: lldb/trunk/source/Expression/IRDynamicChecks.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Expression/IRDynamicChecks.cpp?rev=116634&r1=116633&r2=116634&view=diff ============================================================================== --- lldb/trunk/source/Expression/IRDynamicChecks.cpp (original) +++ lldb/trunk/source/Expression/IRDynamicChecks.cpp Fri Oct 15 17:48:33 2010 @@ -26,18 +26,15 @@ static char ID; -static const char valid_pointer_check_name[] = -"___clang_valid_pointer_check"; +#define VALID_POINTER_CHECK_NAME "$__lldb_valid_pointer_check" +#define VALID_OBJC_OBJECT_CHECK_NAME "$__lldb_objc_object_check" -static const char valid_pointer_check_text[] = - "extern \"C\" void " - "___clang_valid_pointer_check (unsigned char *ptr)" - "{" - "unsigned char val = *ptr;" - "}"; - -static const char objc_object_check_name[] = - "___clang_objc_object_check"; +static const char g_valid_pointer_check_text[] = +"extern \"C\" void\n" +VALID_POINTER_CHECK_NAME " (unsigned char *ptr)\n" +"{\n" +" unsigned char val = *ptr;\n" +"}"; static bool FunctionExists(const SymbolContext &sym_ctx, const char *name) { @@ -55,14 +52,14 @@ std::string ret; if (!exe_ctx.frame) - return "extern \"C\" void ___clang_objc_object_check (unsigned char *obj) { }"; + return "extern \"C\" void $__lldb_objc_object_check (unsigned char *obj) { }"; const SymbolContext &sym_ctx(exe_ctx.frame->GetSymbolContext(lldb::eSymbolContextEverything)); if (FunctionExists(sym_ctx, "gdb_object_getClass")) { return "extern \"C\" void " - "___clang_objc_object_check(uint8_t *obj)" + "$__lldb_objc_object_check(uint8_t *obj)" "{" "" "}"; @@ -70,7 +67,7 @@ else if (FunctionExists(sym_ctx, "gdb_class_getClass")) { return "extern \"C\" void " - "___clang_objc_object_check(uint8_t *obj)" + "$__lldb_objc_object_check(uint8_t *obj)" "{" "" "}"; @@ -78,7 +75,7 @@ else { return "extern \"C\" void " - "___clang_objc_object_check(uint8_t *obj)" + "$__lldb_objc_object_check(uint8_t *obj)" "{" "" "}"; @@ -97,8 +94,8 @@ DynamicCheckerFunctions::Install(Stream &error_stream, ExecutionContext &exe_ctx) { - m_valid_pointer_check.reset(new ClangUtilityFunction(valid_pointer_check_text, - valid_pointer_check_name)); + m_valid_pointer_check.reset(new ClangUtilityFunction(g_valid_pointer_check_text, + VALID_POINTER_CHECK_NAME)); if (!m_valid_pointer_check->Install(error_stream, exe_ctx)) return false; Modified: lldb/trunk/source/Expression/IRForTarget.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Expression/IRForTarget.cpp?rev=116634&r1=116633&r2=116634&view=diff ============================================================================== --- lldb/trunk/source/Expression/IRForTarget.cpp (original) +++ lldb/trunk/source/Expression/IRForTarget.cpp Fri Oct 15 17:48:33 2010 @@ -19,6 +19,7 @@ #include "clang/AST/ASTContext.h" +#include "lldb/Core/ConstString.h" #include "lldb/Core/dwarf.h" #include "lldb/Core/Log.h" #include "lldb/Core/Scalar.h" @@ -73,8 +74,7 @@ } bool -IRForTarget::createResultVariable(llvm::Module &M, - llvm::Function &F) +IRForTarget::createResultVariable (llvm::Module &llvm_module, llvm::Function &llvm_function) { lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS); @@ -83,7 +83,7 @@ // Find the result variable. If it doesn't exist, we can give up right here. - ValueSymbolTable& value_symbol_table = M.getValueSymbolTable(); + ValueSymbolTable& value_symbol_table = llvm_module.getValueSymbolTable(); const char *result_name = NULL; @@ -91,7 +91,7 @@ vi != ve; ++vi) { - if (strstr(vi->first(), "___clang_expr_result") && + if (strstr(vi->first(), "$__lldb_expr_result") && !strstr(vi->first(), "GV")) { result_name = vi->first(); @@ -110,7 +110,7 @@ if (log) log->Printf("Result name: %s", result_name); - Value *result_value = M.getNamedValue(result_name); + Value *result_value = llvm_module.getNamedValue(result_name); if (!result_value) { @@ -134,7 +134,7 @@ // Find the metadata and follow it to the VarDecl - NamedMDNode *named_metadata = M.getNamedMetadata("clang.global.decl.ptrs"); + NamedMDNode *named_metadata = llvm_module.getNamedMetadata("clang.global.decl.ptrs"); if (!named_metadata) { @@ -180,27 +180,26 @@ lldb_private::TypeFromParser result_decl_type (result_decl->getType().getAsOpaquePtr(), &result_decl->getASTContext()); - std::string new_result_name; - - m_decl_map->GetPersistentResultName(new_result_name); - m_decl_map->AddPersistentVariable(result_decl, new_result_name.c_str(), result_decl_type); + + lldb_private::ConstString new_result_name (m_decl_map->GetPersistentResultName()); + m_decl_map->AddPersistentVariable(result_decl, new_result_name, result_decl_type); if (log) - log->Printf("Creating a new result global: %s", new_result_name.c_str()); + log->Printf("Creating a new result global: %s", new_result_name.GetCString()); // Construct a new result global and set up its metadata - GlobalVariable *new_result_global = new GlobalVariable(M, + GlobalVariable *new_result_global = new GlobalVariable(llvm_module, result_global->getType()->getElementType(), false, /* not constant */ GlobalValue::ExternalLinkage, NULL, /* no initializer */ - new_result_name.c_str()); + new_result_name.GetCString ()); // It's too late in compilation to create a new VarDecl for this, but we don't // need to. We point the metadata at the old VarDecl. This creates an odd // anomaly: a variable with a Value whose name is something like $0 and a - // Decl whose name is ___clang_expr_result. This condition is handled in + // Decl whose name is $__lldb_expr_result. This condition is handled in // ClangExpressionDeclMap::DoMaterialize, and the name of the variable is // fixed up. @@ -212,7 +211,7 @@ values[0] = new_result_global; values[1] = new_constant_int; - MDNode *persistent_global_md = MDNode::get(M.getContext(), values, 2); + MDNode *persistent_global_md = MDNode::get(llvm_module.getContext(), values, 2); named_metadata->addOperand(persistent_global_md); if (log) @@ -225,7 +224,7 @@ // We need to synthesize a store for this variable, because otherwise // there's nothing to put into its equivalent persistent variable. - BasicBlock &entry_block(F.getEntryBlock()); + BasicBlock &entry_block(llvm_function.getEntryBlock()); Instruction *first_entry_instruction(entry_block.getFirstNonPHIOrDbg()); if (!first_entry_instruction) @@ -332,7 +331,8 @@ { uint64_t srN_addr; - if (!m_decl_map->GetFunctionAddress("sel_registerName", srN_addr)) + static lldb_private::ConstString g_sel_registerName_str ("sel_registerName"); + if (!m_decl_map->GetFunctionAddress (g_sel_registerName_str, srN_addr)) return false; // Build the function type: struct objc_selector *sel_registerName(uint8_t*) @@ -418,7 +418,7 @@ bool IRForTarget::RewritePersistentAlloc(llvm::Instruction *persistent_alloc, - llvm::Module &M) + llvm::Module &llvm_module) { AllocaInst *alloc = dyn_cast(persistent_alloc); @@ -441,10 +441,12 @@ lldb_private::TypeFromParser result_decl_type (decl->getType().getAsOpaquePtr(), &decl->getASTContext()); - if (!m_decl_map->AddPersistentVariable(decl, decl->getName().str().c_str(), result_decl_type)) + StringRef decl_name (decl->getName()); + lldb_private::ConstString persistent_variable_name (decl_name.data(), decl_name.size()); + if (!m_decl_map->AddPersistentVariable(decl, persistent_variable_name, result_decl_type)) return false; - GlobalVariable *persistent_global = new GlobalVariable(M, + GlobalVariable *persistent_global = new GlobalVariable(llvm_module, alloc->getType()->getElementType(), false, /* not constant */ GlobalValue::ExternalLinkage, @@ -454,13 +456,13 @@ // What we're going to do here is make believe this was a regular old external // variable. That means we need to make the metadata valid. - NamedMDNode *named_metadata = M.getNamedMetadata("clang.global.decl.ptrs"); + NamedMDNode *named_metadata = llvm_module.getNamedMetadata("clang.global.decl.ptrs"); llvm::Value* values[2]; values[0] = persistent_global; values[1] = constant_int; - MDNode *persistent_global_md = MDNode::get(M.getContext(), values, 2); + MDNode *persistent_global_md = MDNode::get(llvm_module.getContext(), values, 2); named_metadata->addOperand(persistent_global_md); alloc->replaceAllUsesWith(persistent_global); @@ -554,13 +556,16 @@ } bool -IRForTarget::MaybeHandleVariable(Module &M, - Value *V, - bool Store) +IRForTarget::MaybeHandleVariable +( + Module &llvm_module, + Value *llvm_value_ptr, + bool Store +) { lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS); - if (ConstantExpr *constant_expr = dyn_cast(V)) + if (ConstantExpr *constant_expr = dyn_cast(llvm_value_ptr)) { switch (constant_expr->getOpcode()) { @@ -569,16 +574,16 @@ case Instruction::GetElementPtr: case Instruction::BitCast: Value *s = constant_expr->getOperand(0); - MaybeHandleVariable(M, s, Store); + MaybeHandleVariable(llvm_module, s, Store); } } - if (GlobalVariable *global_variable = dyn_cast(V)) + if (GlobalVariable *global_variable = dyn_cast(llvm_value_ptr)) { - clang::NamedDecl *named_decl = DeclForGlobalValue(M, global_variable); + clang::NamedDecl *named_decl = DeclForGlobalValue(llvm_module, global_variable); if (!named_decl) { - if (isObjCSelectorRef(V)) + if (isObjCSelectorRef(llvm_value_ptr)) return true; if (log) @@ -586,7 +591,7 @@ return false; } - std::string name = named_decl->getName().str(); + std::string name (named_decl->getName().str()); void *opaque_type = NULL; clang::ASTContext *ast_context = NULL; @@ -618,8 +623,8 @@ if (named_decl && !m_decl_map->AddValueToStruct(named_decl, - name.c_str(), - V, + lldb_private::ConstString (name.c_str()), + llvm_value_ptr, value_size, value_alignment)) return false; @@ -644,16 +649,16 @@ } bool -IRForTarget::MaybeHandleCall(Module &M, - CallInst *C) +IRForTarget::MaybeHandleCall(Module &llvm_module, + CallInst *llvm_call_inst) { lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS); - Function *fun = C->getCalledFunction(); + Function *fun = llvm_call_inst->getCalledFunction(); if (fun == NULL) { - Value *val = C->getCalledValue(); + Value *val = llvm_call_inst->getCalledValue(); ConstantExpr *const_expr = dyn_cast(val); @@ -670,7 +675,7 @@ } } - std::string str; + lldb_private::ConstString str; if (fun->isIntrinsic()) { @@ -683,32 +688,35 @@ log->Printf("Unresolved intrinsic %s", Intrinsic::getName(intrinsic_id).c_str()); return false; case Intrinsic::memcpy: - str = "memcpy"; + { + static lldb_private::ConstString g_memcpy_str ("memcpy"); + str = g_memcpy_str; + } break; } - if (log) - log->Printf("Resolved intrinsic name %s", str.c_str()); + if (log && str) + log->Printf("Resolved intrinsic name %s", str.GetCString()); } else { - str = fun->getName().str(); + str.SetCStringWithLength (fun->getName().data(), fun->getName().size()); } - clang::NamedDecl *fun_decl = DeclForGlobalValue(M, fun); + clang::NamedDecl *fun_decl = DeclForGlobalValue (llvm_module, fun); uint64_t fun_addr; Value **fun_value_ptr = NULL; if (fun_decl) { - if (!m_decl_map->GetFunctionInfo(fun_decl, fun_value_ptr, fun_addr)) + if (!m_decl_map->GetFunctionInfo (fun_decl, fun_value_ptr, fun_addr)) { fun_value_ptr = NULL; - if (!m_decl_map->GetFunctionAddress(str.c_str(), fun_addr)) + if (!m_decl_map->GetFunctionAddress (str, fun_addr)) { if (log) - log->Printf("Function %s had no address", str.c_str()); + log->Printf("Function %s had no address", str.GetCString()); return false; } @@ -716,22 +724,22 @@ } else { - if (!m_decl_map->GetFunctionAddress(str.c_str(), fun_addr)) + if (!m_decl_map->GetFunctionAddress (str, fun_addr)) { if (log) - log->Printf("Metadataless function %s had no address", str.c_str()); + log->Printf ("Metadataless function %s had no address", str.GetCString()); } } if (log) - log->Printf("Found %s at %llx", str.c_str(), fun_addr); + log->Printf("Found %s at %llx", str.GetCString(), fun_addr); Value *fun_addr_ptr; if (!fun_value_ptr || !*fun_value_ptr) { - 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); const FunctionType *fun_ty = fun->getFunctionType(); PointerType *fun_ptr_ty = PointerType::getUnqual(fun_ty); Constant *fun_addr_int = ConstantInt::get(intptr_ty, fun_addr, false); @@ -744,18 +752,18 @@ if (fun_value_ptr) fun_addr_ptr = *fun_value_ptr; - C->setCalledFunction(fun_addr_ptr); + llvm_call_inst->setCalledFunction(fun_addr_ptr); - ConstantArray *func_name = (ConstantArray*)ConstantArray::get(M.getContext(), str); + ConstantArray *func_name = (ConstantArray*)ConstantArray::get(llvm_module.getContext(), str.GetCString()); Value *values[1]; values[0] = func_name; - MDNode *func_metadata = MDNode::get(M.getContext(), values, 1); + MDNode *func_metadata = MDNode::get(llvm_module.getContext(), values, 1); - C->setMetadata("lldb.call.realName", func_metadata); + llvm_call_inst->setMetadata("lldb.call.realName", func_metadata); if (log) - log->Printf("Set metadata for %p [%d, %s]", C, func_name->isString(), func_name->getAsString().c_str()); + log->Printf("Set metadata for %p [%d, %s]", llvm_call_inst, func_name->isString(), func_name->getAsString().c_str()); return true; } @@ -1048,7 +1056,7 @@ argument = iter; } - if (!argument->getName().equals("___clang_arg")) + if (!argument->getName().equals("$__lldb_arg")) return false; if (log) @@ -1071,7 +1079,7 @@ const clang::NamedDecl *decl; Value *value; off_t offset; - const char *name; + lldb_private::ConstString name; if (!m_decl_map->GetStructElement (decl, value, offset, name, element_index)) return false; @@ -1079,7 +1087,7 @@ if (log) log->Printf(" %s [%s] (%s) placed at %d", value->getName().str().c_str(), - name, + name.GetCString(), PrintValue(value, true).c_str(), offset); @@ -1117,7 +1125,7 @@ Function::iterator bbi; //////////////////////////////////////////////////////////// - // Replace __clang_expr_result with a persistent variable + // Replace $__lldb_expr_result with a persistent variable // if (!createResultVariable(M, *function)) From jingham at apple.com Fri Oct 15 17:53:49 2010 From: jingham at apple.com (Jim Ingham) Date: Fri, 15 Oct 2010 22:53:49 -0000 Subject: [Lldb-commits] [lldb] r116638 - /lldb/trunk/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntimeV2/AppleObjCRuntimeV2.cpp Message-ID: <20101015225349.535EF2A6C12C@llvm.org> Author: jingham Date: Fri Oct 15 17:53:49 2010 New Revision: 116638 URL: http://llvm.org/viewvc/llvm-project?rev=116638&view=rev Log: Use the ValueObject directly where possible. Modified: lldb/trunk/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntimeV2/AppleObjCRuntimeV2.cpp Modified: lldb/trunk/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntimeV2/AppleObjCRuntimeV2.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntimeV2/AppleObjCRuntimeV2.cpp?rev=116638&r1=116637&r2=116638&view=diff ============================================================================== --- lldb/trunk/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntimeV2/AppleObjCRuntimeV2.cpp (original) +++ lldb/trunk/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntimeV2/AppleObjCRuntimeV2.cpp Fri Oct 15 17:53:49 2010 @@ -41,7 +41,7 @@ { // ObjC objects can only be pointers: - if (!ClangASTContext::IsPointerType (object.GetClangType())) + if (!object.IsPointerType()) return NULL; // Make the argument list: we pass one arg, the address of our pointer, to the print function. From gclayton at apple.com Fri Oct 15 18:16:40 2010 From: gclayton at apple.com (Greg Clayton) Date: Fri, 15 Oct 2010 23:16:40 -0000 Subject: [Lldb-commits] [lldb] r116641 - in /lldb/trunk: include/lldb/Target/UnixSignals.h source/Target/UnixSignals.cpp Message-ID: <20101015231640.8787E2A6C12C@llvm.org> Author: gclayton Date: Fri Oct 15 18:16:40 2010 New Revision: 116641 URL: http://llvm.org/viewvc/llvm-project?rev=116641&view=rev Log: Fixed the UnixSignals class to be able to get a signal by name, short name, or signal number when using: int32_t UnixSignals::GetSignalNumberFromName (const char *name) const; Modified: lldb/trunk/include/lldb/Target/UnixSignals.h lldb/trunk/source/Target/UnixSignals.cpp Modified: lldb/trunk/include/lldb/Target/UnixSignals.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/Target/UnixSignals.h?rev=116641&r1=116640&r2=116641&view=diff ============================================================================== --- lldb/trunk/include/lldb/Target/UnixSignals.h (original) +++ lldb/trunk/include/lldb/Target/UnixSignals.h Fri Oct 15 18:16:40 2010 @@ -130,14 +130,6 @@ ~Signal () {} }; - Signal * - GetSignalByName (const char *name, - int32_t &signo); - - const Signal * - GetSignalByName (const char *name, - int32_t &signo) const; - void Reset (); Modified: lldb/trunk/source/Target/UnixSignals.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Target/UnixSignals.cpp?rev=116641&r1=116640&r2=116641&view=diff ============================================================================== --- lldb/trunk/source/Target/UnixSignals.cpp (original) +++ lldb/trunk/source/Target/UnixSignals.cpp Fri Oct 15 18:16:40 2010 @@ -13,6 +13,7 @@ // C++ Includes // Other libraries and framework includes // Project includes +#include "lldb/Interpreter/Args.h" using namespace lldb_private; @@ -117,41 +118,6 @@ m_signals.erase (pos); } -UnixSignals::Signal * -UnixSignals::GetSignalByName (const char *name, int32_t &signo) -{ - ConstString const_name (name); - - collection::iterator pos, end = m_signals.end (); - for (pos = m_signals.begin (); pos != end; pos++) - { - if ((const_name == pos->second.m_name) || (const_name == pos->second.m_short_name)) - { - signo = pos->first; - return &pos->second; - } - } - return NULL; -} - - -const UnixSignals::Signal * -UnixSignals::GetSignalByName (const char *name, int32_t &signo) const -{ - ConstString const_name (name); - - collection::const_iterator pos, end = m_signals.end (); - for (pos = m_signals.begin (); pos != end; pos++) - { - if (const_name == pos->second.m_name) - { - signo = pos->first; - return &(pos->second); - } - } - return NULL; -} - const char * UnixSignals::GetSignalAsCString (int signo) const { @@ -173,12 +139,19 @@ int32_t UnixSignals::GetSignalNumberFromName (const char *name) const { - int32_t signo; - const Signal *signal = GetSignalByName (name, signo); - if (signal == NULL) - return LLDB_INVALID_SIGNAL_NUMBER; - else + ConstString const_name (name); + + collection::const_iterator pos, end = m_signals.end (); + for (pos = m_signals.begin (); pos != end; pos++) + { + if ((const_name == pos->second.m_name) || (const_name == pos->second.m_short_name)) + return pos->first; + } + + const int32_t signo = Args::StringToSInt32(name, LLDB_INVALID_SIGNAL_NUMBER, 0); + if (signo != LLDB_INVALID_SIGNAL_NUMBER) return signo; + return LLDB_INVALID_SIGNAL_NUMBER; } int32_t @@ -253,7 +226,10 @@ bool UnixSignals::SetShouldSuppress (const char *signal_name, bool value) { - return SetShouldSuppress (GetSignalNumberFromName (signal_name), value); + const int32_t signo = GetSignalNumberFromName (signal_name); + if (signo != LLDB_INVALID_SIGNAL_NUMBER) + return SetShouldSuppress (signo, value); + return false; } bool @@ -280,7 +256,10 @@ bool UnixSignals::SetShouldStop (const char *signal_name, bool value) { - return SetShouldStop (GetSignalNumberFromName (signal_name), value); + const int32_t signo = GetSignalNumberFromName (signal_name); + if (signo != LLDB_INVALID_SIGNAL_NUMBER) + return SetShouldStop (signo, value); + return false; } bool @@ -307,6 +286,8 @@ bool UnixSignals::SetShouldNotify (const char *signal_name, bool value) { - return SetShouldNotify (GetSignalNumberFromName (signal_name), value); + const int32_t signo = GetSignalNumberFromName (signal_name); + if (signo != LLDB_INVALID_SIGNAL_NUMBER) + return SetShouldNotify (signo, value); + return false; } - From johnny.chen at apple.com Fri Oct 15 18:33:18 2010 From: johnny.chen at apple.com (Johnny Chen) Date: Fri, 15 Oct 2010 23:33:18 -0000 Subject: [Lldb-commits] [lldb] r116643 - /lldb/trunk/test/lldbutil.py Message-ID: <20101015233318.F330E2A6C12C@llvm.org> Author: johnny Date: Fri Oct 15 18:33:18 2010 New Revision: 116643 URL: http://llvm.org/viewvc/llvm-project?rev=116643&view=rev Log: Don't wrap StringIO inside a with statement. It is not a context manager. Modified: lldb/trunk/test/lldbutil.py Modified: lldb/trunk/test/lldbutil.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/lldbutil.py?rev=116643&r1=116642&r2=116643&view=diff ============================================================================== --- lldb/trunk/test/lldbutil.py (original) +++ lldb/trunk/test/lldbutil.py Fri Oct 15 18:33:18 2010 @@ -4,7 +4,7 @@ import lldb import sys -import cStringIO +import StringIO ################################################ # # @@ -167,7 +167,7 @@ def PrintStackTrace(thread, string_buffer = False): """Prints a simple stack trace of this thread.""" - output = cStringIO.StringIO() if string_buffer else sys.stdout + output = StringIO.StringIO() if string_buffer else sys.stdout target = thread.GetProcess().GetTarget() depth = thread.GetNumFrames() @@ -196,14 +196,13 @@ num=i, addr=load_addr, mod=mods[i], func=funcs[i], file=files[i], line=lines[i]) if string_buffer: - with output: - return output.getvalue() + return output.getvalue() def PrintStackTraces(process, string_buffer = False): """Prints the stack traces of all the threads.""" - output = cStringIO.StringIO() if string_buffer else sys.stdout + output = StringIO.StringIO() if string_buffer else sys.stdout print >> output, "Stack traces for " + repr(process) @@ -211,5 +210,4 @@ print >> output, PrintStackTrace(process.GetThreadAtIndex(i), string_buffer=True) if string_buffer: - with output: - return output.getvalue() + return output.getvalue() From johnny.chen at apple.com Fri Oct 15 18:35:32 2010 From: johnny.chen at apple.com (Johnny Chen) Date: Fri, 15 Oct 2010 23:35:32 -0000 Subject: [Lldb-commits] [lldb] r116645 - /lldb/trunk/test/foundation/TestObjCMethods.py Message-ID: <20101015233532.517142A6C12C@llvm.org> Author: johnny Date: Fri Oct 15 18:35:32 2010 New Revision: 116645 URL: http://llvm.org/viewvc/llvm-project?rev=116645&view=rev Log: Remove the @expectedFailure decorators, as rdar://problem/8542091 is supposed to be fixed. Also change the expected matching pattern of the 'expr -o -- my' output. Modified: lldb/trunk/test/foundation/TestObjCMethods.py Modified: lldb/trunk/test/foundation/TestObjCMethods.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/foundation/TestObjCMethods.py?rev=116645&r1=116644&r2=116645&view=diff ============================================================================== --- lldb/trunk/test/foundation/TestObjCMethods.py (original) +++ lldb/trunk/test/foundation/TestObjCMethods.py Fri Oct 15 18:35:32 2010 @@ -23,7 +23,7 @@ self.buildDwarf() self.break_on_objc_methods() - @unittest2.expectedFailure + #@unittest2.expectedFailure # rdar://problem/8542091 # rdar://problem/8492646 def test_data_type_and_expr_with_dsym(self): @@ -31,7 +31,7 @@ self.buildDsym() self.data_type_and_expr_objc() - @unittest2.expectedFailure + #@unittest2.expectedFailure # rdar://problem/8542091 # rdar://problem/8492646 def test_data_type_and_expr_with_dwarf(self): @@ -173,8 +173,7 @@ # Test new feature with r115115: # Add "-o" option to "expression" which prints the object description if available. self.expect("expr -o -- my", "Object description displayed correctly", - startstr = "Hello from ", - substrs = ["a.out", "with timestamp: "]) + patterns = ["Hello from.*a.out.*with timestamp: "]) if __name__ == '__main__': From johnny.chen at apple.com Fri Oct 15 18:38:15 2010 From: johnny.chen at apple.com (Johnny Chen) Date: Fri, 15 Oct 2010 23:38:15 -0000 Subject: [Lldb-commits] [lldb] r116646 - in /lldb/trunk/test/conditional_break: TestConditionalBreak.py main.c Message-ID: <20101015233815.3D2F12A6C12C@llvm.org> Author: johnny Date: Fri Oct 15 18:38:15 2010 New Revision: 116646 URL: http://llvm.org/viewvc/llvm-project?rev=116646&view=rev Log: Use line_number() utility function to find the number from main.c to test against instead of using hard-coded line number. Modified: lldb/trunk/test/conditional_break/TestConditionalBreak.py lldb/trunk/test/conditional_break/main.c Modified: lldb/trunk/test/conditional_break/TestConditionalBreak.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/conditional_break/TestConditionalBreak.py?rev=116646&r1=116645&r2=116646&view=diff ============================================================================== --- lldb/trunk/test/conditional_break/TestConditionalBreak.py (original) +++ lldb/trunk/test/conditional_break/TestConditionalBreak.py Fri Oct 15 18:38:15 2010 @@ -54,6 +54,10 @@ self.assertTrue(self.process.GetState() == lldb.eStateStopped, STOPPED_DUE_TO_BREAKPOINT) + # Find the line number where a's parent frame function is c. + line = line_number('main.c', + "// Find the line number where a's parent frame function is c here.") + # Suppose we are only interested in the call scenario where c()'s # immediate caller is a() and we want to find out the value passed from # a(). @@ -71,11 +75,11 @@ #lldbutil.PrintStackTrace(thread) self.assertTrue(name0 == "c", "Break on function c()") if (name1 == "a"): - line = frame1.GetLineEntry().GetLine() # By design, we know that a() calls c() only from main.c:27. # In reality, similar logic can be used to find out the call # site. - self.assertTrue(line == 27, "Immediate caller a() at main.c:27") + self.assertTrue(frame1.GetLineEntry().GetLine() == line, + "Immediate caller a() at main.c:%d" % line) # And the local variable 'val' should have a value of (int) 3. val = frame1.LookupVar("val") Modified: lldb/trunk/test/conditional_break/main.c URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/conditional_break/main.c?rev=116646&r1=116645&r2=116646&view=diff ============================================================================== --- lldb/trunk/test/conditional_break/main.c (original) +++ lldb/trunk/test/conditional_break/main.c Fri Oct 15 18:38:15 2010 @@ -24,7 +24,7 @@ if (val <= 1) return b(val); else if (val >= 3) - return c(val); + return c(val); // Find the line number where a's parent frame function is c here. return val; } From johnny.chen at apple.com Fri Oct 15 18:55:05 2010 From: johnny.chen at apple.com (Johnny Chen) Date: Fri, 15 Oct 2010 23:55:05 -0000 Subject: [Lldb-commits] [lldb] r116648 - in /lldb/trunk/test: lldbtest.py plugins/darwin.py types/AbstractBase.py Message-ID: <20101015235505.BA7B12A6C12C@llvm.org> Author: johnny Date: Fri Oct 15 18:55:05 2010 New Revision: 116648 URL: http://llvm.org/viewvc/llvm-project?rev=116648&view=rev Log: Some re-achitecturing of the plugins interface. The caller is now required to pass in a 'sender' arg to the buildDefault(), buildDsym(), buildDwarf(), and cleanup() functions. The sender arg will be the test instance itself (i.e., an instance of TestBase). This is so that the relevant command execution can be recorded in the TestBase.session object if sender is available. The lldbtest.system() command has been modified to pop the 'sender' arg out of the keyword arguments dictionary and use it as the test instance to facilitate seesion recordings. An example is in test/types/AbstractBase.py: def generic_type_tester(self, atoms, quotedDisplay=False): """Test that variables with basic types are displayed correctly.""" # First, capture the golden output emitted by the oracle, i.e., the # series of printf statements. go = system("./a.out", sender=self) There are cases when sender is None. This is the case when the @classmethod is involved in the use of these APIs. When this happens, there is no recording into a session object, but printing on the sys.stderr is still honored if the trace flag is ON. An example is in test/settings/TestSettings.py: @classmethod def classCleanup(cls): system(["/bin/sh", "-c", "rm -f output.txt"]) system(["/bin/sh", "-c", "rm -f stdout.txt"]) Modified: lldb/trunk/test/lldbtest.py lldb/trunk/test/plugins/darwin.py lldb/trunk/test/types/AbstractBase.py Modified: lldb/trunk/test/lldbtest.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/lldbtest.py?rev=116648&r1=116647&r2=116648&view=diff ============================================================================== --- lldb/trunk/test/lldbtest.py (original) +++ lldb/trunk/test/lldbtest.py Fri Oct 15 18:55:05 2010 @@ -185,52 +185,6 @@ def EnvArray(): return map(lambda k,v: k+"="+v, os.environ.keys(), os.environ.values()) -# From 2.7's subprocess.check_output() convenience function. -def system(*popenargs, **kwargs): - r"""Run command with arguments and return its output as a byte string. - - If the exit code was non-zero it raises a CalledProcessError. The - CalledProcessError object will have the return code in the returncode - attribute and output in the output attribute. - - The arguments are the same as for the Popen constructor. Example: - - >>> check_output(["ls", "-l", "/dev/null"]) - 'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n' - - The stdout argument is not allowed as it is used internally. - To capture standard error in the result, use stderr=STDOUT. - - >>> check_output(["/bin/sh", "-c", - ... "ls -l non_existent_file ; exit 0"], - ... stderr=STDOUT) - 'ls: non_existent_file: No such file or directory\n' - """ - if 'stdout' in kwargs: - raise ValueError('stdout argument not allowed, it will be overridden.') - process = Popen(stdout=PIPE, *popenargs, **kwargs) - output, error = process.communicate() - retcode = process.poll() - - if traceAlways: - if isinstance(popenargs, types.StringTypes): - args = [popenargs] - else: - args = list(popenargs) - print >> sys.stderr - print >> sys.stderr, "os command:", args - print >> sys.stderr, "stdout:", output - print >> sys.stderr, "stderr:", error - print >> sys.stderr, "retcode:", retcode - print >> sys.stderr - - if retcode: - cmd = kwargs.get("args") - if cmd is None: - cmd = popenargs[0] - raise CalledProcessError(retcode, cmd) - return output - def line_number(filename, string_to_match): """Helper function to return the line number of the first matched string.""" with open(filename, 'r') as f: @@ -254,10 +208,9 @@ into the stderr. """ def __init__(self, test, trace): - """Create a StringIO instance; record session, stderr, and trace.""" + """Create a StringIO instance; record the session obj and trace flag.""" StringIO.StringIO.__init__(self) - self.session = test.session - self.stderr = test.old_stderr + self.session = test.session if test else None self.trace = trace def __enter__(self): @@ -274,10 +227,61 @@ recordings to our session object. And close the StringIO object, too. """ if self.trace: - print >> self.stderr, self.getvalue() - print >> self.session, self.getvalue() + print >> sys.stderr, self.getvalue() + if self.session: + print >> self.session, self.getvalue() self.close() +# From 2.7's subprocess.check_output() convenience function. +def system(*popenargs, **kwargs): + r"""Run command with arguments and return its output as a byte string. + + If the exit code was non-zero it raises a CalledProcessError. The + CalledProcessError object will have the return code in the returncode + attribute and output in the output attribute. + + The arguments are the same as for the Popen constructor. Example: + + >>> check_output(["ls", "-l", "/dev/null"]) + 'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n' + + The stdout argument is not allowed as it is used internally. + To capture standard error in the result, use stderr=STDOUT. + + >>> check_output(["/bin/sh", "-c", + ... "ls -l non_existent_file ; exit 0"], + ... stderr=STDOUT) + 'ls: non_existent_file: No such file or directory\n' + """ + + # Assign the sender object to variable 'test' and remove it from kwargs. + test = kwargs.pop('sender', None) + + if 'stdout' in kwargs: + raise ValueError('stdout argument not allowed, it will be overridden.') + process = Popen(stdout=PIPE, *popenargs, **kwargs) + output, error = process.communicate() + retcode = process.poll() + + with recording(test, traceAlways) as sbuf: + if isinstance(popenargs, types.StringTypes): + args = [popenargs] + else: + args = list(popenargs) + print >> sbuf + print >> sbuf, "os command:", args + print >> sbuf, "stdout:", output + print >> sbuf, "stderr:", error + print >> sbuf, "retcode:", retcode + print >> sbuf + + if retcode: + cmd = kwargs.get("args") + if cmd is None: + cmd = popenargs[0] + raise CalledProcessError(retcode, cmd) + return output + class TestBase(unittest2.TestCase): """This LLDB abstract base class is meant to be subclassed.""" @@ -403,16 +407,10 @@ self.dict = None self.doTearDownCleanup = False - # Create a string buffer to record the session info. + # Create a string buffer to record the session info, to be dumped into a + # test case specific file if test failure is encountered. self.session = StringIO.StringIO() - # Substitute self.session as the sys.stderr and restore it at the end of - # the test during tearDown(). If trace is ON, we dump the session info - # into the real stderr as well. The session info will be dumped into a - # test case specific file if a failure is encountered. - self.old_stderr = sys.stderr - sys.stderr = self.session - # Optimistically set self.__failed__ to False initially. If the test # failed, the session info (self.session) is then dumped into a session # specific file for diagnosis. @@ -469,9 +467,6 @@ if self.__failed__: self.dumpSessionInfo() - # Restore the sys.stderr to what it was before. - sys.stderr = self.old_stderr - def runCmd(self, cmd, msg=None, check=True, trace=False, setCookie=True): """ Ask the command interpreter to handle the command and then check its @@ -656,19 +651,19 @@ def buildDefault(self, architecture=None, compiler=None, dictionary=None): """Platform specific way to build the default binaries.""" module = __import__(sys.platform) - if not module.buildDefault(architecture, compiler, dictionary): + if not module.buildDefault(self, architecture, compiler, dictionary): raise Exception("Don't know how to build default binary") def buildDsym(self, architecture=None, compiler=None, dictionary=None): """Platform specific way to build binaries with dsym info.""" module = __import__(sys.platform) - if not module.buildDsym(architecture, compiler, dictionary): + if not module.buildDsym(self, architecture, compiler, dictionary): raise Exception("Don't know how to build binary with dsym") def buildDwarf(self, architecture=None, compiler=None, dictionary=None): """Platform specific way to build binaries with dwarf maps.""" module = __import__(sys.platform) - if not module.buildDwarf(architecture, compiler, dictionary): + if not module.buildDwarf(self, architecture, compiler, dictionary): raise Exception("Don't know how to build binary with dwarf") def DebugSBValue(self, frame, val): Modified: lldb/trunk/test/plugins/darwin.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/plugins/darwin.py?rev=116648&r1=116647&r2=116648&view=diff ============================================================================== --- lldb/trunk/test/plugins/darwin.py (original) +++ lldb/trunk/test/plugins/darwin.py Fri Oct 15 18:55:05 2010 @@ -57,43 +57,46 @@ return " " + cmdline -def buildDefault(architecture=None, compiler=None, dictionary=None): +def buildDefault(sender=None, architecture=None, compiler=None, dictionary=None): """Build the binaries the default way.""" lldbtest.system(["/bin/sh", "-c", "make clean" + getCmdLine(dictionary) + "; make" + getArchSpec(architecture) + getCCSpec(compiler) - + getCmdLine(dictionary)]) + + getCmdLine(dictionary)], + sender=sender) # True signifies that we can handle building default. return True -def buildDsym(architecture=None, compiler=None, dictionary=None): +def buildDsym(sender=None, architecture=None, compiler=None, dictionary=None): """Build the binaries with dsym debug info.""" lldbtest.system(["/bin/sh", "-c", "make clean" + getCmdLine(dictionary) + "; make MAKE_DSYM=YES" + getArchSpec(architecture) + getCCSpec(compiler) - + getCmdLine(dictionary)]) + + getCmdLine(dictionary)], + sender=sender) # True signifies that we can handle building dsym. return True -def buildDwarf(architecture=None, compiler=None, dictionary=None): +def buildDwarf(sender=None, architecture=None, compiler=None, dictionary=None): """Build the binaries with dwarf debug info.""" lldbtest.system(["/bin/sh", "-c", "make clean" + getCmdLine(dictionary) + "; make MAKE_DSYM=NO" + getArchSpec(architecture) + getCCSpec(compiler) - + getCmdLine(dictionary)]) + + getCmdLine(dictionary)], + sender=sender) # True signifies that we can handle building dsym. return True -def cleanup(dictionary=None): +def cleanup(sender=None, dictionary=None): """Perform a platform-specific cleanup after the test.""" if os.path.isfile("Makefile"): - lldbtest.system(["/bin/sh", "-c", "make clean" + getCmdLine(dictionary)] - ) + lldbtest.system(["/bin/sh", "-c", "make clean"+getCmdLine(dictionary)], + sender=sender) # True signifies that we can handle building dsym. return True Modified: lldb/trunk/test/types/AbstractBase.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/types/AbstractBase.py?rev=116648&r1=116647&r2=116648&view=diff ============================================================================== --- lldb/trunk/test/types/AbstractBase.py (original) +++ lldb/trunk/test/types/AbstractBase.py Fri Oct 15 18:55:05 2010 @@ -24,7 +24,7 @@ # First, capture the golden output emitted by the oracle, i.e., the # series of printf statements. - go = system("./a.out") + go = system("./a.out", sender=self) # This golden list contains a list of (variable, value) pairs extracted # from the golden output. gl = [] @@ -102,7 +102,7 @@ # First, capture the golden output emitted by the oracle, i.e., the # series of printf statements. - go = system("./a.out") + go = system("./a.out", sender=self) # This golden list contains a list of (variable, value) pairs extracted # from the golden output. gl = [] From johnny.chen at apple.com Fri Oct 15 19:08:49 2010 From: johnny.chen at apple.com (Johnny Chen) Date: Sat, 16 Oct 2010 00:08:49 -0000 Subject: [Lldb-commits] [lldb] r116649 - /lldb/trunk/test/lldbtest.py Message-ID: <20101016000849.98A0E2A6C12C@llvm.org> Author: johnny Date: Fri Oct 15 19:08:49 2010 New Revision: 116649 URL: http://llvm.org/viewvc/llvm-project?rev=116649&view=rev Log: Missed this spot where module.cleanup() can be passed a test instance to facilitate session recording. This happens inside an instance method where the test instance is well known. Modified: lldb/trunk/test/lldbtest.py Modified: lldb/trunk/test/lldbtest.py URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/lldbtest.py?rev=116649&r1=116648&r2=116649&view=diff ============================================================================== --- lldb/trunk/test/lldbtest.py (original) +++ lldb/trunk/test/lldbtest.py Fri Oct 15 19:08:49 2010 @@ -458,7 +458,7 @@ # Perform registered teardown cleanup. if doCleanup and self.doTearDownCleanup: module = __import__(sys.platform) - if not module.cleanup(dictionary=self.dict): + if not module.cleanup(self, dictionary=self.dict): raise Exception("Don't know how to do cleanup") # See also LLDBTestResult (dotest.py) which is a singlton class derived From gclayton at apple.com Sat Oct 16 13:11:41 2010 From: gclayton at apple.com (Greg Clayton) Date: Sat, 16 Oct 2010 18:11:41 -0000 Subject: [Lldb-commits] [lldb] r116674 - /lldb/trunk/tools/debugserver/source/MacOSX/MachTask.cpp Message-ID: <20101016181141.792AF2A6C12C@llvm.org> Author: gclayton Date: Sat Oct 16 13:11:41 2010 New Revision: 116674 URL: http://llvm.org/viewvc/llvm-project?rev=116674&view=rev Log: Fixed an issue with MachTask::TaskResume () where if the task was already suspended, we would call "int ::task_resume (task_t task);" as many times as it took to resume the task which isn't what we want to do. Modified: lldb/trunk/tools/debugserver/source/MacOSX/MachTask.cpp Modified: lldb/trunk/tools/debugserver/source/MacOSX/MachTask.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/debugserver/source/MacOSX/MachTask.cpp?rev=116674&r1=116673&r2=116674&view=diff ============================================================================== --- lldb/trunk/tools/debugserver/source/MacOSX/MachTask.cpp (original) +++ lldb/trunk/tools/debugserver/source/MacOSX/MachTask.cpp Sat Oct 16 13:11:41 2010 @@ -86,14 +86,18 @@ { struct task_basic_info task_info; task_t task = TaskPort(); + if (task == TASK_NULL) + return KERN_INVALID_ARGUMENT; DNBError err; err = BasicInfo(task, &task_info); if (err.Success()) { - integer_t i; - for (i=0; i 0) { err = ::task_resume (task); if (DNBLogCheckLogBit(LOG_TASK) || err.Fail()) From gclayton at apple.com Sat Oct 16 16:09:32 2010 From: gclayton at apple.com (Greg Clayton) Date: Sat, 16 Oct 2010 21:09:32 -0000 Subject: [Lldb-commits] [lldb] r116676 - /lldb/trunk/source/Expression/IRDynamicChecks.cpp Message-ID: <20101016210932.A8A132A6C12C@llvm.org> Author: gclayton Date: Sat Oct 16 16:09:32 2010 New Revision: 116676 URL: http://llvm.org/viewvc/llvm-project?rev=116676&view=rev Log: prefix more stuff with '$' to make sure we don't go trying to lookup anything we don't need to. Modified: lldb/trunk/source/Expression/IRDynamicChecks.cpp Modified: lldb/trunk/source/Expression/IRDynamicChecks.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Expression/IRDynamicChecks.cpp?rev=116676&r1=116675&r2=116676&view=diff ============================================================================== --- lldb/trunk/source/Expression/IRDynamicChecks.cpp (original) +++ lldb/trunk/source/Expression/IRDynamicChecks.cpp Sat Oct 16 16:09:32 2010 @@ -31,9 +31,9 @@ static const char g_valid_pointer_check_text[] = "extern \"C\" void\n" -VALID_POINTER_CHECK_NAME " (unsigned char *ptr)\n" +"$__lldb_valid_pointer_check (unsigned char *$__lldb_arg_ptr)\n" "{\n" -" unsigned char val = *ptr;\n" +" unsigned char $__lldb_local_val = *__lldb_arg_ptr;\n" "}"; static bool FunctionExists(const SymbolContext &sym_ctx, const char *name) @@ -59,7 +59,7 @@ if (FunctionExists(sym_ctx, "gdb_object_getClass")) { return "extern \"C\" void " - "$__lldb_objc_object_check(uint8_t *obj)" + "$__lldb_objc_object_check(uint8_t *$__lldb_arg_obj)" "{" "" "}"; @@ -67,7 +67,7 @@ else if (FunctionExists(sym_ctx, "gdb_class_getClass")) { return "extern \"C\" void " - "$__lldb_objc_object_check(uint8_t *obj)" + "$__lldb_objc_object_check(uint8_t *$__lldb_arg_obj)" "{" "" "}"; @@ -75,7 +75,7 @@ else { return "extern \"C\" void " - "$__lldb_objc_object_check(uint8_t *obj)" + "$__lldb_objc_object_check(uint8_t *$__lldb_arg_obj)" "{" "" "}"; From gclayton at apple.com Sun Oct 17 17:03:33 2010 From: gclayton at apple.com (Greg Clayton) Date: Sun, 17 Oct 2010 22:03:33 -0000 Subject: [Lldb-commits] [lldb] r116690 - in /lldb/trunk: include/lldb/ include/lldb/Host/ lldb.xcodeproj/ source/Core/ source/Expression/ source/Host/common/ source/Host/macosx/ source/Host/macosx/cfcpp/ source/Interpreter/ source/Plugins/Process/gdb-remote/ source/Target/ tools/darwin-debug/ tools/debugserver/debugserver.xcodeproj/ Message-ID: <20101017220333.4B01B2A6C12C@llvm.org> Author: gclayton Date: Sun Oct 17 17:03:32 2010 New Revision: 116690 URL: http://llvm.org/viewvc/llvm-project?rev=116690&view=rev Log: Added a new Host call to find LLDB related paths: static bool Host::GetLLDBPath (lldb::PathType path_type, FileSpec &file_spec); This will fill in "file_spec" with an appropriate path that is appropriate for the current Host OS. MacOSX will return paths within the LLDB.framework, and other unixes will return the paths they want. The current PathType enums are: typedef enum PathType { ePathTypeLLDBShlibDir, // The directory where the lldb.so (unix) or LLDB mach-o file in LLDB.framework (MacOSX) exists ePathTypeSupportExecutableDir, // Find LLDB support executable directory (debugserver, etc) ePathTypeHeaderDir, // Find LLDB header file directory ePathTypePythonDir // Find Python modules (PYTHONPATH) directory } PathType; All places that were finding executables are and python paths are now updated to use this Host call. Added another new host call to launch the inferior in a terminal. This ability will be very host specific and doesn't need to be supported on all systems. MacOSX currently will create a new .command file and tell Terminal.app to open the .command file. It also uses the new "darwin-debug" app which is a small app that uses posix to exec (no fork) and stop at the entry point of the program. The GDB remote plug-in is almost able launch a process and attach to it, it currently will spawn the process, but it won't attach to it just yet. This will let LLDB not have to share the terminal with another process and a new terminal window will pop up when you launch. This won't get hooked up until we work out all of the kinks. The new Host function is: static lldb::pid_t Host::LaunchInNewTerminal ( const char **argv, // argv[0] is executable const char **envp, const ArchSpec *arch_spec, bool stop_at_entry, bool disable_aslr); Cleaned up FileSpec::GetPath to not use strncpy() as it was always zero filling the entire path buffer. Fixed an issue with the dynamic checker function where I missed a '$' prefix that should have been added. Added: lldb/trunk/tools/darwin-debug/ lldb/trunk/tools/darwin-debug/darwin-debug.cpp Modified: lldb/trunk/include/lldb/Host/Host.h lldb/trunk/include/lldb/lldb-enumerations.h lldb/trunk/lldb.xcodeproj/project.pbxproj lldb/trunk/source/Core/FileSpec.cpp lldb/trunk/source/Expression/IRDynamicChecks.cpp lldb/trunk/source/Host/common/Host.cpp lldb/trunk/source/Host/macosx/Host.mm lldb/trunk/source/Host/macosx/cfcpp/CFCMutableArray.cpp lldb/trunk/source/Host/macosx/cfcpp/CFCMutableArray.h lldb/trunk/source/Interpreter/ScriptInterpreterPython.cpp lldb/trunk/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp lldb/trunk/source/Target/Target.cpp lldb/trunk/source/Target/TargetList.cpp lldb/trunk/tools/debugserver/debugserver.xcodeproj/project.pbxproj Modified: lldb/trunk/include/lldb/Host/Host.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/Host/Host.h?rev=116690&r1=116689&r2=116690&view=diff ============================================================================== --- lldb/trunk/include/lldb/Host/Host.h (original) +++ lldb/trunk/include/lldb/Host/Host.h Sun Oct 17 17:03:32 2010 @@ -256,8 +256,46 @@ static FileSpec GetModuleFileSpecForHostAddress (const void *host_addr); + + //------------------------------------------------------------------ + /// When executable files may live within a directory, where the + /// directory represents an executable bundle (like the MacOSX + /// app bundles), the locate the executable within the containing + /// bundle. + /// + /// @param[in,out] file + /// A file spec that currently points to the bundle that will + /// be filled in with the executable path within the bundle + /// if \b true is returned. Otherwise \a file is left untouched. + /// + /// @return + /// \b true if \a file was resolved, \b false if this function + /// was not able to resolve the path. + //------------------------------------------------------------------ + static bool + ResolveExecutableInBundle (FileSpec &file); + + //------------------------------------------------------------------ + /// Find a resource files that are related to LLDB. + /// + /// Operating systems have different ways of storing shared + /// libraries and related resources. This function abstracts the + /// access to these paths. + /// + /// @param[in] path_type + /// The type of LLDB resource path you are looking for. If the + /// enumeration ends with "Dir", then only the \a file_spec's + /// directory member gets filled in. + /// + /// @param[in] file_spec + /// A file spec that gets filled in with the appriopriate path. + /// + /// @return + /// \b true if \a resource_path was resolved, \a false otherwise. + //------------------------------------------------------------------ static bool - ResolveExecutableInBundle (FileSpec *file); + GetLLDBPath (lldb::PathType path_type, + FileSpec &file_spec); static uint32_t ListProcessesMatchingName (const char *name, StringList &matches, std::vector &pids); @@ -269,7 +307,14 @@ GetArchSpecForExistingProcess (const char *process_name); static lldb::pid_t - LaunchApplication (const FileSpec &file_spec); + LaunchApplication (const FileSpec &app_file_spec); + + static lldb::pid_t + LaunchInNewTerminal (const char **argv, // argv[0] is executable + const char **envp, + const ArchSpec *arch_spec, + bool stop_at_entry, + bool disable_aslr); static bool OpenFileInExternalEditor (const FileSpec &file_spec, uint32_t line_no); Modified: lldb/trunk/include/lldb/lldb-enumerations.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/lldb-enumerations.h?rev=116690&r1=116689&r2=116690&view=diff ============================================================================== --- lldb/trunk/include/lldb/lldb-enumerations.h (original) +++ lldb/trunk/include/lldb/lldb-enumerations.h Sun Oct 17 17:03:32 2010 @@ -597,6 +597,19 @@ eSortOrderByName, } SortOrder; + +//---------------------------------------------------------------------- +// Used in conjunction with Host::GetLLDBResource () to find files that +// are related to +//---------------------------------------------------------------------- +typedef enum PathType +{ + ePathTypeLLDBShlibDir, // The directory where the lldb.so (unix) or LLDB mach-o file in LLDB.framework (MacOSX) exists + ePathTypeSupportExecutableDir, // Find LLDB support executable directory (debugserver, etc) + ePathTypeHeaderDir, // Find LLDB header file directory + ePathTypePythonDir // Find Python modules (PYTHONPATH) directory +} PathType; + } // namespace lldb Modified: lldb/trunk/lldb.xcodeproj/project.pbxproj URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/lldb.xcodeproj/project.pbxproj?rev=116690&r1=116689&r2=116690&view=diff ============================================================================== --- lldb/trunk/lldb.xcodeproj/project.pbxproj (original) +++ lldb/trunk/lldb.xcodeproj/project.pbxproj Sun Oct 17 17:03:32 2010 @@ -21,6 +21,8 @@ 261B5A5411C3F2AD00AABD0A /* SharingPtr.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 261B5A5211C3F2AD00AABD0A /* SharingPtr.cpp */; }; 261B5A5511C3F2AD00AABD0A /* SharingPtr.h in Headers */ = {isa = PBXBuildFile; fileRef = 261B5A5311C3F2AD00AABD0A /* SharingPtr.h */; settings = {ATTRIBUTES = (Public, ); }; }; 262CFC7711A4510000946C6C /* debugserver in Resources */ = {isa = PBXBuildFile; fileRef = 26CE05A0115C31E50022F371 /* debugserver */; }; + 26368A3C126B697600E8659F /* darwin-debug.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 26368A3B126B697600E8659F /* darwin-debug.cpp */; }; + 26368AF7126B960500E8659F /* darwin-debug in Resources */ = {isa = PBXBuildFile; fileRef = 26579F68126A25920007C5CB /* darwin-debug */; }; 26424E3D125986CB0016D82C /* ValueObjectConstResult.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 26424E3C125986CB0016D82C /* ValueObjectConstResult.cpp */; }; 26424E3F125986D30016D82C /* ValueObjectConstResult.h in Headers */ = {isa = PBXBuildFile; fileRef = 26424E3E125986D30016D82C /* ValueObjectConstResult.h */; }; 264723A611FA076E00DE380C /* CleanUp.h in Headers */ = {isa = PBXBuildFile; fileRef = 264723A511FA076E00DE380C /* CleanUp.h */; }; @@ -415,6 +417,13 @@ remoteGlobalIDString = 26CE0593115C31C20022F371; remoteInfo = debugserver; }; + 26368AF5126B95FA00E8659F /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 26579F67126A25920007C5CB /* darwin-debug */; + remoteInfo = "darwin-debug"; + }; 266803611160110D008E1FE4 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */; @@ -562,6 +571,7 @@ 261E18CD1148966100BADCD3 /* GDBRemoteRegisterContext.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = GDBRemoteRegisterContext.cpp; path = "source/Plugins/Process/gdb-remote/GDBRemoteRegisterContext.cpp"; sourceTree = ""; }; 263664921140A4930075843B /* Debugger.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = Debugger.cpp; path = source/Core/Debugger.cpp; sourceTree = ""; }; 263664941140A4C10075843B /* Debugger.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = Debugger.h; path = include/lldb/Core/Debugger.h; sourceTree = ""; }; + 26368A3B126B697600E8659F /* darwin-debug.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = "darwin-debug.cpp"; path = "tools/darwin-debug/darwin-debug.cpp"; sourceTree = ""; }; 263FEDA5112CC1DA00E4C208 /* ThreadSafeSTLMap.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = ThreadSafeSTLMap.h; path = include/lldb/Core/ThreadSafeSTLMap.h; sourceTree = ""; }; 26424E3C125986CB0016D82C /* ValueObjectConstResult.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = ValueObjectConstResult.cpp; path = source/Core/ValueObjectConstResult.cpp; sourceTree = ""; }; 26424E3E125986D30016D82C /* ValueObjectConstResult.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = ValueObjectConstResult.h; path = include/lldb/Core/ValueObjectConstResult.h; sourceTree = ""; }; @@ -570,6 +580,7 @@ 264723A511FA076E00DE380C /* CleanUp.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = CleanUp.h; path = include/lldb/Utility/CleanUp.h; sourceTree = ""; }; 264AD83711095BA600E0B039 /* CommandObjectLog.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = CommandObjectLog.cpp; path = source/Commands/CommandObjectLog.cpp; sourceTree = ""; }; 264AD83911095BBD00E0B039 /* CommandObjectLog.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = CommandObjectLog.h; path = source/Commands/CommandObjectLog.h; sourceTree = ""; }; + 26579F68126A25920007C5CB /* darwin-debug */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = "darwin-debug"; sourceTree = BUILT_PRODUCTS_DIR; }; 265ABF6210F42EE900531910 /* DebugSymbols.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = DebugSymbols.framework; path = /System/Library/PrivateFrameworks/DebugSymbols.framework; sourceTree = ""; }; 265E9BE1115C2BAA00D0DCCB /* debugserver.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = debugserver.xcodeproj; path = tools/debugserver/debugserver.xcodeproj; sourceTree = ""; }; 2660D9F611922A1300958FBD /* StringExtractor.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = StringExtractor.cpp; path = source/Utility/StringExtractor.cpp; sourceTree = ""; }; @@ -1123,6 +1134,13 @@ /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ + 26579F66126A25920007C5CB /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; 26680205115FD0ED008E1FE4 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; @@ -1196,6 +1214,7 @@ children = ( 26F5C26A10F3D9A4009D5894 /* lldb */, 26680207115FD0ED008E1FE4 /* LLDB.framework */, + 26579F68126A25920007C5CB /* darwin-debug */, ); name = Products; sourceTree = ""; @@ -1543,6 +1562,14 @@ name = API; sourceTree = ""; }; + 26579F55126A255E0007C5CB /* darwin-debug */ = { + isa = PBXGroup; + children = ( + 26368A3B126B697600E8659F /* darwin-debug.cpp */, + ); + name = "darwin-debug"; + sourceTree = ""; + }; 265E9BE0115C2B8500D0DCCB /* debugserver */ = { isa = PBXGroup; children = ( @@ -2112,6 +2139,7 @@ 26F5C22410F3D950009D5894 /* Tools */ = { isa = PBXGroup; children = ( + 26579F55126A255E0007C5CB /* darwin-debug */, 265E9BE0115C2B8500D0DCCB /* debugserver */, 26F5C22510F3D956009D5894 /* Driver */, ); @@ -2397,6 +2425,22 @@ /* End PBXHeadersBuildPhase section */ /* Begin PBXNativeTarget section */ + 26579F67126A25920007C5CB /* darwin-debug */ = { + isa = PBXNativeTarget; + buildConfigurationList = 26579F6D126A25BF0007C5CB /* Build configuration list for PBXNativeTarget "darwin-debug" */; + buildPhases = ( + 26579F65126A25920007C5CB /* Sources */, + 26579F66126A25920007C5CB /* Frameworks */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = "darwin-debug"; + productName = "lldb-launcher"; + productReference = 26579F68126A25920007C5CB /* darwin-debug */; + productType = "com.apple.product-type.tool"; + }; 26680206115FD0ED008E1FE4 /* LLDB */ = { isa = PBXNativeTarget; buildConfigurationList = 2668020B115FD0EE008E1FE4 /* Build configuration list for PBXNativeTarget "LLDB" */; @@ -2414,6 +2458,7 @@ ); dependencies = ( 262CFC7211A450CB00946C6C /* PBXTargetDependency */, + 26368AF6126B95FA00E8659F /* PBXTargetDependency */, ); name = LLDB; productName = LLDB; @@ -2462,6 +2507,7 @@ targets = ( 26F5C26910F3D9A4009D5894 /* lldb-tool */, 26680206115FD0ED008E1FE4 /* LLDB */, + 26579F67126A25920007C5CB /* darwin-debug */, ); }; /* End PBXProject section */ @@ -2482,6 +2528,7 @@ buildActionMask = 2147483647; files = ( 262CFC7711A4510000946C6C /* debugserver in Resources */, + 26368AF7126B960500E8659F /* darwin-debug in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -2557,6 +2604,14 @@ /* End PBXShellScriptBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ + 26579F65126A25920007C5CB /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 26368A3C126B697600E8659F /* darwin-debug.cpp in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; 26680204115FD0ED008E1FE4 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; @@ -2885,6 +2940,11 @@ name = debugserver; targetProxy = 262CFC7111A450CB00946C6C /* PBXContainerItemProxy */; }; + 26368AF6126B95FA00E8659F /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 26579F67126A25920007C5CB /* darwin-debug */; + targetProxy = 26368AF5126B95FA00E8659F /* PBXContainerItemProxy */; + }; 266803621160110D008E1FE4 /* PBXTargetDependency */ = { isa = PBXTargetDependency; target = 26680206115FD0ED008E1FE4 /* LLDB */; @@ -2944,6 +3004,48 @@ }; name = Release; }; + 26579F6A126A25920007C5CB /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + COPY_PHASE_STRIP = NO; + GCC_DYNAMIC_NO_PIC = NO; + GCC_ENABLE_FIX_AND_CONTINUE = YES; + GCC_MODEL_TUNING = G5; + GCC_OPTIMIZATION_LEVEL = 0; + INSTALL_PATH = /usr/local/bin; + PREBINDING = NO; + PRODUCT_NAME = "darwin-debug"; + }; + name = Debug; + }; + 26579F6B126A25920007C5CB /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + COPY_PHASE_STRIP = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + GCC_ENABLE_FIX_AND_CONTINUE = NO; + GCC_MODEL_TUNING = G5; + INSTALL_PATH = /usr/local/bin; + PREBINDING = NO; + PRODUCT_NAME = "darwin-debug"; + ZERO_LINK = NO; + }; + name = Release; + }; + 26579F6C126A25920007C5CB /* BuildAndIntegration */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + GCC_ENABLE_FIX_AND_CONTINUE = YES; + GCC_MODEL_TUNING = G5; + INSTALL_PATH = /usr/local/bin; + PREBINDING = NO; + PRODUCT_NAME = "darwin-debug"; + }; + name = BuildAndIntegration; + }; 26680209115FD0ED008E1FE4 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { @@ -3251,6 +3353,16 @@ defaultConfigurationIsVisible = 0; defaultConfigurationName = BuildAndIntegration; }; + 26579F6D126A25BF0007C5CB /* Build configuration list for PBXNativeTarget "darwin-debug" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 26579F6A126A25920007C5CB /* Debug */, + 26579F6B126A25920007C5CB /* Release */, + 26579F6C126A25920007C5CB /* BuildAndIntegration */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = BuildAndIntegration; + }; 2668020B115FD0EE008E1FE4 /* Build configuration list for PBXNativeTarget "LLDB" */ = { isa = XCConfigurationList; buildConfigurations = ( Modified: lldb/trunk/source/Core/FileSpec.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Core/FileSpec.cpp?rev=116690&r1=116689&r2=116690&view=diff ============================================================================== --- lldb/trunk/source/Core/FileSpec.cpp (original) +++ lldb/trunk/source/Core/FileSpec.cpp Sun Oct 17 17:03:32 2010 @@ -574,42 +574,37 @@ bool FileSpec::GetPath(char *path, size_t max_path_length) const { - if (max_path_length == 0) - return false; - - path[0] = '\0'; - const char *dirname = m_directory.AsCString(); - const char *filename = m_filename.AsCString(); - if (dirname) + if (max_path_length) { - if (filename && filename[0]) + const char *dirname = m_directory.AsCString(); + const char *filename = m_filename.AsCString(); + if (dirname) { - return (size_t)::snprintf (path, max_path_length, "%s/%s", dirname, filename) < max_path_length; + if (filename) + { + return (size_t)::snprintf (path, max_path_length, "%s/%s", dirname, filename) < max_path_length; + } + else + { + size_t dir_len = m_directory.GetLength() + 1; + if (dir_len < max_path_length) + { + ::memcpy (path, dirname, dir_len); + return true; + } + } } - else + else if (filename) { - ::strncpy (path, dirname, max_path_length); + size_t filename_len = m_filename.GetLength() + 1; + if (filename_len < max_path_length) + { + ::memcpy (path, filename, filename_len); + return true; + } } } - else if (filename) - { - ::strncpy (path, filename, max_path_length); - } - else - { - return false; - } - - // Any code paths that reach here assume that strncpy, or a similar function was called - // where any remaining bytes will be filled with NULLs and that the string won't be - // NULL terminated if it won't fit in the buffer. - - // If the last character is NULL, then all went well - if (path[max_path_length-1] == '\0') - return true; - - // Make sure the path is terminated, as it didn't fit into "path" - path[max_path_length-1] = '\0'; + path[0] = '\0'; return false; } Modified: lldb/trunk/source/Expression/IRDynamicChecks.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Expression/IRDynamicChecks.cpp?rev=116690&r1=116689&r2=116690&view=diff ============================================================================== --- lldb/trunk/source/Expression/IRDynamicChecks.cpp (original) +++ lldb/trunk/source/Expression/IRDynamicChecks.cpp Sun Oct 17 17:03:32 2010 @@ -33,7 +33,7 @@ "extern \"C\" void\n" "$__lldb_valid_pointer_check (unsigned char *$__lldb_arg_ptr)\n" "{\n" -" unsigned char $__lldb_local_val = *__lldb_arg_ptr;\n" +" unsigned char $__lldb_local_val = *$__lldb_arg_ptr;\n" "}"; static bool FunctionExists(const SymbolContext &sym_ctx, const char *name) Modified: lldb/trunk/source/Host/common/Host.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Host/common/Host.cpp?rev=116690&r1=116689&r2=116690&view=diff ============================================================================== --- lldb/trunk/source/Host/common/Host.cpp (original) +++ lldb/trunk/source/Host/common/Host.cpp Sun Oct 17 17:03:32 2010 @@ -626,12 +626,140 @@ #if !defined (__APPLE__) // see Host.mm bool -Host::ResolveExecutableInBundle (FileSpec *file) +Host::ResolveExecutableInBundle (FileSpec &file) { - return false; + return false; } #endif + +bool +Host::GetLLDBPath (PathType path_type, FileSpec &file_spec) +{ + // To get paths related to LLDB we get the path to the exectuable that + // contains this function. On MacOSX this will be "LLDB.framework/.../LLDB", + // on linux this is assumed to be the "lldb" main executable. If LLDB on + // linux is actually in a shared library (lldb.so??) then this function will + // need to be modified to "do the right thing". + + switch (path_type) + { + case ePathTypeLLDBShlibDir: + { + static ConstString g_lldb_so_dir; + if (!g_lldb_so_dir) + { + FileSpec lldb_file_spec (Host::GetModuleFileSpecForHostAddress ((void *)Host::GetLLDBPath)); + g_lldb_so_dir = lldb_file_spec.GetDirectory(); + } + file_spec.GetDirectory() = g_lldb_so_dir; + return file_spec.GetDirectory(); + } + break; + + case ePathTypeSupportExecutableDir: + { + static ConstString g_lldb_support_exe_dir; + if (!g_lldb_support_exe_dir) + { + FileSpec lldb_file_spec; + if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec)) + { + char raw_path[PATH_MAX]; + char resolved_path[PATH_MAX]; + lldb_file_spec.GetPath(raw_path, sizeof(raw_path)); + +#if defined (__APPLE__) + char *framework_pos = ::strstr (raw_path, "LLDB.framework"); + if (framework_pos) + { + framework_pos += strlen("LLDB.framework"); + ::strncpy (framework_pos, "/Resources", PATH_MAX - (framework_pos - raw_path)); + } +#endif + FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path)); + g_lldb_support_exe_dir.SetCString(resolved_path); + } + } + file_spec.GetDirectory() = g_lldb_support_exe_dir; + return file_spec.GetDirectory(); + } + break; + + case ePathTypeHeaderDir: + { + static ConstString g_lldb_headers_dir; + if (!g_lldb_headers_dir) + { +#if defined (__APPLE__) + FileSpec lldb_file_spec; + if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec)) + { + char raw_path[PATH_MAX]; + char resolved_path[PATH_MAX]; + lldb_file_spec.GetPath(raw_path, sizeof(raw_path)); + + char *framework_pos = ::strstr (raw_path, "LLDB.framework"); + if (framework_pos) + { + framework_pos += strlen("LLDB.framework"); + ::strncpy (framework_pos, "/Headers", PATH_MAX - (framework_pos - raw_path)); + } + FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path)); + g_lldb_headers_dir.SetCString(resolved_path); + } +#else + // TODO: Anyone know how we can determine this for linux?? + g_lldb_headers_dir.SetCString ("/opt/local/include/lldb"); +#endif + } + file_spec.GetDirectory() = g_lldb_headers_dir; + return file_spec.GetDirectory(); + } + break; + + case ePathTypePythonDir: + { + // TODO: Anyone know how we can determine this for linux?? + // For linux we are currently assuming the location of the lldb + // binary that contains this function is the directory that will + // contain lldb.so, lldb.py and embedded_interpreter.py... + + static ConstString g_lldb_python_dir; + if (!g_lldb_python_dir) + { + FileSpec lldb_file_spec; + if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec)) + { + char raw_path[PATH_MAX]; + char resolved_path[PATH_MAX]; + lldb_file_spec.GetPath(raw_path, sizeof(raw_path)); + +#if defined (__APPLE__) + char *framework_pos = ::strstr (raw_path, "LLDB.framework"); + if (framework_pos) + { + framework_pos += strlen("LLDB.framework"); + ::strncpy (framework_pos, "/Resources/Python", PATH_MAX - (framework_pos - raw_path)); + } +#endif + FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path)); + g_lldb_python_dir.SetCString(resolved_path); + } + } + file_spec.GetDirectory() = g_lldb_python_dir; + return file_spec.GetDirectory(); + } + break; + + default: + assert (!"Unhandled PathType"); + break; + } + + return false; +} + uint32_t Host::ListProcessesMatchingName (const char *name, StringList &matches, std::vector &pids) { @@ -727,4 +855,25 @@ { return false; } + + +lldb::pid_t +LaunchApplication (const FileSpec &app_file_spec) +{ + return LLDB_INVALID_PROCESS_ID; +} + +lldb::pid_t +Host::LaunchInNewTerminal +( + const char **argv, + const char **envp, + const ArchSpec *arch_spec, + bool stop_at_entry, + bool disable_aslr +) +{ + return LLDB_INVALID_PROCESS_ID; +} + #endif Modified: lldb/trunk/source/Host/macosx/Host.mm URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Host/macosx/Host.mm?rev=116690&r1=116689&r2=116690&view=diff ============================================================================== --- lldb/trunk/source/Host/macosx/Host.mm (original) +++ lldb/trunk/source/Host/macosx/Host.mm Sun Oct 17 17:03:32 2010 @@ -8,10 +8,18 @@ //===----------------------------------------------------------------------===// #include "lldb/Host/Host.h" + +#include +#include + +#include "lldb/Core/ArchSpec.h" #include "lldb/Core/FileSpec.h" #include "lldb/Core/Log.h" +#include "lldb/Core/StreamFile.h" +#include "lldb/Core/StreamString.h" #include "cfcpp/CFCBundle.h" +#include "cfcpp/CFCMutableArray.h" #include "cfcpp/CFCMutableDictionary.h" #include "cfcpp/CFCReleaser.h" #include "cfcpp/CFCString.h" @@ -90,26 +98,26 @@ bool -Host::ResolveExecutableInBundle (FileSpec *file) +Host::ResolveExecutableInBundle (FileSpec &file) { #if defined (__APPLE__) - if (file->GetFileType () == FileSpec::eFileTypeDirectory) - { - char path[PATH_MAX]; - if (file->GetPath(path, sizeof(path))) - { - CFCBundle bundle (path); - CFCReleaser url(bundle.CopyExecutableURL ()); - if (url.get()) - { - if (::CFURLGetFileSystemRepresentation (url.get(), YES, (UInt8*)path, sizeof(path))) + if (file.GetFileType () == FileSpec::eFileTypeDirectory) + { + char path[PATH_MAX]; + if (file.GetPath(path, sizeof(path))) { - file->SetFile(path); - return true; + CFCBundle bundle (path); + CFCReleaser url(bundle.CopyExecutableURL ()); + if (url.get()) + { + if (::CFURLGetFileSystemRepresentation (url.get(), YES, (UInt8*)path, sizeof(path))) + { + file.SetFile(path); + return true; + } + } } - } } - } #endif return false; } @@ -124,8 +132,8 @@ ::bzero (&app_params, sizeof (app_params)); app_params.flags = kLSLaunchDefaults | kLSLaunchDontAddToRecents | - kLSLaunchDontSwitch | - kLSLaunchNewInstance;// | 0x00001000; + kLSLaunchNewInstance; + FSRef app_fsref; CFCString app_cfstr (app_path, kCFStringEncodingUTF8); @@ -150,6 +158,122 @@ return pid; } +lldb::pid_t +Host::LaunchInNewTerminal +( + const char **argv, + const char **envp, + const ArchSpec *arch_spec, + bool stop_at_entry, + bool disable_aslr +) +{ + if (!argv || !argv[0]) + return LLDB_INVALID_PROCESS_ID; + + OSStatus error = 0; + + FileSpec program (argv[0]); + + + char temp_file_path[PATH_MAX]; + const char *tmpdir = ::getenv ("TMPDIR"); + if (tmpdir == NULL) + tmpdir = "/tmp/"; + ::snprintf (temp_file_path, sizeof(temp_file_path), "%s%s-XXXXXX", tmpdir, program.GetFilename().AsCString()); + + if (::mktemp (temp_file_path) == NULL) + return LLDB_INVALID_PROCESS_ID; + + ::strncat (temp_file_path, ".command", sizeof (temp_file_path)); + + StreamFile command_file (temp_file_path, "w"); + + FileSpec darwin_debug_file_spec; + if (!Host::GetLLDBPath (ePathTypeSupportExecutableDir, darwin_debug_file_spec)) + return LLDB_INVALID_PROCESS_ID; + darwin_debug_file_spec.GetFilename().SetCString("darwin-debug"); + + if (!darwin_debug_file_spec.Exists()) + return LLDB_INVALID_PROCESS_ID; + + char launcher_path[PATH_MAX]; + darwin_debug_file_spec.GetPath(launcher_path, sizeof(launcher_path)); + command_file.Printf("\"%s\" ", launcher_path); + + if (arch_spec && arch_spec->IsValid()) + { + command_file.Printf("--arch=%s ", arch_spec->AsCString()); + } + + if (disable_aslr) + { + command_file.PutCString("--disable-aslr "); + } + + command_file.PutCString("-- "); + + if (argv) + { + for (size_t i=0; argv[i] != NULL; ++i) + { + command_file.Printf("\"%s\" ", argv[i]); + } + } + command_file.EOL(); + command_file.Close(); + if (::chmod (temp_file_path, S_IRWXU | S_IRWXG) != 0) + return LLDB_INVALID_PROCESS_ID; + + CFCMutableDictionary cf_env_dict; + + const bool can_create = true; + if (envp) + { + for (size_t i=0; envp[i] != NULL; ++i) + { + const char *env_entry = envp[i]; + const char *equal_pos = strchr(env_entry, '='); + if (equal_pos) + { + std::string env_key (env_entry, equal_pos); + std::string env_val (equal_pos + 1); + CFCString cf_env_key (env_key.c_str(), kCFStringEncodingUTF8); + CFCString cf_env_val (env_val.c_str(), kCFStringEncodingUTF8); + cf_env_dict.AddValue (cf_env_key.get(), cf_env_val.get(), can_create); + } + } + } + + LSApplicationParameters app_params; + ::bzero (&app_params, sizeof (app_params)); + app_params.flags = kLSLaunchDontAddToRecents | kLSLaunchAsync; + app_params.argv = NULL; + app_params.environment = (CFDictionaryRef)cf_env_dict.get(); + + CFCReleaser command_file_url (::CFURLCreateFromFileSystemRepresentation (NULL, + (const UInt8 *)temp_file_path, + strlen (temp_file_path), + false)); + + CFCMutableArray urls; + + // Terminal.app will open the ".command" file we have created + // and run our process inside it which will wait at the entry point + // for us to attach. + urls.AppendValue(command_file_url.get()); + + ProcessSerialNumber psn; + error = LSOpenURLsWithRole(urls.get(), kLSRolesShell, NULL, &app_params, &psn, 1); + + if (error != noErr) + return LLDB_INVALID_PROCESS_ID; + + ::pid_t pid = LLDB_INVALID_PROCESS_ID; + error = ::GetProcessPID(&psn, &pid); + return pid; +} + bool Host::OpenFileInExternalEditor (const FileSpec &file_spec, uint32_t line_no) { Modified: lldb/trunk/source/Host/macosx/cfcpp/CFCMutableArray.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Host/macosx/cfcpp/CFCMutableArray.cpp?rev=116690&r1=116689&r2=116690&view=diff ============================================================================== --- lldb/trunk/source/Host/macosx/cfcpp/CFCMutableArray.cpp (original) +++ lldb/trunk/source/Host/macosx/cfcpp/CFCMutableArray.cpp Sun Oct 17 17:03:32 2010 @@ -8,6 +8,7 @@ //===----------------------------------------------------------------------===// #include "CFCMutableArray.h" +#include "CFCString.h" //---------------------------------------------------------------------- // CFCString constructor @@ -121,3 +122,45 @@ } return false; } + + +bool +CFCMutableArray::AppendCStringAsCFString (const char *s, CFStringEncoding encoding, bool can_create) +{ + CFMutableArrayRef array = get(); + if (array == NULL) + { + if (can_create == false) + return false; + array = ::CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks); + reset ( array ); + } + if (array != NULL) + { + CFCString cf_str (s, encoding); + ::CFArrayAppendValue (array, cf_str.get()); + return true; + } + return false; +} + +bool +CFCMutableArray::AppendFileSystemRepresentationAsCFString (const char *s, bool can_create) +{ + CFMutableArrayRef array = get(); + if (array == NULL) + { + if (can_create == false) + return false; + array = ::CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks); + reset ( array ); + } + if (array != NULL) + { + CFCString cf_path; + cf_path.SetFileSystemRepresentation(s); + ::CFArrayAppendValue (array, cf_path.get()); + return true; + } + return false; +} Modified: lldb/trunk/source/Host/macosx/cfcpp/CFCMutableArray.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Host/macosx/cfcpp/CFCMutableArray.h?rev=116690&r1=116689&r2=116690&view=diff ============================================================================== --- lldb/trunk/source/Host/macosx/cfcpp/CFCMutableArray.h (original) +++ lldb/trunk/source/Host/macosx/cfcpp/CFCMutableArray.h Sun Oct 17 17:03:32 2010 @@ -29,6 +29,11 @@ const void * GetValueAtIndex(CFIndex idx) const; bool SetValueAtIndex(CFIndex idx, const void *value); bool AppendValue(const void *value, bool can_create = true); // Appends value and optionally creates a CFCMutableArray if this class doesn't contain one + bool AppendCStringAsCFString (const char *cstr, + CFStringEncoding encoding = kCFStringEncodingUTF8, + bool can_create = true); + bool AppendFileSystemRepresentationAsCFString (const char *s, + bool can_create = true); }; #endif // #ifndef CoreFoundationCPP_CFMutableArray_h_ Modified: lldb/trunk/source/Interpreter/ScriptInterpreterPython.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Interpreter/ScriptInterpreterPython.cpp?rev=116690&r1=116689&r2=116690&view=diff ============================================================================== --- lldb/trunk/source/Interpreter/ScriptInterpreterPython.cpp (original) +++ lldb/trunk/source/Interpreter/ScriptInterpreterPython.cpp Sun Oct 17 17:03:32 2010 @@ -164,34 +164,42 @@ // Find the module that owns this code and use that path we get to // set the PYTHONPATH appropriately. - FileSpec this_module (Host::GetModuleFileSpecForHostAddress ((void *)init_lldb)); - std::string python_path; - - if (this_module.GetDirectory()) + FileSpec file_spec; + char python_dir_path[PATH_MAX]; + if (Host::GetLLDBPath (ePathTypePythonDir, file_spec)) { - // Append the directory that the module that loaded this code - // belongs to - python_path += this_module.GetDirectory().AsCString(""); - -#if defined (__APPLE__) - // If we are running on MacOSX we might be in a framework and should - // add an appropriate path so Resource can be found in a bundle + std::string python_path; + const char *curr_python_path = ::getenv ("PYTHONPATH"); + if (curr_python_path) + { + // We have a current value for PYTHONPATH, so lets append to it + python_path.append (curr_python_path); + } - if (::strstr(this_module.GetDirectory().AsCString(""), ".framework")) + if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path))) + { + if (!python_path.empty()) + python_path.append (1, ':'); + python_path.append (python_dir_path); + } + + if (Host::GetLLDBPath (ePathTypeLLDBShlibDir, file_spec)) { - python_path.append(1, ':'); - python_path.append(this_module.GetDirectory().AsCString("")); - python_path.append("/Resources/Python"); + if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path))) + { + if (!python_path.empty()) + python_path.append (1, ':'); + python_path.append (python_dir_path); + } } -#endif - // The the PYTHONPATH environment variable so that Python can find - // our lldb.py module and our _lldb.so. - ::setenv ("PYTHONPATH", python_path.c_str(), 1); + const char *pathon_path_env_cstr = python_path.c_str(); + ::setenv ("PYTHONPATH", pathon_path_env_cstr, 1); } Py_Initialize (); - PyObject *compiled_module = Py_CompileString (embedded_interpreter_string, "embedded_interpreter.py", + PyObject *compiled_module = Py_CompileString (embedded_interpreter_string, + "embedded_interpreter.py", Py_file_input); m_compiled_module = static_cast(compiled_module); @@ -310,14 +318,15 @@ int input_fd; FILE *input_fh = reader.GetDebugger().GetInputFileHandle(); if (input_fh != NULL) - input_fd = ::fileno (input_fh); + input_fd = ::fileno (input_fh); else - input_fd = STDIN_FILENO; + input_fd = STDIN_FILENO; script_interpreter->m_termios_valid = ::tcgetattr (input_fd, &script_interpreter->m_termios) == 0; - struct termios tmp_termios; - if (::tcgetattr (input_fd, &tmp_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); } @@ -352,9 +361,9 @@ int input_fd; FILE *input_fh = reader.GetDebugger().GetInputFileHandle(); if (input_fh != NULL) - input_fd = ::fileno (input_fh); + input_fd = ::fileno (input_fh); else - input_fd = STDIN_FILENO; + input_fd = STDIN_FILENO; ::tcsetattr (input_fd, TCSANOW, &script_interpreter->m_termios); } 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=116690&r1=116689&r2=116690&view=diff ============================================================================== --- lldb/trunk/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp (original) +++ lldb/trunk/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp Sun Oct 17 17:03:32 2010 @@ -384,12 +384,28 @@ { Error error; #if defined (LAUNCH_WITH_LAUNCH_SERVICES) - FileSpec app_file_spec (argv[0]); - pid_t pid = Host::LaunchApplication (app_file_spec); + ArchSpec inferior_arch(module->GetArchitecture()); + + //FileSpec app_file_spec (argv[0]); + pid_t pid = Host::LaunchInNewTerminal (argv, + envp, + &inferior_arch, + true, // stop at entry + (launch_flags & eLaunchFlagDisableASLR) != 0); + + // Let the app get launched and stopped... + sleep (1); + if (pid != LLDB_INVALID_PROCESS_ID) - error = DoAttachToProcessWithID (pid); + { + FileSpec program(argv[0]); + error = DoAttachToProcessWithName (program.GetFilename().AsCString(), false); + //error = DoAttachToProcessWithID (pid); + } else - error.SetErrorString("failed"); + { + error.SetErrorString("Host::LaunchApplication(() failed to launch process"); + } #else // ::LogSetBitMask (GDBR_LOG_DEFAULT); // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD); @@ -1683,31 +1699,19 @@ { // The debugserver binary is in the LLDB.framework/Resources // directory. - FileSpec framework_file_spec (Host::GetModuleFileSpecForHostAddress ((void *)lldb_private::Initialize)); - const char *framework_dir = framework_file_spec.GetDirectory().AsCString(); - const char *lldb_framework = ::strstr (framework_dir, "/LLDB.framework"); - - if (lldb_framework) - { - int len = lldb_framework - framework_dir + strlen ("/LLDB.framework"); - ::snprintf (debugserver_path, - sizeof(debugserver_path), - "%.*s/Resources/%s", - len, - framework_dir, - DEBUGSERVER_BASENAME); - debugserver_file_spec.SetFile (debugserver_path); - debugserver_exists = debugserver_file_spec.Exists(); - } - - if (debugserver_exists) + if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec)) { - g_debugserver_file_spec = debugserver_file_spec; - } - else - { - g_debugserver_file_spec.Clear(); - debugserver_file_spec.Clear(); + debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME); + debugserver_exists = debugserver_file_spec.Exists(); + if (debugserver_exists) + { + g_debugserver_file_spec = debugserver_file_spec; + } + else + { + g_debugserver_file_spec.Clear(); + debugserver_file_spec.Clear(); + } } } @@ -1731,9 +1735,9 @@ #if !defined (__arm__) - // 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... + // 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... if (inferior_arch.GetType() == eArchTypeMachO) { cpu_type_t cpu = inferior_arch.GetCPUType(); @@ -1781,10 +1785,11 @@ // Start args with "debugserver /file/path -r --" debugserver_args.AppendArgument(debugserver_path); debugserver_args.AppendArgument(debugserver_url); - debugserver_args.AppendArgument("--native-regs"); // use native registers, not the GDB registers - debugserver_args.AppendArgument("--setsid"); // make debugserver run in its own session so - // signals generated by special terminal key - // sequences (^C) don't affect debugserver + // use native registers, not the GDB registers + debugserver_args.AppendArgument("--native-regs"); + // make debugserver run in its own session so signals generated by + // special terminal key sequences (^C) don't affect debugserver + debugserver_args.AppendArgument("--setsid"); if (disable_aslr) debugserver_args.AppendArguments("--disable-aslr"); Modified: lldb/trunk/source/Target/Target.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Target/Target.cpp?rev=116690&r1=116689&r2=116690&view=diff ============================================================================== --- lldb/trunk/source/Target/Target.cpp (original) +++ lldb/trunk/source/Target/Target.cpp Sun Oct 17 17:03:32 2010 @@ -402,7 +402,7 @@ { FileSpec bundle_executable(executable_sp->GetFileSpec()); - if (Host::ResolveExecutableInBundle (&bundle_executable)) + if (Host::ResolveExecutableInBundle (bundle_executable)) { ModuleSP bundle_exe_module_sp(GetSharedModule(bundle_executable, exe_arch)); Modified: lldb/trunk/source/Target/TargetList.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Target/TargetList.cpp?rev=116690&r1=116689&r2=116690&view=diff ============================================================================== --- lldb/trunk/source/Target/TargetList.cpp (original) +++ lldb/trunk/source/Target/TargetList.cpp Sun Oct 17 17:03:32 2010 @@ -75,7 +75,7 @@ if (!resolved_file.Exists()) resolved_file.ResolveExecutableLocation (); - if (!Host::ResolveExecutableInBundle (&resolved_file)) + if (!Host::ResolveExecutableInBundle (resolved_file)) resolved_file = file; error = ModuleList::GetSharedModule(resolved_file, Added: lldb/trunk/tools/darwin-debug/darwin-debug.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/darwin-debug/darwin-debug.cpp?rev=116690&view=auto ============================================================================== --- lldb/trunk/tools/darwin-debug/darwin-debug.cpp (added) +++ lldb/trunk/tools/darwin-debug/darwin-debug.cpp Sun Oct 17 17:03:32 2010 @@ -0,0 +1,221 @@ +//===-- Launcher.cpp --------------------------------------------*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +//---------------------------------------------------------------------- +// Darwin launch helper +// +// This program was written to allow programs to be launched in a new +// Terminal.app window and have the application be stopped for debugging +// at the program entry point. +// +// Although it uses posix_spawn(), it uses Darwin specific posix spawn +// attribute flags to accomplish its task. It uses an "exec only" flag +// which avoids forking this process, and it uses a "stop at entry" +// flag to stop the program at the entry point. +// +// Since it uses darwin specific flags this code should not be compiled +// on other systems. +//---------------------------------------------------------------------- +#if defined (__APPLE__) + +#include +#include +#include +#include +#include +#include + +#ifndef _POSIX_SPAWN_DISABLE_ASLR +#define _POSIX_SPAWN_DISABLE_ASLR 0x0100 +#endif + +#define streq(a,b) strcmp(a,b) == 0 + +static struct option g_long_options[] = +{ + { "arch", required_argument, NULL, 'a' }, + { "disable-aslr", no_argument, NULL, 'd' }, + { "no-env", no_argument, NULL, 'e' }, + { "help", no_argument, NULL, 'h' }, + { "setsid", no_argument, NULL, 's' }, + { NULL, 0, NULL, 0 } +}; + +static void +usage() +{ + puts ( +"NAME\n" +" darwin-debug -- posix spawn a process that is stopped at the entry point\n" +" for debugging.\n" +"\n" +"SYNOPSIS\n" +" darwin-debug [--arch=] [--disable-aslr] [--no-env] [--setsid] [--help] -- [ ....]\n" +"\n" +"DESCRIPTION\n" +" darwin-debug will exec itself into a child process that is\n" +" halted for debugging. It does this by using posix_spawn() along with\n" +" darwin specific posix_spawn flags that allows exec only (no fork), and\n" +" stop at the program entry point. Any program arguments are\n" +" passed on to the exec as the arguments for the new process. The current\n" +" environment will be passed to the new process unless the \"--no-env\"\n" +" option is used.\n" +"\n" +"EXAMPLE\n" +" darwin-debug --arch=i386 -- /bin/ls -al /tmp\n" +); + exit (1); +} + +static void +exit_with_errno (int err, const char *prefix) +{ + if (err) + { + fprintf (stderr, + "%s%s", + prefix ? prefix : "", + strerror(err)); + exit (err); + } +} + +pid_t +posix_spawn_for_debug (const char *path, char *const *argv, char *const *envp, cpu_type_t cpu_type, int disable_aslr) +{ + pid_t pid = 0; + + posix_spawnattr_t attr; + + exit_with_errno (::posix_spawnattr_init (&attr), "::posix_spawnattr_init (&attr) error: "); + + // Here we are using a darwin specific feature that allows us to exec only + // since we want this program to turn into the program we want to debug, + // and also have the new program start suspended (right at __dyld_start) + // so we can debug it + short flags = POSIX_SPAWN_START_SUSPENDED | POSIX_SPAWN_SETEXEC; + + // Disable ASLR if we were asked to + if (disable_aslr) + flags |= _POSIX_SPAWN_DISABLE_ASLR; + + // Set the flags we just made into our posix spawn attributes + exit_with_errno (::posix_spawnattr_setflags (&attr, flags), "::posix_spawnattr_setflags (&attr, flags) error: "); + + + // Another darwin specific thing here where we can select the architecture + // of the binary we want to re-exec as. + if (cpu_type != 0) + { + size_t ocount = 0; + exit_with_errno (::posix_spawnattr_setbinpref_np (&attr, 1, &cpu_type, &ocount), "posix_spawnattr_setbinpref_np () error: "); + } + + exit_with_errno (::posix_spawnp (&pid, path, NULL, &attr, (char * const*)argv, (char * const*)envp), "posix_spawn() error: "); + + // This code will only be reached if the posix_spawn exec failed... + ::posix_spawnattr_destroy (&attr); + + return pid; +} + + +int main (int argc, char *const *argv, char *const *envp, const char **apple) +{ + const char *program_name = strrchr(apple[0], '/'); + + if (program_name) + program_name++; // Skip the last slash.. + else + program_name = apple[0]; + +#if defined (DEBUG_LLDB_LAUNCHER) + printf("%s called with:\n", program_name); + for (int i=0; i Author: gclayton Date: Sun Oct 17 20:45:30 2010 New Revision: 116693 URL: http://llvm.org/viewvc/llvm-project?rev=116693&view=rev Log: Fixed debugserver to properly attach to a process by name with the "vAttachName;" packet, and wait for a new process by name to launch with the "vAttachWait;". Fixed a few issues with attaching where if DoAttach() returned no error, yet there was no valid process ID, we would deadlock waiting for an event that would never happen. Added a new "process launch" option "--tty" that will launch the process in a new terminal if the Host layer supports the "Host::LaunchInNewTerminal(...)" function. This currently works on MacOSX and will allow the debugging of terminal applications that do complex operations with the terminal. Cleaned up the output when the process resumes, stops and halts to be consistent with the output format. Modified: lldb/trunk/source/Commands/CommandObjectProcess.cpp lldb/trunk/source/Commands/CommandObjectThread.cpp lldb/trunk/source/Core/State.cpp lldb/trunk/source/Host/macosx/Host.mm lldb/trunk/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp 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/RNBRemote.cpp lldb/trunk/tools/debugserver/source/RNBRemote.h Modified: lldb/trunk/source/Commands/CommandObjectProcess.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Commands/CommandObjectProcess.cpp?rev=116693&r1=116692&r2=116693&view=diff ============================================================================== --- lldb/trunk/source/Commands/CommandObjectProcess.cpp (original) +++ lldb/trunk/source/Commands/CommandObjectProcess.cpp Sun Oct 17 20:45:30 2010 @@ -62,6 +62,7 @@ case 'i': stdin_path = option_arg; break; case 'o': stdout_path = option_arg; break; case 'p': plugin_name = option_arg; break; + case 't': in_new_tty = true; break; default: error.SetErrorStringWithFormat("Invalid short option character '%c'.\n", short_option); break; @@ -75,6 +76,7 @@ { Options::ResetOptionValues(); stop_at_entry = false; + in_new_tty = false; stdin_path.clear(); stdout_path.clear(); stderr_path.clear(); @@ -94,6 +96,7 @@ // Instance variables to hold the values for command options. bool stop_at_entry; + bool in_new_tty; std::string stderr_path; std::string stdin_path; std::string stdout_path; @@ -146,7 +149,7 @@ // If our listener is NULL, users aren't allows to launch char filename[PATH_MAX]; - Module *exe_module = target->GetExecutableModule().get(); + const Module *exe_module = target->GetExecutableModule().get(); exe_module->GetFileSpec().GetPath(filename, sizeof(filename)); Process *process = m_interpreter.GetDebugger().GetExecutionContext().process; @@ -181,6 +184,21 @@ launch_args = process->GetRunArguments(); } + if (m_options.in_new_tty) + { + char exec_file_path[PATH_MAX]; + if (exe_module->GetFileSpec().GetPath(exec_file_path, sizeof(exec_file_path))) + { + launch_args.InsertArgumentAtIndex(0, exec_file_path); + } + else + { + result.AppendError("invalid executable"); + result.SetStatus (eReturnStatusFailed); + return false; + } + } + Args environment; process->GetEnvironmentAsArgs (environment); @@ -189,48 +207,83 @@ if (process->GetDisableASLR()) launch_flags |= eLaunchFlagDisableASLR; + + const char **inferior_argv = launch_args.GetArgumentCount() ? launch_args.GetConstArgumentVector() : NULL; + const char **inferior_envp = environment.GetArgumentCount() ? environment.GetConstArgumentVector() : NULL; + + Error error; - const char *archname = exe_module->GetArchitecture().AsCString(); + if (m_options.in_new_tty) + { + + lldb::pid_t terminal_pid = Host::LaunchInNewTerminal (inferior_argv, + inferior_envp, + &exe_module->GetArchitecture(), + true, + process->GetDisableASLR()); + + // Let the app get launched and stopped... + const char *process_name = exe_module->GetFileSpec().GetFilename().AsCString(""); - const char * stdin_path = NULL; - const char * stdout_path = NULL; - const char * stderr_path = NULL; - - // Were any standard input/output/error paths given on the command line? - if (m_options.stdin_path.empty() && - m_options.stdout_path.empty() && - m_options.stderr_path.empty()) - { - // No standard file handles were given on the command line, check - // with the process object in case they were give using "set settings" - stdin_path = process->GetStandardInputPath(); - stdout_path = process->GetStandardOutputPath(); - stderr_path = process->GetStandardErrorPath(); + if (terminal_pid == LLDB_INVALID_PROCESS_ID) + { + error.SetErrorStringWithFormat ("failed to launch '%s' in new terminal", process_name); + } + else + { + for (int i=0; i<20; i++) + { + usleep (250000); + error = process->Attach (process_name, false); + if (error.Success()) + break; + } + } } else { - stdin_path = m_options.stdin_path.empty() ? NULL : m_options.stdin_path.c_str(); - stdout_path = m_options.stdout_path.empty() ? NULL : m_options.stdout_path.c_str(); - stderr_path = m_options.stderr_path.empty() ? NULL : m_options.stderr_path.c_str(); - } - - if (stdin_path == NULL) - stdin_path = "/dev/null"; - if (stdout_path == NULL) - stdout_path = "/dev/null"; - if (stderr_path == NULL) - stderr_path = "/dev/null"; - - Error error (process->Launch (launch_args.GetArgumentCount() ? launch_args.GetConstArgumentVector() : NULL, - environment.GetArgumentCount() ? environment.GetConstArgumentVector() : NULL, - launch_flags, - stdin_path, - stdout_path, - stderr_path)); + const char * stdin_path = NULL; + const char * stdout_path = NULL; + const char * stderr_path = NULL; + + // Were any standard input/output/error paths given on the command line? + if (m_options.stdin_path.empty() && + m_options.stdout_path.empty() && + m_options.stderr_path.empty()) + { + // No standard file handles were given on the command line, check + // with the process object in case they were give using "set settings" + stdin_path = process->GetStandardInputPath(); + stdout_path = process->GetStandardOutputPath(); + stderr_path = process->GetStandardErrorPath(); + } + else + { + stdin_path = m_options.stdin_path.empty() ? NULL : m_options.stdin_path.c_str(); + stdout_path = m_options.stdout_path.empty() ? NULL : m_options.stdout_path.c_str(); + stderr_path = m_options.stderr_path.empty() ? NULL : m_options.stderr_path.c_str(); + } + + if (stdin_path == NULL) + stdin_path = "/dev/null"; + if (stdout_path == NULL) + stdout_path = "/dev/null"; + if (stderr_path == NULL) + stderr_path = "/dev/null"; + + error = process->Launch (inferior_argv, + inferior_envp, + launch_flags, + stdin_path, + stdout_path, + stderr_path); + } if (error.Success()) { - result.AppendMessageWithFormat ("Launching '%s' (%s)\n", filename, archname); + const char *archname = exe_module->GetArchitecture().AsCString(); + + result.AppendMessageWithFormat ("Process %i launched: '%s' (%s)\n", process->GetID(), filename, archname); result.SetDidChangeProcessState (true); if (m_options.stop_at_entry == false) { @@ -273,17 +326,23 @@ }; +#define SET1 LLDB_OPT_SET_1 +#define SET2 LLDB_OPT_SET_2 + lldb::OptionDefinition CommandObjectProcessLaunch::CommandOptions::g_option_table[] = { -{ LLDB_OPT_SET_1, false, "stop-at-entry", 's', no_argument, NULL, 0, eArgTypeNone, "Stop at the entry point of the program when launching a process."}, -{ LLDB_OPT_SET_1, false, "stdin", 'i', required_argument, NULL, 0, eArgTypePath, "Redirect stdin for the process to ."}, -{ LLDB_OPT_SET_1, false, "stdout", 'o', required_argument, NULL, 0, eArgTypePath, "Redirect stdout for the process to ."}, -{ LLDB_OPT_SET_1, false, "stderr", 'e', required_argument, NULL, 0, eArgTypePath, "Redirect stderr for the process to ."}, -{ LLDB_OPT_SET_1, false, "plugin", 'p', required_argument, NULL, 0, eArgTypePlugin, "Name of the process plugin you want to use."}, -{ 0, false, NULL, 0, 0, NULL, 0, eArgTypeNone, NULL } +{ SET1 | SET2, false, "stop-at-entry", 's', no_argument, NULL, 0, eArgTypeNone, "Stop at the entry point of the program when launching a process."}, +{ SET1 , false, "stdin", 'i', required_argument, NULL, 0, eArgTypePath, "Redirect stdin for the process to ."}, +{ SET1 , false, "stdout", 'o', required_argument, NULL, 0, eArgTypePath, "Redirect stdout for the process to ."}, +{ SET1 , false, "stderr", 'e', required_argument, NULL, 0, eArgTypePath, "Redirect stderr for the process to ."}, +{ SET1 | SET2, false, "plugin", 'p', required_argument, NULL, 0, eArgTypePlugin, "Name of the process plugin you want to use."}, +{ SET2, false, "tty", 't', no_argument, NULL, 0, eArgTypeNone, "Start the process in a new terminal (tty)."}, +{ 0, false, NULL, 0, 0, NULL, 0, eArgTypeNone, NULL } }; +#undef SET1 +#undef SET2 //------------------------------------------------------------------------- // CommandObjectProcessAttach @@ -722,7 +781,7 @@ Error error(process->Resume()); if (error.Success()) { - result.AppendMessageWithFormat ("Resuming process %i\n", process->GetID()); + result.AppendMessageWithFormat ("Process %i resuming\n", process->GetID()); if (synchronous_execution) { state = process->WaitForProcessToStop (NULL); Modified: lldb/trunk/source/Commands/CommandObjectThread.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Commands/CommandObjectThread.cpp?rev=116693&r1=116692&r2=116693&view=diff ============================================================================== --- lldb/trunk/source/Commands/CommandObjectThread.cpp (original) +++ lldb/trunk/source/Commands/CommandObjectThread.cpp Sun Oct 17 20:45:30 2010 @@ -924,7 +924,7 @@ Error error (process->Resume()); if (error.Success()) { - result.AppendMessageWithFormat ("Resuming process %i\n", process->GetID()); + result.AppendMessageWithFormat ("Process %i resuming\n", process->GetID()); if (synchronous_execution) { state = process->WaitForProcessToStop (NULL); @@ -1223,7 +1223,7 @@ Error error (process->Resume ()); if (error.Success()) { - result.AppendMessageWithFormat ("Resuming process %i\n", process->GetID()); + result.AppendMessageWithFormat ("Process %i resuming\n", process->GetID()); if (synchronous_execution) { StateType state = process->WaitForProcessToStop (NULL); Modified: lldb/trunk/source/Core/State.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Core/State.cpp?rev=116693&r1=116692&r2=116693&view=diff ============================================================================== --- lldb/trunk/source/Core/State.cpp (original) +++ lldb/trunk/source/Core/State.cpp Sun Oct 17 20:45:30 2010 @@ -22,17 +22,17 @@ { switch (state) { - case eStateInvalid: return "Invalid"; - case eStateUnloaded: return "Unloaded"; - case eStateAttaching: return "Attaching"; - case eStateLaunching: return "Launching"; - case eStateStopped: return "Stopped"; - case eStateRunning: return "Running"; - case eStateStepping: return "Stepping"; - case eStateCrashed: return "Crashed"; - case eStateDetached: return "Detached"; - case eStateExited: return "Exited"; - case eStateSuspended: return "Suspended"; + case eStateInvalid: return "invalid"; + case eStateUnloaded: return "unloaded"; + case eStateAttaching: return "attaching"; + case eStateLaunching: return "launching"; + case eStateStopped: return "stopped"; + case eStateRunning: return "running"; + case eStateStepping: return "stepping"; + case eStateCrashed: return "crashed"; + case eStateDetached: return "detached"; + case eStateExited: return "exited"; + case eStateSuspended: return "suspended"; } static char unknown_state_string[64]; snprintf(unknown_state_string, sizeof (unknown_state_string), "StateType = %i", state); Modified: lldb/trunk/source/Host/macosx/Host.mm URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Host/macosx/Host.mm?rev=116693&r1=116692&r2=116693&view=diff ============================================================================== --- lldb/trunk/source/Host/macosx/Host.mm (original) +++ lldb/trunk/source/Host/macosx/Host.mm Sun Oct 17 20:45:30 2010 @@ -220,7 +220,7 @@ command_file.Printf("\"%s\" ", argv[i]); } } - command_file.EOL(); + command_file.PutCString("\necho Process exited with status $?\n"); command_file.Close(); if (::chmod (temp_file_path, S_IRWXU | S_IRWXG) != 0) return LLDB_INVALID_PROCESS_ID; 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=116693&r1=116692&r2=116693&view=diff ============================================================================== --- lldb/trunk/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp (original) +++ lldb/trunk/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp Sun Oct 17 20:45:30 2010 @@ -366,7 +366,6 @@ return error; } -//#define LAUNCH_WITH_LAUNCH_SERVICES 1 //---------------------------------------------------------------------- // Process Control //---------------------------------------------------------------------- @@ -383,30 +382,6 @@ ) { Error error; -#if defined (LAUNCH_WITH_LAUNCH_SERVICES) - ArchSpec inferior_arch(module->GetArchitecture()); - - //FileSpec app_file_spec (argv[0]); - pid_t pid = Host::LaunchInNewTerminal (argv, - envp, - &inferior_arch, - true, // stop at entry - (launch_flags & eLaunchFlagDisableASLR) != 0); - - // Let the app get launched and stopped... - sleep (1); - - if (pid != LLDB_INVALID_PROCESS_ID) - { - FileSpec program(argv[0]); - error = DoAttachToProcessWithName (program.GetFilename().AsCString(), false); - //error = DoAttachToProcessWithID (pid); - } - else - { - error.SetErrorString("Host::LaunchApplication(() failed to launch process"); - } -#else // ::LogSetBitMask (GDBR_LOG_DEFAULT); // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD); // ::LogSetLogFile ("/dev/stdout"); @@ -522,7 +497,6 @@ SetID(LLDB_INVALID_PROCESS_ID); error.SetErrorStringWithFormat("Failed to get object file from '%s' for arch %s.\n", module->GetFileSpec().GetFilename().AsCString(), module->GetArchitecture().AsCString()); } -#endif return error; } @@ -646,13 +620,9 @@ void ProcessGDBRemote::DidLaunch () { -#if defined (LAUNCH_WITH_LAUNCH_SERVICES) - DidAttach (); -#else DidLaunchOrAttach (); if (m_dynamic_loader_ap.get()) m_dynamic_loader_ap->DidLaunch(); -#endif } Error @@ -795,9 +765,10 @@ { StreamString packet; - packet.PutCString("vAttach"); if (wait_for_launch) - packet.PutCString("Wait"); + packet.PutCString("vAttachWait"); + else + packet.PutCString("vAttachName"); packet.PutChar(';'); packet.PutBytesAsRawHex8(process_name, strlen(process_name), eByteOrderHost, eByteOrderHost); StringExtractorGDBRemote response; @@ -835,7 +806,11 @@ if (pid == LLDB_INVALID_PROCESS_ID) { KillDebugserverProcess(); + + if (error.Success()) + error.SetErrorStringWithFormat("unable to attach to process named '%s'", process_name); } + return error; } Modified: lldb/trunk/source/Target/Process.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Target/Process.cpp?rev=116693&r1=116692&r2=116693&view=diff ============================================================================== --- lldb/trunk/source/Target/Process.cpp (original) +++ lldb/trunk/source/Target/Process.cpp Sun Oct 17 20:45:30 2010 @@ -1109,6 +1109,12 @@ Process::CompleteAttach () { Error error; + + if (GetID() == LLDB_INVALID_PROCESS_ID) + { + error.SetErrorString("no process"); + } + EventSP event_sp; StateType state = WaitForProcessStopPrivate(NULL, event_sp); if (state == eStateStopped || state == eStateCrashed) @@ -1205,7 +1211,7 @@ if (!wait_for_launch) { ArchSpec attach_spec = GetArchSpecForExistingProcess (process_name); - if (attach_spec != GetTarget().GetArchitecture()) + if (attach_spec.IsValid() && attach_spec != GetTarget().GetArchitecture()) { // Set the architecture on the target. GetTarget().SetArchitecture(attach_spec); 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=116693&r1=116692&r2=116693&view=diff ============================================================================== --- lldb/trunk/tools/debugserver/debugserver.xcodeproj/project.pbxproj (original) +++ lldb/trunk/tools/debugserver/debugserver.xcodeproj/project.pbxproj Sun Oct 17 20:45:30 2010 @@ -369,6 +369,7 @@ isa = PBXProject; buildConfigurationList = 1DEB914E08733D8E0010E9CD /* Build configuration list for PBXProject "debugserver" */; compatibilityVersion = "Xcode 3.1"; + developmentRegion = English; hasScannedForEncodings = 1; knownRegions = ( English, Modified: lldb/trunk/tools/debugserver/source/DNB.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/debugserver/source/DNB.cpp?rev=116693&r1=116692&r2=116693&view=diff ============================================================================== --- lldb/trunk/tools/debugserver/source/DNB.cpp (original) +++ lldb/trunk/tools/debugserver/source/DNB.cpp Sun Oct 17 20:45:30 2010 @@ -433,9 +433,12 @@ } nub_process_t -DNBProcessAttachWait (const char *waitfor_process_name, nub_launch_flavor_t launch_flavor, - struct timespec *timeout_abstime, useconds_t waitfor_interval, - char *err_str, size_t err_len, +DNBProcessAttachWait (const char *waitfor_process_name, + nub_launch_flavor_t launch_flavor, + struct timespec *timeout_abstime, + useconds_t waitfor_interval, + char *err_str, + size_t err_len, DNBShouldCancelCallback should_cancel_callback, void *callback_data) { Modified: lldb/trunk/tools/debugserver/source/RNBRemote.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/debugserver/source/RNBRemote.cpp?rev=116693&r1=116692&r2=116693&view=diff ============================================================================== --- lldb/trunk/tools/debugserver/source/RNBRemote.cpp (original) +++ lldb/trunk/tools/debugserver/source/RNBRemote.cpp Sun Oct 17 20:45:30 2010 @@ -138,6 +138,7 @@ t.push_back (Packet (thread_alive_p, &RNBRemote::HandlePacket_T, NULL, "T", "Is thread alive")); t.push_back (Packet (vattach, &RNBRemote::HandlePacket_v, NULL, "vAttach", "Attach to a new process")); t.push_back (Packet (vattachwait, &RNBRemote::HandlePacket_v, NULL, "vAttachWait", "Wait for a process to start up then attach to it")); + t.push_back (Packet (vattachname, &RNBRemote::HandlePacket_v, NULL, "vAttachName", "Attach to an existing process by name")); t.push_back (Packet (vcont_list_actions, &RNBRemote::HandlePacket_v, NULL, "vCont;", "Verbose resume with thread actions")); t.push_back (Packet (vcont_list_actions, &RNBRemote::HandlePacket_v, NULL, "vCont?", "List valid continue-with-thread-actions actions")); // The X packet doesn't currently work. If/when it does, remove the line above and uncomment out the line below @@ -2551,6 +2552,31 @@ attach_pid = DNBProcessAttachWait(attach_name.c_str (), m_ctx.LaunchFlavor(), NULL, 1000, err_str, sizeof(err_str), RNBRemoteShouldCancelCallback); } + if (strstr (p, "vAttachName;") == p) + { + p += strlen("vAttachName;"); + std::string attach_name; + while (*p != '\0') + { + char smallbuf[3]; + smallbuf[0] = *p; + smallbuf[1] = *(p + 1); + smallbuf[2] = '\0'; + + errno = 0; + int ch = strtoul (smallbuf, NULL, 16); + if (errno != 0 && ch == 0) + { + return HandlePacket_ILLFORMED ("non-hex char in arg on 'vAttachWait' pkt"); + } + + attach_name.push_back(ch); + p += 2; + } + + attach_pid = DNBProcessAttachByName (attach_name.c_str(), NULL, err_str, sizeof(err_str)); + + } else if (strstr (p, "vAttach;") == p) { p += strlen("vAttach;"); Modified: lldb/trunk/tools/debugserver/source/RNBRemote.h URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/debugserver/source/RNBRemote.h?rev=116693&r1=116692&r2=116693&view=diff ============================================================================== --- lldb/trunk/tools/debugserver/source/RNBRemote.h (original) +++ lldb/trunk/tools/debugserver/source/RNBRemote.h Sun Oct 17 20:45:30 2010 @@ -61,8 +61,9 @@ single_step_with_sig, // 'S' search_mem_backwards, // 't' thread_alive_p, // 'T' - vattach, // 'vAttach' - vattachwait, // 'vAttachWait' + vattach, // 'vAttach;pid' + vattachwait, // 'vAttachWait:XX...' where XX is one or more hex encoded process name ASCII bytes + vattachname, // 'vAttachName:XX...' where XX is one or more hex encoded process name ASCII bytes vcont, // 'vCont' vcont_list_actions, // 'vCont?' write_data_to_memory, // 'X' From gclayton at apple.com Sun Oct 17 23:14:23 2010 From: gclayton at apple.com (Greg Clayton) Date: Mon, 18 Oct 2010 04:14:23 -0000 Subject: [Lldb-commits] [lldb] r116697 - in /lldb/trunk: lldb.xcodeproj/project.pbxproj source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp source/Target/Process.cpp tools/darwin-debug/darwin-debug.cpp tools/debugserver/source/MacOSX/MachProcess.cpp tools/debugserver/source/MacOSX/MachProcess.h tools/debugserver/source/MacOSX/MachThreadList.cpp tools/debugserver/source/MacOSX/MachThreadList.h tools/debugserver/source/RNBContext.cpp tools/debugserver/source/RNBRemote.cpp Message-ID: <20101018041423.BB0112A6C12C@llvm.org> Author: gclayton Date: Sun Oct 17 23:14:23 2010 New Revision: 116697 URL: http://llvm.org/viewvc/llvm-project?rev=116697&view=rev Log: Still trying to get detach to work with debugserver. Got a bit closer, but something is still killing our inferior. Fixed an issue with darwin-debug where it wasn't passing all needed arguments to the inferior. Fixed a race condition with the attach to named process code. Modified: lldb/trunk/lldb.xcodeproj/project.pbxproj lldb/trunk/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp lldb/trunk/source/Target/Process.cpp lldb/trunk/tools/darwin-debug/darwin-debug.cpp lldb/trunk/tools/debugserver/source/MacOSX/MachProcess.cpp lldb/trunk/tools/debugserver/source/MacOSX/MachProcess.h lldb/trunk/tools/debugserver/source/MacOSX/MachThreadList.cpp lldb/trunk/tools/debugserver/source/MacOSX/MachThreadList.h lldb/trunk/tools/debugserver/source/RNBContext.cpp lldb/trunk/tools/debugserver/source/RNBRemote.cpp Modified: lldb/trunk/lldb.xcodeproj/project.pbxproj URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/lldb.xcodeproj/project.pbxproj?rev=116697&r1=116696&r2=116697&view=diff ============================================================================== --- lldb/trunk/lldb.xcodeproj/project.pbxproj (original) +++ lldb/trunk/lldb.xcodeproj/project.pbxproj Sun Oct 17 23:14:23 2010 @@ -421,7 +421,7 @@ isa = PBXContainerItemProxy; containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */; proxyType = 1; - remoteGlobalIDString = 26579F67126A25920007C5CB /* darwin-debug */; + remoteGlobalIDString = 26579F67126A25920007C5CB; remoteInfo = "darwin-debug"; }; 266803611160110D008E1FE4 /* PBXContainerItemProxy */ = { 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=116697&r1=116696&r2=116697&view=diff ============================================================================== --- lldb/trunk/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp (original) +++ lldb/trunk/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp Sun Oct 17 23:14:23 2010 @@ -1139,13 +1139,25 @@ { bool timed_out = false; Mutex::Locker locker; + PausePrivateStateThread(); + m_thread_list.DiscardThreadPlans(); + m_debugserver_pid = LLDB_INVALID_PROCESS_ID; 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"); + ResumePrivateStateThread(); } + TimeValue timeout_time; + timeout_time = TimeValue::Now(); + timeout_time.OffsetWithSeconds(2); + + EventSP event_sp; + StateType state = WaitForStateChangedEventsPrivate (&timeout_time, event_sp); + if (state != eStateStopped) + error.SetErrorString("unable to stop target"); } return error; } @@ -1160,30 +1172,26 @@ DisableAllBreakpointSites (); - StringExtractorGDBRemote response; - size_t response_size = m_gdb_comm.SendPacketAndWaitForResponse("D", response, 2, false); - if (response_size) - { - if (response.IsOKPacket()) - { - if (log) - log->Printf ("ProcessGDBRemote::DoDetach() detach was successful"); + m_thread_list.DiscardThreadPlans(); - } - else if (log) - { - log->Printf ("ProcessGDBRemote::DoDestroy() detach failed: %s", response.GetStringRef().c_str()); - } - } - else if (log) + size_t response_size = m_gdb_comm.SendPacket ("D", 1); + if (log) { - log->PutCString ("ProcessGDBRemote::DoDestroy() detach failed for unknown reasons"); + if (response_size) + log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully"); + else + log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed"); } + // Sleep for one second to let the process get all detached... StopAsyncThread (); + m_gdb_comm.StopReadThread(); - KillDebugserverProcess (); m_gdb_comm.Disconnect(); // Disconnect from the debug server. - SetPublicState (eStateDetached); + + SetPrivateState (eStateDetached); + ResumePrivateStateThread(); + + //KillDebugserverProcess (); return error; } @@ -1922,7 +1930,13 @@ usleep (500000); // If our process hasn't yet exited, debugserver might have died. // If the process did exit, the we are reaping it. - if (process->GetState() != eStateExited) + const StateType state = process->GetState(); + + if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID && + state != eStateInvalid && + state != eStateUnloaded && + state != eStateExited && + state != eStateDetached) { char error_str[1024]; if (signo) @@ -1940,15 +1954,12 @@ process->SetExitStatus (-1, error_str); } - else - { - // Debugserver has exited we need to let our ProcessGDBRemote - // know that it no longer has a debugserver instance - process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID; - // We are returning true to this function below, so we can - // forget about the monitor handle. - process->m_debugserver_thread = LLDB_INVALID_HOST_THREAD; - } + // Debugserver has exited we need to let our ProcessGDBRemote + // know that it no longer has a debugserver instance + process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID; + // We are returning true to this function below, so we can + // forget about the monitor handle. + process->m_debugserver_thread = LLDB_INVALID_HOST_THREAD; } return true; } Modified: lldb/trunk/source/Target/Process.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Target/Process.cpp?rev=116697&r1=116696&r2=116697&view=diff ============================================================================== --- lldb/trunk/source/Target/Process.cpp (original) +++ lldb/trunk/source/Target/Process.cpp Sun Oct 17 23:14:23 2010 @@ -1222,7 +1222,6 @@ if (error.Success()) { SetPublicState (eStateAttaching); - StartPrivateStateThread(); error = DoAttachToProcessWithName (process_name, wait_for_launch); if (error.Fail()) { @@ -1635,7 +1634,9 @@ HandlePrivateEvent (event_sp); } - if (internal_state == eStateInvalid || internal_state == eStateExited) + if (internal_state == eStateInvalid || + internal_state == eStateExited || + internal_state == eStateDetached ) break; } Modified: lldb/trunk/tools/darwin-debug/darwin-debug.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/darwin-debug/darwin-debug.cpp?rev=116697&r1=116696&r2=116697&view=diff ============================================================================== --- lldb/trunk/tools/darwin-debug/darwin-debug.cpp (original) +++ lldb/trunk/tools/darwin-debug/darwin-debug.cpp Sun Oct 17 23:14:23 2010 @@ -87,10 +87,12 @@ } pid_t -posix_spawn_for_debug (const char *path, char *const *argv, char *const *envp, cpu_type_t cpu_type, int disable_aslr) +posix_spawn_for_debug (char *const *argv, char *const *envp, cpu_type_t cpu_type, int disable_aslr) { pid_t pid = 0; + const char *path = argv[0]; + posix_spawnattr_t attr; exit_with_errno (::posix_spawnattr_init (&attr), "::posix_spawnattr_init (&attr) error: "); @@ -203,13 +205,7 @@ printf ("argv[%u] = '%s'\n", i, argv[i]); #endif - const char *exe_path = argv[0]; - - // Skip this inferior program name... - ++argv; - - posix_spawn_for_debug (exe_path, - argv, + posix_spawn_for_debug (argv, pass_env ? envp : NULL, cpu_type, disable_aslr); 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=116697&r1=116696&r2=116697&view=diff ============================================================================== --- lldb/trunk/tools/debugserver/source/MacOSX/MachProcess.cpp (original) +++ lldb/trunk/tools/debugserver/source/MacOSX/MachProcess.cpp Sun Oct 17 23:14:23 2010 @@ -101,7 +101,7 @@ m_stdio_thread (0), m_stdio_mutex (PTHREAD_MUTEX_RECURSIVE), m_stdout_data (), - m_threadList (), + m_thread_list (), m_exception_messages (), m_exception_messages_mutex (PTHREAD_MUTEX_RECURSIVE), m_state (eStateUnloaded), @@ -147,62 +147,62 @@ const char * MachProcess::ThreadGetName(nub_thread_t tid) { - return m_threadList.GetName(tid); + return m_thread_list.GetName(tid); } nub_state_t MachProcess::ThreadGetState(nub_thread_t tid) { - return m_threadList.GetState(tid); + return m_thread_list.GetState(tid); } nub_size_t MachProcess::GetNumThreads () const { - return m_threadList.NumThreads(); + return m_thread_list.NumThreads(); } nub_thread_t MachProcess::GetThreadAtIndex (nub_size_t thread_idx) const { - return m_threadList.ThreadIDAtIndex(thread_idx); + return m_thread_list.ThreadIDAtIndex(thread_idx); } uint32_t MachProcess::GetThreadIndexFromThreadID (nub_thread_t tid) { - return m_threadList.GetThreadIndexByID(tid); + return m_thread_list.GetThreadIndexByID(tid); } nub_thread_t MachProcess::GetCurrentThread () { - return m_threadList.CurrentThreadID(); + return m_thread_list.CurrentThreadID(); } nub_thread_t MachProcess::SetCurrentThread(nub_thread_t tid) { - return m_threadList.SetCurrentThread(tid); + return m_thread_list.SetCurrentThread(tid); } bool MachProcess::GetThreadStoppedReason(nub_thread_t tid, struct DNBThreadStopInfo *stop_info) const { - return m_threadList.GetThreadStoppedReason(tid, stop_info); + return m_thread_list.GetThreadStoppedReason(tid, stop_info); } void MachProcess::DumpThreadStoppedReason(nub_thread_t tid) const { - return m_threadList.DumpThreadStoppedReason(tid); + return m_thread_list.DumpThreadStoppedReason(tid); } const char * MachProcess::GetThreadInfo(nub_thread_t tid) const { - return m_threadList.GetThreadInfo(tid); + return m_thread_list.GetThreadInfo(tid); } const DNBRegisterSetInfo * @@ -214,13 +214,13 @@ bool MachProcess::GetRegisterValue ( nub_thread_t tid, uint32_t set, uint32_t reg, DNBRegisterValue *value ) const { - return m_threadList.GetRegisterValue(tid, set, reg, value); + return m_thread_list.GetRegisterValue(tid, set, reg, value); } bool MachProcess::SetRegisterValue ( nub_thread_t tid, uint32_t set, uint32_t reg, const DNBRegisterValue *value ) const { - return m_threadList.SetRegisterValue(tid, set, reg, value); + return m_thread_list.SetRegisterValue(tid, set, reg, value); } void @@ -273,7 +273,7 @@ SetState(eStateUnloaded); m_flags = eMachProcessFlagsNone; m_stop_count = 0; - m_threadList.Clear(); + m_thread_list.Clear(); { PTHREAD_MUTEX_LOCKER(locker, m_exception_messages_mutex); m_exception_messages.clear(); @@ -373,7 +373,13 @@ clear_bps_and_wps = false; } - // Resume our process + // If we already have a thread stopped due to a SIGSTOP, we don't have + // to do anything... + if (m_thread_list.GetThreadIndexForThreadStoppedWithSignal (SIGSTOP) != UINT32_MAX) + return GetState(); + + // No threads were stopped with a SIGSTOP, we need to run and halt the + // process with a signal DNBLogThreadedIf(LOG_PROCESS, "MachProcess::DoSIGSTOP() state = %s -- resuming process", DNBStateAsString (state)); PrivateResume (DNBThreadResumeActions (eStateRunning, 0)); @@ -406,11 +412,15 @@ nub_state_t state = DoSIGSTOP(true); DNBLogThreadedIf(LOG_PROCESS, "MachProcess::Detach() DoSIGSTOP() returned %s", DNBStateAsString(state)); + { + DNBThreadResumeActions thread_actions (eStateRunning, 0); + PTHREAD_MUTEX_LOCKER (locker, m_exception_messages_mutex); - // Don't reply to our SIGSTOP exception, just make sure no threads - // are still suspended. - PrivateResume (DNBThreadResumeActions (eStateRunning, 0)); + ReplyToAllExceptions (thread_actions); + + } + m_task.ShutDownExcecptionThread(); // Detach from our process errno = 0; @@ -423,13 +433,14 @@ // Resume our task m_task.Resume(); - SetState(eStateDetached); - // NULL our task out as we have already retored all exception ports m_task.Clear(); // Clear out any notion of the process we once were Clear(); + + SetState(eStateDetached); + return true; } @@ -604,7 +615,7 @@ // Let the thread prepare to resume and see if any threads want us to // step over a breakpoint instruction (ProcessWillResume will modify // the value of stepOverBreakInstruction). - m_threadList.ProcessWillResume (this, thread_actions); + m_thread_list.ProcessWillResume (this, thread_actions); // Set our state accordingly if (thread_actions.NumActionsWithState(eStateStepping)) @@ -718,7 +729,7 @@ if (bp->IsHardware()) { - bool hw_disable_result = m_threadList.DisableHardwareBreakpoint (bp); + bool hw_disable_result = m_thread_list.DisableHardwareBreakpoint (bp); if (hw_disable_result == true) { @@ -726,7 +737,7 @@ // Let the thread list know that a breakpoint has been modified if (remove) { - m_threadList.NotifyBreakpointChanged(bp); + m_thread_list.NotifyBreakpointChanged(bp); m_breakpoints.Remove(breakID); } DNBLogThreadedIf(LOG_BREAKPOINTS, "MachProcess::DisableBreakpoint ( breakID = %d, remove = %d ) addr = 0x%8.8llx (hardware) => success", breakID, remove, (uint64_t)addr); @@ -794,7 +805,7 @@ // Let the thread list know that a breakpoint has been modified if (remove) { - m_threadList.NotifyBreakpointChanged(bp); + m_thread_list.NotifyBreakpointChanged(bp); m_breakpoints.Remove(breakID); } DNBLogThreadedIf(LOG_BREAKPOINTS, "MachProcess::DisableBreakpoint ( breakID = %d, remove = %d ) addr = 0x%8.8llx => success", breakID, remove, (uint64_t)addr); @@ -839,7 +850,7 @@ if (wp->IsHardware()) { - bool hw_disable_result = m_threadList.DisableHardwareWatchpoint (wp); + bool hw_disable_result = m_thread_list.DisableHardwareWatchpoint (wp); if (hw_disable_result == true) { @@ -916,7 +927,7 @@ { if (bp->HardwarePreferred()) { - bp->SetHardwareIndex(m_threadList.EnableHardwareBreakpoint(bp)); + bp->SetHardwareIndex(m_thread_list.EnableHardwareBreakpoint(bp)); if (bp->IsHardware()) { bp->SetEnabled(true); @@ -942,7 +953,7 @@ { bp->SetEnabled(true); // Let the thread list know that a breakpoint has been modified - m_threadList.NotifyBreakpointChanged(bp); + m_thread_list.NotifyBreakpointChanged(bp); DNBLogThreadedIf(LOG_BREAKPOINTS, "MachProcess::EnableBreakpoint ( breakID = %d ) addr = 0x%8.8llx: SUCCESS.", breakID, (uint64_t)addr); return true; } @@ -991,7 +1002,7 @@ else { // Currently only try and set hardware watchpoints. - wp->SetHardwareIndex(m_threadList.EnableHardwareWatchpoint(wp)); + wp->SetHardwareIndex(m_thread_list.EnableHardwareWatchpoint(wp)); if (wp->IsHardware()) { wp->SetEnabled(true); @@ -1031,7 +1042,7 @@ { // Let all threads recover from stopping and do any clean up based // on the previous thread state (if any). - m_threadList.ProcessDidStop(this); + m_thread_list.ProcessDidStop(this); // Let each thread know of any exceptions task_t task = m_task.TaskPort(); @@ -1041,16 +1052,16 @@ // Let the thread list figure use the MachProcess to forward all exceptions // on down to each thread. if (m_exception_messages[i].state.task_port == task) - m_threadList.NotifyException(m_exception_messages[i].state); + m_thread_list.NotifyException(m_exception_messages[i].state); if (DNBLogCheckLogBit(LOG_EXCEPTIONS)) m_exception_messages[i].Dump(); } if (DNBLogCheckLogBit(LOG_THREAD)) - m_threadList.Dump(); + m_thread_list.Dump(); bool step_more = false; - if (m_threadList.ShouldStop(step_more)) + if (m_thread_list.ShouldStop(step_more)) { // Wait for the eEventProcessRunningStateChanged event to be reset // before changing state to stopped to avoid race condition with 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=116697&r1=116696&r2=116697&view=diff ============================================================================== --- lldb/trunk/tools/debugserver/source/MacOSX/MachProcess.h (original) +++ lldb/trunk/tools/debugserver/source/MacOSX/MachProcess.h Sun Oct 17 23:14:23 2010 @@ -141,7 +141,7 @@ uint32_t GetThreadIndexFromThreadID (nub_thread_t tid); nub_thread_t GetCurrentThread (); nub_thread_t SetCurrentThread (nub_thread_t tid); - MachThreadList & GetThreadList() { return m_threadList; } + MachThreadList & GetThreadList() { return m_thread_list; } bool GetThreadStoppedReason(nub_thread_t tid, struct DNBThreadStopInfo *stop_info) const; void DumpThreadStoppedReason(nub_thread_t tid) const; const char * GetThreadInfo (nub_thread_t tid) const; @@ -243,7 +243,7 @@ m_exception_messages; // A collection of exception messages caught when listening to the exception port PThreadMutex m_exception_messages_mutex; // Multithreaded protection for m_exception_messages - MachThreadList m_threadList; // A list of threads that is maintained/updated after each stop + MachThreadList m_thread_list; // A list of threads that is maintained/updated after each stop nub_state_t m_state; // The state of our process PThreadMutex m_state_mutex; // Multithreaded protection for m_state PThreadEvent m_events; // Process related events in the child processes lifetime can be waited upon 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=116697&r1=116696&r2=116697&view=diff ============================================================================== --- lldb/trunk/tools/debugserver/source/MacOSX/MachThreadList.cpp (original) +++ lldb/trunk/tools/debugserver/source/MacOSX/MachThreadList.cpp Sun Oct 17 23:14:23 2010 @@ -429,4 +429,17 @@ return false; } +uint32_t +MachThreadList::GetThreadIndexForThreadStoppedWithSignal (const int signo) const +{ + uint32_t should_stop = false; + const uint32_t num_threads = m_threads.size(); + uint32_t idx = 0; + for (idx = 0; !should_stop && idx < num_threads; ++idx) + { + if (m_threads[idx]->GetStopException().SoftSignal () == signo) + return idx; + } + return UINT32_MAX; +} 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=116697&r1=116696&r2=116697&view=diff ============================================================================== --- lldb/trunk/tools/debugserver/source/MacOSX/MachThreadList.h (original) +++ lldb/trunk/tools/debugserver/source/MacOSX/MachThreadList.h Sun Oct 17 23:14:23 2010 @@ -53,6 +53,7 @@ bool DisableHardwareBreakpoint (const DNBBreakpoint *bp) const; uint32_t EnableHardwareWatchpoint (const DNBBreakpoint *wp) const; bool DisableHardwareWatchpoint (const DNBBreakpoint *wp) const; + uint32_t GetThreadIndexForThreadStoppedWithSignal (const int signo) const; protected: typedef std::vector collection; Modified: lldb/trunk/tools/debugserver/source/RNBContext.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/debugserver/source/RNBContext.cpp?rev=116697&r1=116696&r2=116697&view=diff ============================================================================== --- lldb/trunk/tools/debugserver/source/RNBContext.cpp (original) +++ lldb/trunk/tools/debugserver/source/RNBContext.cpp Sun Oct 17 23:14:23 2010 @@ -167,6 +167,7 @@ case eStateInvalid: case eStateExited: + case eStateDetached: done = true; break; } Modified: lldb/trunk/tools/debugserver/source/RNBRemote.cpp URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/debugserver/source/RNBRemote.cpp?rev=116697&r1=116696&r2=116697&view=diff ============================================================================== --- lldb/trunk/tools/debugserver/source/RNBRemote.cpp (original) +++ lldb/trunk/tools/debugserver/source/RNBRemote.cpp Sun Oct 17 23:14:23 2010 @@ -3064,7 +3064,8 @@ rnb_err_t RNBRemote::HandlePacket_D (const char *p) { - SendPacket ("OK"); + // We are not supposed to send a response for deatch. + //SendPacket ("OK"); if (m_ctx.HasValidProcessID()) DNBProcessDetach(m_ctx.ProcessID()); return rnb_success;